Compare commits
47
Commits
4115646d66
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b7a0934f83 | ||
|
|
e5cbc3e4d4 | ||
|
|
08983814b5 | ||
|
|
4c7ca94ee4 | ||
|
|
56f10f7c29 | ||
|
|
ce00bc84b5 | ||
|
|
cfbc74d882 | ||
|
|
741fce0adb | ||
|
|
1d8037adf1 | ||
|
|
4f70e07cb7 | ||
|
|
1db1d1d1d6 | ||
|
|
1df1cd54f8 | ||
|
|
fafacec781 | ||
|
|
89eafb8770 | ||
|
|
9a17502d29 | ||
|
|
2935a526c7 | ||
|
|
3ef86b0b66 | ||
|
|
d18e36e962 | ||
|
|
63a4aeace7 | ||
|
|
a6c1acbc31 | ||
|
|
e24bb60627 | ||
|
|
67b4032ff0 | ||
|
|
8668234065 | ||
|
|
1a7a1cca68 | ||
|
|
a69e86f2bc | ||
|
|
77ba93b94a | ||
|
|
d4e7cb6e8b | ||
|
|
df0e43d884 | ||
|
|
d35843a8e2 | ||
|
|
1e2f1695ce | ||
|
|
897e2092a3 | ||
|
|
3460a93eaf | ||
|
|
02538ae300 | ||
|
|
43662a86d8 | ||
|
|
304f157b91 | ||
|
|
bc36a8f0f0 | ||
|
|
38cb97d86a | ||
|
|
9d43cc266c | ||
|
|
f447e0c6ab | ||
|
|
ca7258d8d1 | ||
|
|
ad1a775bc1 | ||
|
|
1ba87c0fe1 | ||
|
|
e1164e0b47 | ||
|
|
770c198ccd | ||
|
|
256d776131 | ||
|
|
1f2805be23 | ||
|
|
34ae20476f |
No files matched your search
@@ -20,11 +20,13 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@infisical/sdk": "^5.0.2",
|
"@infisical/sdk": "^5.0.2",
|
||||||
|
"@nestjs/bullmq": "^11.0.4",
|
||||||
"@nestjs/common": "^11.0.1",
|
"@nestjs/common": "^11.0.1",
|
||||||
"@nestjs/config": "^4.0.4",
|
"@nestjs/config": "^4.0.4",
|
||||||
"@nestjs/core": "^11.0.1",
|
"@nestjs/core": "^11.0.1",
|
||||||
"@nestjs/platform-express": "^11.0.1",
|
"@nestjs/platform-express": "^11.0.1",
|
||||||
"@persona-lenz/shared": "workspace:*",
|
"@persona-lenz/shared": "workspace:*",
|
||||||
|
"bullmq": "^5.79.2",
|
||||||
"mongoose": "^9.7.3",
|
"mongoose": "^9.7.3",
|
||||||
"redis": "^5.12.1",
|
"redis": "^5.12.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
|
|||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { bootstrap } from './app.bootstrap';
|
||||||
|
import { configureApp } from './app.setup';
|
||||||
|
|
||||||
|
type ListenFunction = (port: string | number) => Promise<void>;
|
||||||
|
|
||||||
|
jest.mock('@nestjs/core', () => ({
|
||||||
|
NestFactory: {
|
||||||
|
create: jest.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
jest.mock('./app.setup', () => ({
|
||||||
|
API_GLOBAL_PREFIX: 'api',
|
||||||
|
configureApp: jest.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('bootstrap', () => {
|
||||||
|
const originalPort = process.env.PORT;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.env.PORT = originalPort;
|
||||||
|
jest.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('applies shared app setup before listening', async () => {
|
||||||
|
process.env.PORT = '3123';
|
||||||
|
|
||||||
|
const mockListen = jest
|
||||||
|
.fn<ReturnType<ListenFunction>, Parameters<ListenFunction>>()
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
const mockApp = { listen: mockListen };
|
||||||
|
const mockedNestFactory = NestFactory as unknown as {
|
||||||
|
create: jest.MockedFunction<() => Promise<typeof mockApp>>;
|
||||||
|
};
|
||||||
|
mockedNestFactory.create.mockResolvedValue(mockApp);
|
||||||
|
|
||||||
|
await bootstrap();
|
||||||
|
|
||||||
|
expect(configureApp).toHaveBeenCalledWith(mockApp);
|
||||||
|
expect(mockListen).toHaveBeenCalledWith('3123');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { NestFactory } from '@nestjs/core';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
import { configureApp } from './app.setup';
|
||||||
|
|
||||||
|
export async function bootstrap(): Promise<void> {
|
||||||
|
const app = await NestFactory.create(AppModule);
|
||||||
|
configureApp(app);
|
||||||
|
await app.listen(process.env.PORT ?? 3000);
|
||||||
|
}
|
||||||
@@ -14,9 +14,9 @@ describe('AppController', () => {
|
|||||||
appController = app.get<AppController>(AppController);
|
appController = app.get<AppController>(AppController);
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('root', () => {
|
describe('health', () => {
|
||||||
it('should return "Hello World!"', () => {
|
it('returns the API health status', () => {
|
||||||
expect(appController.getHello()).toBe('Hello World!');
|
expect(appController.getHealth()).toEqual({ status: 'ok' });
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
import { Controller, Get } from '@nestjs/common';
|
import { Controller, Get } from '@nestjs/common';
|
||||||
import { AppService } from './app.service';
|
import { AppService, type HealthResponse } from './app.service';
|
||||||
|
|
||||||
@Controller()
|
@Controller('health')
|
||||||
export class AppController {
|
export class AppController {
|
||||||
constructor(private readonly appService: AppService) {}
|
constructor(private readonly appService: AppService) {}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
getHello(): string {
|
getHealth(): HealthResponse {
|
||||||
return this.appService.getHello();
|
return this.appService.getHealth();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import { getQueueToken } from '@nestjs/bullmq';
|
||||||
|
import { Test } from '@nestjs/testing';
|
||||||
|
import { AppModule } from './app.module';
|
||||||
|
import { AnalysisQueueService } from './modules/analysis/analysis-queue.service';
|
||||||
|
import {
|
||||||
|
ANALYSIS_QUEUE_NAME,
|
||||||
|
SEED_COLLECTION_QUEUE_NAME,
|
||||||
|
} from './modules/analysis/analysis.constants';
|
||||||
|
import { ConnectionService } from './modules/global/database/connection.service';
|
||||||
|
import { REDIS_CLIENT } from './modules/global/redis/redis.constants';
|
||||||
|
import { SecretService } from './modules/global/secret/secret.service';
|
||||||
|
|
||||||
|
function createSecretServiceStub() {
|
||||||
|
return {
|
||||||
|
get: jest.fn((key: string) => {
|
||||||
|
if (key === 'REDIS_URL')
|
||||||
|
return Promise.resolve('redis://localhost:6379/0');
|
||||||
|
return Promise.resolve('');
|
||||||
|
}),
|
||||||
|
ready: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AppModule', () => {
|
||||||
|
it('compiles with the analysis queue module wired', async () => {
|
||||||
|
const moduleRef = await Test.createTestingModule({
|
||||||
|
imports: [AppModule],
|
||||||
|
})
|
||||||
|
.overrideProvider(SecretService)
|
||||||
|
.useValue(createSecretServiceStub())
|
||||||
|
.overrideProvider(ConnectionService)
|
||||||
|
.useValue({})
|
||||||
|
.overrideProvider(REDIS_CLIENT)
|
||||||
|
.useValue({
|
||||||
|
destroy: jest.fn(),
|
||||||
|
quit: jest.fn().mockResolvedValue(undefined),
|
||||||
|
})
|
||||||
|
.overrideProvider(getQueueToken(ANALYSIS_QUEUE_NAME))
|
||||||
|
.useValue({
|
||||||
|
add: jest.fn(),
|
||||||
|
})
|
||||||
|
.overrideProvider(getQueueToken(SEED_COLLECTION_QUEUE_NAME))
|
||||||
|
.useValue({
|
||||||
|
add: jest.fn(),
|
||||||
|
})
|
||||||
|
.compile();
|
||||||
|
|
||||||
|
expect(moduleRef.get(AnalysisQueueService)).toBeInstanceOf(
|
||||||
|
AnalysisQueueService,
|
||||||
|
);
|
||||||
|
|
||||||
|
await moduleRef.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,10 +1,11 @@
|
|||||||
import { Module } from '@nestjs/common';
|
import { Module } from '@nestjs/common';
|
||||||
import { AppController } from './app.controller';
|
import { AppController } from './app.controller';
|
||||||
import { AppService } from './app.service';
|
import { AppService } from './app.service';
|
||||||
|
import { AnalysisModule } from './modules/analysis/analysis.module';
|
||||||
import { GlobalModule } from './modules/global/global.module';
|
import { GlobalModule } from './modules/global/global.module';
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [GlobalModule],
|
imports: [GlobalModule, AnalysisModule],
|
||||||
controllers: [AppController],
|
controllers: [AppController],
|
||||||
providers: [AppService],
|
providers: [AppService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
import { Injectable } from '@nestjs/common';
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
export interface HealthResponse {
|
||||||
|
status: 'ok';
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class AppService {
|
export class AppService {
|
||||||
getHello(): string {
|
getHealth(): HealthResponse {
|
||||||
return 'Hello World!';
|
return { status: 'ok' };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
import type { INestApplication } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const API_GLOBAL_PREFIX = 'api';
|
||||||
|
|
||||||
|
export function configureApp(app: INestApplication): void {
|
||||||
|
app.setGlobalPrefix(API_GLOBAL_PREFIX);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { bootstrap } from './app.bootstrap';
|
||||||
|
import './main';
|
||||||
|
|
||||||
|
jest.mock('./app.bootstrap', () => ({
|
||||||
|
bootstrap: jest.fn().mockResolvedValue(undefined),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe('main', () => {
|
||||||
|
it('starts the Nest application bootstrap', () => {
|
||||||
|
expect(bootstrap).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,8 +1,3 @@
|
|||||||
import { NestFactory } from '@nestjs/core';
|
import { bootstrap } from './app.bootstrap';
|
||||||
import { AppModule } from './app.module';
|
|
||||||
|
|
||||||
async function bootstrap() {
|
|
||||||
const app = await NestFactory.create(AppModule);
|
|
||||||
await app.listen(process.env.PORT ?? 3000);
|
|
||||||
}
|
|
||||||
void bootstrap();
|
void bootstrap();
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,455 @@
|
|||||||
|
import type { AnalysisJob } from '../global/database/schemas';
|
||||||
|
import type { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type {
|
||||||
|
BaselineComputationJobData,
|
||||||
|
SeedCollectionJobData,
|
||||||
|
UserAnalysisJobData,
|
||||||
|
} from './analysis.types';
|
||||||
|
import {
|
||||||
|
BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
DEFAULT_SEED_COLLECTION_MATCH_COUNT,
|
||||||
|
FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
SEED_COLLECTION_JOB_NAME,
|
||||||
|
USER_ANALYSIS_JOB_NAME,
|
||||||
|
} from './analysis.constants';
|
||||||
|
import { AnalysisQueueService } from './analysis-queue.service';
|
||||||
|
|
||||||
|
function createJobData(
|
||||||
|
overrides: Partial<UserAnalysisJobData> = {},
|
||||||
|
): UserAnalysisJobData {
|
||||||
|
return {
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
platformRoute: 'kr',
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount: 20,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createFindOneChain(
|
||||||
|
result: Pick<AnalysisJob, 'jobId' | 'status'> | null,
|
||||||
|
) {
|
||||||
|
const exec = jest
|
||||||
|
.fn<Promise<Pick<AnalysisJob, 'jobId' | 'status'> | null>, []>()
|
||||||
|
.mockResolvedValue(result);
|
||||||
|
const lean = jest.fn(() => ({ exec }));
|
||||||
|
const sort = jest.fn(() => ({ lean }));
|
||||||
|
return {
|
||||||
|
chain: { sort },
|
||||||
|
exec,
|
||||||
|
lean,
|
||||||
|
sort,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSeedCollectionJobData(
|
||||||
|
overrides: Partial<SeedCollectionJobData> = {},
|
||||||
|
): SeedCollectionJobData {
|
||||||
|
return {
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: 50,
|
||||||
|
grandmaster: 50,
|
||||||
|
master: 50,
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBaselineComputationJobData(
|
||||||
|
overrides: Partial<BaselineComputationJobData> = {},
|
||||||
|
): BaselineComputationJobData {
|
||||||
|
return {
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
cohort: 'MASTER_PLUS',
|
||||||
|
patch: 'ALL',
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AnalysisQueueService', () => {
|
||||||
|
it('creates an analysis job document and enqueues a BullMQ job', async () => {
|
||||||
|
const add = jest.fn().mockResolvedValue({ id: 'job-from-bull' });
|
||||||
|
const seedAdd = jest.fn();
|
||||||
|
const findOneChain = createFindOneChain(null);
|
||||||
|
const create = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue({}),
|
||||||
|
}));
|
||||||
|
const analysisJobModel = {
|
||||||
|
create,
|
||||||
|
findOne: jest.fn(() => findOneChain.chain),
|
||||||
|
updateOne,
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add } as never,
|
||||||
|
{ add: seedAdd } as never,
|
||||||
|
connectionService,
|
||||||
|
() => 'analysis-job-1',
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await service.enqueueUserAnalysis(createJobData());
|
||||||
|
|
||||||
|
expect(result).toEqual({ jobId: 'analysis-job-1', status: 'queued' });
|
||||||
|
expect(create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
jobType: USER_ANALYSIS_JOB_NAME,
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
status: 'queued',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(add).toHaveBeenCalledWith(
|
||||||
|
USER_ANALYSIS_JOB_NAME,
|
||||||
|
createJobData(),
|
||||||
|
expect.objectContaining({
|
||||||
|
attempts: 2,
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(seedAdd).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a feature recompute job document and enqueues a BullMQ job', async () => {
|
||||||
|
const add = jest.fn().mockResolvedValue({ id: 'job-from-bull' });
|
||||||
|
const seedAdd = jest.fn();
|
||||||
|
const create = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue({}),
|
||||||
|
}));
|
||||||
|
const analysisJobModel = {
|
||||||
|
create,
|
||||||
|
updateOne,
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add } as never,
|
||||||
|
{ add: seedAdd } as never,
|
||||||
|
connectionService,
|
||||||
|
() => 'recompute-job-1',
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await service.enqueueFeatureRecompute({
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
batchSize: 25,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toEqual({ jobId: 'recompute-job-1', status: 'queued' });
|
||||||
|
expect(create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
jobId: 'recompute-job-1',
|
||||||
|
jobType: FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount: 0,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
status: 'queued',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(add).toHaveBeenCalledWith(
|
||||||
|
FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
{
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
batchSize: 25,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
},
|
||||||
|
expect.objectContaining({
|
||||||
|
attempts: 1,
|
||||||
|
jobId: 'recompute-job-1',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(seedAdd).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a seed collection job document and enqueues the seed queue', async () => {
|
||||||
|
const analysisAdd = jest.fn();
|
||||||
|
const seedAdd = jest.fn().mockResolvedValue({ id: 'job-from-bull' });
|
||||||
|
const create = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue({}),
|
||||||
|
}));
|
||||||
|
const analysisJobModel = {
|
||||||
|
create,
|
||||||
|
updateOne,
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add: analysisAdd } as never,
|
||||||
|
{ add: seedAdd } as never,
|
||||||
|
connectionService,
|
||||||
|
() => 'seed-job-1',
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await service.enqueueSeedCollection(
|
||||||
|
createSeedCollectionJobData(),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toEqual({ jobId: 'seed-job-1', status: 'queued' });
|
||||||
|
expect(create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
jobId: 'seed-job-1',
|
||||||
|
jobType: SEED_COLLECTION_JOB_NAME,
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount: DEFAULT_SEED_COLLECTION_MATCH_COUNT,
|
||||||
|
status: 'queued',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(seedAdd).toHaveBeenCalledWith(
|
||||||
|
SEED_COLLECTION_JOB_NAME,
|
||||||
|
createSeedCollectionJobData(),
|
||||||
|
expect.objectContaining({
|
||||||
|
attempts: 1,
|
||||||
|
jobId: 'seed-job-1',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(analysisAdd).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates a baseline computation job document and enqueues an analysis queue job', async () => {
|
||||||
|
const add = jest.fn().mockResolvedValue({ id: 'job-from-bull' });
|
||||||
|
const seedAdd = jest.fn();
|
||||||
|
const create = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue({}),
|
||||||
|
}));
|
||||||
|
const analysisJobModel = {
|
||||||
|
create,
|
||||||
|
updateOne,
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add } as never,
|
||||||
|
{ add: seedAdd } as never,
|
||||||
|
connectionService,
|
||||||
|
() => 'baseline-job-1',
|
||||||
|
);
|
||||||
|
|
||||||
|
const result = await service.enqueueBaselineComputation(
|
||||||
|
createBaselineComputationJobData(),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toEqual({ jobId: 'baseline-job-1', status: 'queued' });
|
||||||
|
expect(create).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
jobId: 'baseline-job-1',
|
||||||
|
jobType: BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount: 0,
|
||||||
|
status: 'queued',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(add).toHaveBeenCalledWith(
|
||||||
|
BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
createBaselineComputationJobData(),
|
||||||
|
expect.objectContaining({
|
||||||
|
attempts: 1,
|
||||||
|
jobId: 'baseline-job-1',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(seedAdd).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an existing active job instead of enqueueing a duplicate', async () => {
|
||||||
|
const add = jest.fn();
|
||||||
|
const findOneChain = createFindOneChain({
|
||||||
|
jobId: 'existing-job',
|
||||||
|
status: 'processing',
|
||||||
|
});
|
||||||
|
const analysisJobModel = {
|
||||||
|
create: jest.fn(),
|
||||||
|
findOne: jest.fn(() => findOneChain.chain),
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add } as never,
|
||||||
|
{ add: jest.fn() } as never,
|
||||||
|
connectionService,
|
||||||
|
() => 'new-job',
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(service.enqueueUserAnalysis(createJobData())).resolves.toEqual(
|
||||||
|
{
|
||||||
|
jobId: 'existing-job',
|
||||||
|
status: 'processing',
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(add).not.toHaveBeenCalled();
|
||||||
|
expect(analysisJobModel.create).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks the pre-created job failed when BullMQ enqueue fails', async () => {
|
||||||
|
const add = jest.fn().mockRejectedValue(new Error('redis unavailable'));
|
||||||
|
const findOneChain = createFindOneChain(null);
|
||||||
|
const create = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue({}),
|
||||||
|
}));
|
||||||
|
const analysisJobModel = {
|
||||||
|
create,
|
||||||
|
findOne: jest.fn(() => findOneChain.chain),
|
||||||
|
updateOne,
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add } as never,
|
||||||
|
{ add: jest.fn() } as never,
|
||||||
|
connectionService,
|
||||||
|
() => 'analysis-job-1',
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(service.enqueueUserAnalysis(createJobData())).rejects.toThrow(
|
||||||
|
'redis unavailable',
|
||||||
|
);
|
||||||
|
expect(updateOne).toHaveBeenCalledWith(
|
||||||
|
{ jobId: 'analysis-job-1' },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'failed',
|
||||||
|
stage: 'enqueue',
|
||||||
|
error: 'Analysis could not be queued.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks a pre-created feature recompute job failed when BullMQ enqueue fails', async () => {
|
||||||
|
const add = jest.fn().mockRejectedValue(new Error('redis unavailable'));
|
||||||
|
const create = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue({}),
|
||||||
|
}));
|
||||||
|
const analysisJobModel = {
|
||||||
|
create,
|
||||||
|
updateOne,
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add } as never,
|
||||||
|
{ add: jest.fn() } as never,
|
||||||
|
connectionService,
|
||||||
|
() => 'recompute-job-1',
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.enqueueFeatureRecompute({
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
batchSize: 25,
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('redis unavailable');
|
||||||
|
expect(updateOne).toHaveBeenCalledWith(
|
||||||
|
{ jobId: 'recompute-job-1' },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'failed',
|
||||||
|
stage: 'enqueue',
|
||||||
|
error: 'Analysis could not be queued.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks a pre-created seed collection job failed when BullMQ enqueue fails', async () => {
|
||||||
|
const analysisAdd = jest.fn();
|
||||||
|
const seedAdd = jest.fn().mockRejectedValue(new Error('redis unavailable'));
|
||||||
|
const create = jest.fn().mockResolvedValue({});
|
||||||
|
const updateOne = jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue({}),
|
||||||
|
}));
|
||||||
|
const analysisJobModel = {
|
||||||
|
create,
|
||||||
|
updateOne,
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add: analysisAdd } as never,
|
||||||
|
{ add: seedAdd } as never,
|
||||||
|
connectionService,
|
||||||
|
() => 'seed-job-1',
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.enqueueSeedCollection(createSeedCollectionJobData()),
|
||||||
|
).rejects.toThrow('redis unavailable');
|
||||||
|
expect(updateOne).toHaveBeenCalledWith(
|
||||||
|
{ jobId: 'seed-job-1' },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'failed',
|
||||||
|
stage: 'enqueue',
|
||||||
|
error: 'Analysis could not be queued.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(analysisAdd).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serializes identical in-process requests before creating a duplicate job', async () => {
|
||||||
|
const add = jest.fn().mockResolvedValue({ id: 'analysis-job-1' });
|
||||||
|
let activeJob: Pick<AnalysisJob, 'jobId' | 'status'> | null = null;
|
||||||
|
const findOne = jest.fn(() => ({
|
||||||
|
sort: jest.fn(() => ({
|
||||||
|
lean: jest.fn(() => ({
|
||||||
|
exec: jest
|
||||||
|
.fn<Promise<Pick<AnalysisJob, 'jobId' | 'status'> | null>, []>()
|
||||||
|
.mockImplementation(() => Promise.resolve(activeJob)),
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
}));
|
||||||
|
const create = jest.fn().mockImplementation(() => {
|
||||||
|
activeJob = { jobId: 'analysis-job-1', status: 'queued' };
|
||||||
|
return Promise.resolve({});
|
||||||
|
});
|
||||||
|
const analysisJobModel = {
|
||||||
|
create,
|
||||||
|
findOne,
|
||||||
|
updateOne: jest.fn(),
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(analysisJobModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new AnalysisQueueService(
|
||||||
|
{ add } as never,
|
||||||
|
{ add: jest.fn() } as never,
|
||||||
|
connectionService,
|
||||||
|
() => (create.mock.calls.length === 0 ? 'analysis-job-1' : 'unexpected'),
|
||||||
|
);
|
||||||
|
|
||||||
|
const [firstResult, secondResult] = await Promise.all([
|
||||||
|
service.enqueueUserAnalysis(createJobData()),
|
||||||
|
service.enqueueUserAnalysis(createJobData()),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(firstResult).toEqual({ jobId: 'analysis-job-1', status: 'queued' });
|
||||||
|
expect(secondResult).toEqual({ jobId: 'analysis-job-1', status: 'queued' });
|
||||||
|
expect(create).toHaveBeenCalledTimes(1);
|
||||||
|
expect(add).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
import { InjectQueue } from '@nestjs/bullmq';
|
||||||
|
import { Inject, Injectable } from '@nestjs/common';
|
||||||
|
import type { AnalysisRequestAcceptedDto } from '@persona-lenz/shared';
|
||||||
|
import type { Queue } from 'bullmq';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { AnalysisJob, SeedSource } from '../global/database/schemas';
|
||||||
|
import {
|
||||||
|
ANALYSIS_JOB_ID_FACTORY,
|
||||||
|
ACTIVE_ANALYSIS_JOB_STATUSES,
|
||||||
|
ANALYSIS_QUEUE_NAME,
|
||||||
|
BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
DEFAULT_SEED_COLLECTION_MATCH_COUNT,
|
||||||
|
FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
normalizeFeatureRecomputeBatchSize,
|
||||||
|
normalizeRequestedMatchCount,
|
||||||
|
SEED_COLLECTION_JOB_NAME,
|
||||||
|
SEED_COLLECTION_QUEUE_NAME,
|
||||||
|
USER_ANALYSIS_JOB_NAME,
|
||||||
|
} from './analysis.constants';
|
||||||
|
import type {
|
||||||
|
BaselineComputationJobData,
|
||||||
|
FeatureRecomputeJobData,
|
||||||
|
SeedCollectionJobData,
|
||||||
|
UserAnalysisJobData,
|
||||||
|
} from './analysis.types';
|
||||||
|
|
||||||
|
type JobIdFactory = () => string;
|
||||||
|
type AnalysisQueueJobData =
|
||||||
|
UserAnalysisJobData | FeatureRecomputeJobData | BaselineComputationJobData;
|
||||||
|
type AnalysisQueueJobName =
|
||||||
|
| typeof USER_ANALYSIS_JOB_NAME
|
||||||
|
| typeof FEATURE_RECOMPUTE_JOB_NAME
|
||||||
|
| typeof BASELINE_COMPUTATION_JOB_NAME;
|
||||||
|
type SeedCollectionQueueJobName = typeof SEED_COLLECTION_JOB_NAME;
|
||||||
|
type ActiveAnalysisJob = Pick<AnalysisJob, 'jobId'> & {
|
||||||
|
status: Extract<AnalysisJob['status'], 'queued' | 'processing'>;
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AnalysisQueueService {
|
||||||
|
constructor(
|
||||||
|
@InjectQueue(ANALYSIS_QUEUE_NAME)
|
||||||
|
private readonly analysisQueue: Queue<
|
||||||
|
AnalysisQueueJobData,
|
||||||
|
void,
|
||||||
|
AnalysisQueueJobName
|
||||||
|
>,
|
||||||
|
@InjectQueue(SEED_COLLECTION_QUEUE_NAME)
|
||||||
|
private readonly seedCollectionQueue: Queue<
|
||||||
|
SeedCollectionJobData,
|
||||||
|
void,
|
||||||
|
SeedCollectionQueueJobName
|
||||||
|
>,
|
||||||
|
private readonly connectionService: ConnectionService,
|
||||||
|
@Inject(ANALYSIS_JOB_ID_FACTORY)
|
||||||
|
private readonly jobIdFactory: JobIdFactory = randomUUID,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async enqueueUserAnalysis(
|
||||||
|
data: UserAnalysisJobData,
|
||||||
|
): Promise<AnalysisRequestAcceptedDto> {
|
||||||
|
const normalizedData = {
|
||||||
|
...data,
|
||||||
|
requestedMatchCount: normalizeRequestedMatchCount(
|
||||||
|
data.requestedMatchCount,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
const duplicateRequestKey = this.duplicateRequestKey(normalizedData);
|
||||||
|
while (this.pendingDuplicateRequestKeys.has(duplicateRequestKey)) {
|
||||||
|
await this.sleep(10);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.pendingDuplicateRequestKeys.add(duplicateRequestKey);
|
||||||
|
try {
|
||||||
|
return await this.enqueueUserAnalysisWithoutDuplicateRequestRace(
|
||||||
|
normalizedData,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
this.pendingDuplicateRequestKeys.delete(duplicateRequestKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async enqueueFeatureRecompute(
|
||||||
|
data: FeatureRecomputeJobData,
|
||||||
|
): Promise<AnalysisRequestAcceptedDto> {
|
||||||
|
const normalizedData = this.normalizeFeatureRecomputeData(data);
|
||||||
|
const analysisJobModel =
|
||||||
|
await this.connectionService.getModel('analysisJob');
|
||||||
|
const jobId = this.jobIdFactory();
|
||||||
|
|
||||||
|
await analysisJobModel.create({
|
||||||
|
jobId,
|
||||||
|
jobType: FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
puuid: normalizedData.puuid,
|
||||||
|
platformRoute: normalizedData.platformRoute,
|
||||||
|
queueId: normalizedData.queueId,
|
||||||
|
requestedMatchCount: 0,
|
||||||
|
status: 'queued',
|
||||||
|
stage: 'queued',
|
||||||
|
progress: {
|
||||||
|
fetchedMatches: 0,
|
||||||
|
totalMatches: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.analysisQueue.add(FEATURE_RECOMPUTE_JOB_NAME, normalizedData, {
|
||||||
|
attempts: 1,
|
||||||
|
jobId,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
await analysisJobModel
|
||||||
|
.updateOne(
|
||||||
|
{ jobId },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'failed',
|
||||||
|
stage: 'enqueue',
|
||||||
|
error: this.publicErrorMessage(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
jobId,
|
||||||
|
status: 'queued',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async enqueueSeedCollection(
|
||||||
|
data: SeedCollectionJobData,
|
||||||
|
): Promise<AnalysisRequestAcceptedDto> {
|
||||||
|
const normalizedData = this.normalizeSeedCollectionData(data);
|
||||||
|
const analysisJobModel =
|
||||||
|
await this.connectionService.getModel('analysisJob');
|
||||||
|
const jobId = this.jobIdFactory();
|
||||||
|
|
||||||
|
await analysisJobModel.create({
|
||||||
|
jobId,
|
||||||
|
jobType: SEED_COLLECTION_JOB_NAME,
|
||||||
|
platformRoute: normalizedData.platformRoute,
|
||||||
|
queueId: normalizedData.queueId,
|
||||||
|
requestedMatchCount: DEFAULT_SEED_COLLECTION_MATCH_COUNT,
|
||||||
|
status: 'queued',
|
||||||
|
stage: 'queued',
|
||||||
|
progress: {
|
||||||
|
fetchedMatches: 0,
|
||||||
|
totalMatches: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.seedCollectionQueue.add(
|
||||||
|
SEED_COLLECTION_JOB_NAME,
|
||||||
|
normalizedData,
|
||||||
|
{
|
||||||
|
attempts: 1,
|
||||||
|
jobId,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
await analysisJobModel
|
||||||
|
.updateOne(
|
||||||
|
{ jobId },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'failed',
|
||||||
|
stage: 'enqueue',
|
||||||
|
error: this.publicErrorMessage(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
jobId,
|
||||||
|
status: 'queued',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async enqueueBaselineComputation(
|
||||||
|
data: BaselineComputationJobData,
|
||||||
|
): Promise<AnalysisRequestAcceptedDto> {
|
||||||
|
const normalizedData = this.normalizeBaselineComputationData(data);
|
||||||
|
const analysisJobModel =
|
||||||
|
await this.connectionService.getModel('analysisJob');
|
||||||
|
const jobId = this.jobIdFactory();
|
||||||
|
|
||||||
|
await analysisJobModel.create({
|
||||||
|
jobId,
|
||||||
|
jobType: BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
platformRoute: normalizedData.platformRoute,
|
||||||
|
queueId: normalizedData.queueId,
|
||||||
|
requestedMatchCount: 0,
|
||||||
|
status: 'queued',
|
||||||
|
stage: 'queued',
|
||||||
|
progress: {
|
||||||
|
fetchedMatches: 0,
|
||||||
|
totalMatches: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.analysisQueue.add(
|
||||||
|
BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
normalizedData,
|
||||||
|
{
|
||||||
|
attempts: 1,
|
||||||
|
jobId,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
await analysisJobModel
|
||||||
|
.updateOne(
|
||||||
|
{ jobId },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'failed',
|
||||||
|
stage: 'enqueue',
|
||||||
|
error: this.publicErrorMessage(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
jobId,
|
||||||
|
status: 'queued',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private readonly pendingDuplicateRequestKeys = new Set<string>();
|
||||||
|
|
||||||
|
private async enqueueUserAnalysisWithoutDuplicateRequestRace(
|
||||||
|
normalizedData: UserAnalysisJobData,
|
||||||
|
): Promise<AnalysisRequestAcceptedDto> {
|
||||||
|
const analysisJobModel =
|
||||||
|
await this.connectionService.getModel('analysisJob');
|
||||||
|
const existingJob = await this.findActiveJob(
|
||||||
|
analysisJobModel,
|
||||||
|
normalizedData,
|
||||||
|
);
|
||||||
|
if (existingJob) {
|
||||||
|
return {
|
||||||
|
jobId: existingJob.jobId,
|
||||||
|
status: existingJob.status,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const jobId = this.jobIdFactory();
|
||||||
|
await analysisJobModel.create({
|
||||||
|
jobId,
|
||||||
|
jobType: USER_ANALYSIS_JOB_NAME,
|
||||||
|
gameName: normalizedData.gameName,
|
||||||
|
tagLine: normalizedData.tagLine,
|
||||||
|
platformRoute: normalizedData.platformRoute,
|
||||||
|
queueId: normalizedData.queueId,
|
||||||
|
requestedMatchCount: normalizedData.requestedMatchCount,
|
||||||
|
status: 'queued',
|
||||||
|
stage: 'queued',
|
||||||
|
progress: {
|
||||||
|
fetchedMatches: 0,
|
||||||
|
totalMatches: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.analysisQueue.add(USER_ANALYSIS_JOB_NAME, normalizedData, {
|
||||||
|
attempts: 2,
|
||||||
|
backoff: {
|
||||||
|
type: 'exponential',
|
||||||
|
delay: 1_000,
|
||||||
|
},
|
||||||
|
jobId,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
await analysisJobModel
|
||||||
|
.updateOne(
|
||||||
|
{ jobId },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'failed',
|
||||||
|
stage: 'enqueue',
|
||||||
|
error: this.publicErrorMessage(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
jobId,
|
||||||
|
status: 'queued',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findActiveJob(
|
||||||
|
analysisJobModel: Awaited<ReturnType<ConnectionService['getModel']>>,
|
||||||
|
data: UserAnalysisJobData,
|
||||||
|
): Promise<ActiveAnalysisJob | null> {
|
||||||
|
return analysisJobModel
|
||||||
|
.findOne({
|
||||||
|
gameName: data.gameName,
|
||||||
|
tagLine: data.tagLine,
|
||||||
|
platformRoute: data.platformRoute,
|
||||||
|
queueId: data.queueId,
|
||||||
|
status: { $in: ACTIVE_ANALYSIS_JOB_STATUSES },
|
||||||
|
})
|
||||||
|
.sort({ createdAt: -1 })
|
||||||
|
.lean<ActiveAnalysisJob>()
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
private errorMessage(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
private publicErrorMessage(): string {
|
||||||
|
return 'Analysis could not be queued.';
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeFeatureRecomputeData(
|
||||||
|
data: FeatureRecomputeJobData,
|
||||||
|
): FeatureRecomputeJobData {
|
||||||
|
const puuid = data.puuid?.trim();
|
||||||
|
return {
|
||||||
|
platformRoute: data.platformRoute,
|
||||||
|
queueId: data.queueId,
|
||||||
|
batchSize: normalizeFeatureRecomputeBatchSize(data.batchSize),
|
||||||
|
...(puuid ? { puuid } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeSeedCollectionData(
|
||||||
|
data: SeedCollectionJobData,
|
||||||
|
): SeedCollectionJobData {
|
||||||
|
return {
|
||||||
|
platformRoute: data.platformRoute,
|
||||||
|
queueId: data.queueId,
|
||||||
|
...(data.sourceLimits
|
||||||
|
? { sourceLimits: this.normalizeSeedSourceLimits(data.sourceLimits) }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeBaselineComputationData(
|
||||||
|
data: BaselineComputationJobData,
|
||||||
|
): BaselineComputationJobData {
|
||||||
|
const patch = data.patch?.trim();
|
||||||
|
return {
|
||||||
|
platformRoute: data.platformRoute,
|
||||||
|
queueId: data.queueId,
|
||||||
|
cohort: data.cohort ?? 'MASTER_PLUS',
|
||||||
|
patch: patch && patch.length > 0 ? patch : 'ALL',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeSeedSourceLimits(
|
||||||
|
sourceLimits: NonNullable<SeedCollectionJobData['sourceLimits']>,
|
||||||
|
): NonNullable<SeedCollectionJobData['sourceLimits']> {
|
||||||
|
const normalizedSourceLimits: Partial<Record<SeedSource, number>> = {};
|
||||||
|
for (const [source, limit] of Object.entries(sourceLimits)) {
|
||||||
|
if (typeof limit === 'number' && Number.isFinite(limit) && limit >= 0) {
|
||||||
|
normalizedSourceLimits[source as SeedSource] = Math.trunc(limit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return normalizedSourceLimits;
|
||||||
|
}
|
||||||
|
|
||||||
|
private duplicateRequestKey(data: UserAnalysisJobData): string {
|
||||||
|
return [
|
||||||
|
data.platformRoute,
|
||||||
|
data.queueId,
|
||||||
|
data.gameName.trim().toLocaleLowerCase(),
|
||||||
|
data.tagLine.trim().toLocaleLowerCase(),
|
||||||
|
].join(':');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async sleep(durationMs: number): Promise<void> {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, durationMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import { FEATURE_SCHEMA_VERSION } from '@persona-lenz/shared';
|
||||||
|
import type { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { AnalysisReadService } from './analysis-read.service';
|
||||||
|
|
||||||
|
function createLeanExec<T>(value: T) {
|
||||||
|
return {
|
||||||
|
lean: jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AnalysisReadService', () => {
|
||||||
|
it('queries analysis jobs by jobId and serializes public failed errors', async () => {
|
||||||
|
const findOne = jest.fn(() =>
|
||||||
|
createLeanExec({
|
||||||
|
error: 'internal host redis.local refused connection',
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
progress: { fetchedMatches: 0, totalMatches: 20 },
|
||||||
|
status: 'failed',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const service = new AnalysisReadService({
|
||||||
|
getModel: jest.fn().mockResolvedValue({ findOne }),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
await expect(service.getJobStatus('analysis-job-1')).resolves.toEqual({
|
||||||
|
error: 'Analysis failed during processing.',
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
progress: { fetchedMatches: 0, totalMatches: 20 },
|
||||||
|
status: 'failed',
|
||||||
|
});
|
||||||
|
expect(findOne).toHaveBeenCalledWith({ jobId: 'analysis-job-1' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves public Riot account not-found job errors', async () => {
|
||||||
|
const findOne = jest.fn(() =>
|
||||||
|
createLeanExec({
|
||||||
|
error: 'Riot account was not found for the selected region.',
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
progress: { fetchedMatches: 0, totalMatches: 0 },
|
||||||
|
stage: 'resolve-account',
|
||||||
|
status: 'failed',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const service = new AnalysisReadService({
|
||||||
|
getModel: jest.fn().mockResolvedValue({ findOne }),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
await expect(service.getJobStatus('analysis-job-1')).resolves.toEqual({
|
||||||
|
error: 'Riot account was not found for the selected region.',
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
progress: { fetchedMatches: 0, totalMatches: 0 },
|
||||||
|
stage: 'resolve-account',
|
||||||
|
status: 'failed',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('distinguishes analyzed accounts with no ranked games from missing accounts', async () => {
|
||||||
|
const accountFindOne = jest.fn(() =>
|
||||||
|
createLeanExec({
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
profileIconId: 1,
|
||||||
|
tagLine: 'KR1',
|
||||||
|
tiers: [],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const profileFindOne = jest.fn(() => createLeanExec(null));
|
||||||
|
const service = new AnalysisReadService({
|
||||||
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'account'
|
||||||
|
? { findOne: accountFindOne }
|
||||||
|
: { findOne: profileFindOne },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.getLatestPlayerAnalysis('target-puuid', 420),
|
||||||
|
).rejects.toThrow('분석할 랭크 게임이 없음');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('queries account and profile by puuid/queue and applies lower-is-better scoring', async () => {
|
||||||
|
const accountFindOne = jest.fn(() =>
|
||||||
|
createLeanExec({
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
profileIconId: 1,
|
||||||
|
tagLine: 'KR1',
|
||||||
|
tiers: [],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const profileFindOne = jest.fn(() =>
|
||||||
|
createLeanExec({
|
||||||
|
championPool: [{ championId: 103, games: 4, wins: 3 }],
|
||||||
|
confidence: 0.9,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
profile: {
|
||||||
|
kda: 0.8,
|
||||||
|
killParticipation: 0.7,
|
||||||
|
damageShare: 0.6,
|
||||||
|
damagePerMin: 0.5,
|
||||||
|
goldPerMin: 0.4,
|
||||||
|
csPerMin: 0.3,
|
||||||
|
visionScorePerMin: 0.2,
|
||||||
|
wardsKilledPerMin: 0.1,
|
||||||
|
controlWardsPlaced: 0.2,
|
||||||
|
deathsPerMin: 0.1,
|
||||||
|
objectiveParticipation: 0.6,
|
||||||
|
soloKills: 0.4,
|
||||||
|
},
|
||||||
|
queueId: 420,
|
||||||
|
sampleGameCount: 12,
|
||||||
|
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const service = new AnalysisReadService({
|
||||||
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'account'
|
||||||
|
? { findOne: accountFindOne }
|
||||||
|
: { findOne: profileFindOne },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
const analysis = await service.getLatestPlayerAnalysis('target-puuid', 420);
|
||||||
|
|
||||||
|
expect(accountFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid' });
|
||||||
|
expect(profileFindOne).toHaveBeenCalledWith({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
});
|
||||||
|
expect(analysis.profile.playstyle.kda).toBe(0.8);
|
||||||
|
expect(analysis.profile.playstyle.goldDiffAt10).toBeUndefined();
|
||||||
|
expect(analysis.profile.playstyle.objectivePreWardRate).toBeUndefined();
|
||||||
|
expect(
|
||||||
|
analysis.strengths.some((metric) => metric.metricId === 'goldDiffAt10'),
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
analysis.weaknesses.some(
|
||||||
|
(metric) => metric.metricId === 'deathWithShutdownBountyGivenRate',
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
expect(analysis.strengths).toHaveLength(12);
|
||||||
|
expect(analysis.weaknesses).toHaveLength(12);
|
||||||
|
expect(analysis.strengths.slice(0, 3)).toEqual([
|
||||||
|
{ metricId: 'deathsPerMin', value: 0.1 },
|
||||||
|
{ metricId: 'kda', value: 0.8 },
|
||||||
|
{ metricId: 'killParticipation', value: 0.7 },
|
||||||
|
]);
|
||||||
|
expect(analysis.strengths.at(-1)).toEqual({
|
||||||
|
metricId: 'wardsKilledPerMin',
|
||||||
|
value: 0.1,
|
||||||
|
});
|
||||||
|
expect(analysis.weaknesses.slice(0, 3)).toEqual([
|
||||||
|
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
||||||
|
{ metricId: 'visionScorePerMin', value: 0.2 },
|
||||||
|
{ metricId: 'controlWardsPlaced', value: 0.2 },
|
||||||
|
]);
|
||||||
|
expect(analysis.weaknesses.at(-1)).toEqual({
|
||||||
|
metricId: 'deathsPerMin',
|
||||||
|
value: 0.1,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
FEATURE_SCHEMA_VERSION,
|
||||||
|
METRICS,
|
||||||
|
type AnalysisJobStatusDto,
|
||||||
|
type MetricValueDto,
|
||||||
|
type PlayerAnalysisDto,
|
||||||
|
type SimilarPlayersDto,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type {
|
||||||
|
Account,
|
||||||
|
AnalysisJob,
|
||||||
|
PlayerProfile,
|
||||||
|
TierInfo,
|
||||||
|
} from '../global/database/schemas';
|
||||||
|
import { SimilarPlayerService } from './similar-player.service';
|
||||||
|
import type { SimilarPlayer } from './analysis.types';
|
||||||
|
|
||||||
|
type JobStatusRecord = Pick<
|
||||||
|
AnalysisJob,
|
||||||
|
'error' | 'jobId' | 'progress' | 'puuid' | 'stage' | 'status'
|
||||||
|
>;
|
||||||
|
|
||||||
|
type AccountSummaryRecord = Pick<
|
||||||
|
Account,
|
||||||
|
'gameName' | 'profileIconId' | 'tagLine' | 'tiers'
|
||||||
|
>;
|
||||||
|
|
||||||
|
type CounterpartAccountRecord = Pick<Account, 'gameName' | 'puuid' | 'tagLine'>;
|
||||||
|
|
||||||
|
type PlayerProfileRecord = Pick<
|
||||||
|
PlayerProfile,
|
||||||
|
| 'championPool'
|
||||||
|
| 'confidence'
|
||||||
|
| 'featureSchemaVersion'
|
||||||
|
| 'mainRole'
|
||||||
|
| 'profile'
|
||||||
|
| 'queueId'
|
||||||
|
| 'sampleGameCount'
|
||||||
|
| 'updatedAt'
|
||||||
|
>;
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AnalysisReadService {
|
||||||
|
constructor(
|
||||||
|
private readonly connectionService: ConnectionService,
|
||||||
|
private readonly similarPlayerService?: SimilarPlayerService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async getJobStatus(jobId: string): Promise<AnalysisJobStatusDto> {
|
||||||
|
const analysisJobModel =
|
||||||
|
await this.connectionService.getModel('analysisJob');
|
||||||
|
const job = await analysisJobModel
|
||||||
|
.findOne({ jobId })
|
||||||
|
.lean<JobStatusRecord>()
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
if (!job) {
|
||||||
|
throw new NotFoundException('Analysis job not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
jobId: job.jobId,
|
||||||
|
status: job.status,
|
||||||
|
stage: job.stage,
|
||||||
|
puuid: job.puuid,
|
||||||
|
progress: job.progress,
|
||||||
|
error: this.publicJobError(job.error),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getLatestPlayerAnalysis(
|
||||||
|
puuid: string,
|
||||||
|
queueId: number,
|
||||||
|
): Promise<PlayerAnalysisDto> {
|
||||||
|
const [account, profile] = await Promise.all([
|
||||||
|
this.findAccount(puuid),
|
||||||
|
this.findPlayerProfile(puuid, queueId),
|
||||||
|
]);
|
||||||
|
|
||||||
|
if (!account) {
|
||||||
|
throw new NotFoundException('Player account not found.');
|
||||||
|
}
|
||||||
|
if (!profile) {
|
||||||
|
throw new NotFoundException('분석할 랭크 게임이 없음');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
account: {
|
||||||
|
gameName: account.gameName,
|
||||||
|
tagLine: account.tagLine,
|
||||||
|
profileIconId: account.profileIconId,
|
||||||
|
tiers: account.tiers.map((tier) => this.toTierDto(tier)),
|
||||||
|
},
|
||||||
|
profile: {
|
||||||
|
mainRole: profile.mainRole,
|
||||||
|
queueId: profile.queueId,
|
||||||
|
sampleGameCount: profile.sampleGameCount,
|
||||||
|
championPool: profile.championPool,
|
||||||
|
playstyle: Object.fromEntries(
|
||||||
|
Object.entries(profile.profile).map(([metricId, value]) => [
|
||||||
|
metricId,
|
||||||
|
this.clampMetricValue(value),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
featureSchemaVersion: profile.featureSchemaVersion,
|
||||||
|
confidence: profile.confidence,
|
||||||
|
},
|
||||||
|
strengths: this.resolveMetricHighlights(profile.profile, 'strength'),
|
||||||
|
weaknesses: this.resolveMetricHighlights(profile.profile, 'weakness'),
|
||||||
|
updatedAt: profile.updatedAt.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getSimilarPlayers(
|
||||||
|
puuid: string,
|
||||||
|
queueId: number,
|
||||||
|
limit: number,
|
||||||
|
): Promise<SimilarPlayersDto> {
|
||||||
|
if (!this.similarPlayerService) {
|
||||||
|
throw new Error('SimilarPlayerService is not configured.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const similarPlayersResult =
|
||||||
|
await this.similarPlayerService.findSimilarPlayers(puuid, queueId, limit);
|
||||||
|
const accountsByPuuid = await this.findCounterpartAccounts(
|
||||||
|
similarPlayersResult.matches.map((match) => match.puuid),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
puuid: similarPlayersResult.puuid,
|
||||||
|
queueId: similarPlayersResult.queueId,
|
||||||
|
profileUpdatedAt: similarPlayersResult.profileUpdatedAt.toISOString(),
|
||||||
|
matches: similarPlayersResult.matches.map((match, index) =>
|
||||||
|
this.toSimilarPlayerDto(match, accountsByPuuid.get(match.puuid), index),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findAccount(
|
||||||
|
puuid: string,
|
||||||
|
): Promise<AccountSummaryRecord | null> {
|
||||||
|
const accountModel = await this.connectionService.getModel('account');
|
||||||
|
return accountModel.findOne({ puuid }).lean<AccountSummaryRecord>().exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findCounterpartAccounts(
|
||||||
|
puuids: string[],
|
||||||
|
): Promise<Map<string, CounterpartAccountRecord>> {
|
||||||
|
const uniquePuuids = Array.from(new Set(puuids));
|
||||||
|
if (uniquePuuids.length === 0) return new Map();
|
||||||
|
|
||||||
|
const accountModel = await this.connectionService.getModel('account');
|
||||||
|
const accounts = await accountModel
|
||||||
|
.find({ puuid: { $in: uniquePuuids } })
|
||||||
|
.lean<CounterpartAccountRecord[]>()
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
return new Map(accounts.map((account) => [account.puuid, account]));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findPlayerProfile(
|
||||||
|
puuid: string,
|
||||||
|
queueId: number,
|
||||||
|
): Promise<PlayerProfileRecord | null> {
|
||||||
|
const playerProfileModel =
|
||||||
|
await this.connectionService.getModel('playerProfile');
|
||||||
|
return playerProfileModel
|
||||||
|
.findOne({ puuid, queueId, featureSchemaVersion: FEATURE_SCHEMA_VERSION })
|
||||||
|
.lean<PlayerProfileRecord>()
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveMetricHighlights(
|
||||||
|
profile: Record<string, number>,
|
||||||
|
direction: 'strength' | 'weakness',
|
||||||
|
): MetricValueDto[] {
|
||||||
|
return METRICS.flatMap((metric) => {
|
||||||
|
const rawValue = profile[metric.id];
|
||||||
|
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const value = this.clampMetricValue(rawValue);
|
||||||
|
return {
|
||||||
|
metricId: metric.id,
|
||||||
|
score: metric.direction === 'lowerIsBetter' ? 1 - value : value,
|
||||||
|
value,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((left, right) =>
|
||||||
|
direction === 'strength'
|
||||||
|
? right.score - left.score
|
||||||
|
: left.score - right.score,
|
||||||
|
)
|
||||||
|
.map(({ metricId, value }) => ({ metricId, value }));
|
||||||
|
}
|
||||||
|
|
||||||
|
private clampMetricValue(value: unknown): number {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? Math.max(0, Math.min(1, value))
|
||||||
|
: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
private toTierDto(
|
||||||
|
tier: TierInfo,
|
||||||
|
): PlayerAnalysisDto['account']['tiers'][number] {
|
||||||
|
return {
|
||||||
|
queueType: tier.queueType,
|
||||||
|
tier: tier.tier,
|
||||||
|
rank: tier.rank,
|
||||||
|
leaguePoints: tier.leaguePoints,
|
||||||
|
wins: tier.wins,
|
||||||
|
losses: tier.losses,
|
||||||
|
fetchedAt: tier.fetchedAt?.toISOString(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private toSimilarPlayerDto(
|
||||||
|
match: SimilarPlayer,
|
||||||
|
account: CounterpartAccountRecord | undefined,
|
||||||
|
index: number,
|
||||||
|
): SimilarPlayersDto['matches'][number] {
|
||||||
|
return {
|
||||||
|
displayId: `similar-${index + 1}`,
|
||||||
|
riotId: account
|
||||||
|
? {
|
||||||
|
gameName: account.gameName,
|
||||||
|
tagLine: account.tagLine,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
similarityScore: match.similarityScore,
|
||||||
|
finalScore: match.finalScore,
|
||||||
|
tier: match.tier,
|
||||||
|
division: match.division,
|
||||||
|
leaguePoints: match.leaguePoints,
|
||||||
|
tierComparison: match.tierComparison,
|
||||||
|
mainRole: match.mainRole,
|
||||||
|
mainChampions: match.mainChampions,
|
||||||
|
sampleGameCount: match.sampleGameCount,
|
||||||
|
similarMetrics: match.similarMetrics,
|
||||||
|
strongerMetrics: match.strongerMetrics,
|
||||||
|
weakerMetrics: match.weakerMetrics,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private publicJobError(error: string | undefined): string | null {
|
||||||
|
if (!error) return null;
|
||||||
|
if (
|
||||||
|
error === 'Analysis failed during processing.' ||
|
||||||
|
error === 'Riot API key is invalid or expired.' ||
|
||||||
|
error === 'Riot account was not found for the selected region.' ||
|
||||||
|
error === 'Analysis could not be queued.'
|
||||||
|
) {
|
||||||
|
return error;
|
||||||
|
}
|
||||||
|
return 'Analysis failed during processing.';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
const REQUEST_WINDOW_MS = 60_000;
|
||||||
|
const MAX_REQUESTS_PER_WINDOW = 10;
|
||||||
|
|
||||||
|
interface RequestWindow {
|
||||||
|
count: number;
|
||||||
|
resetAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class AnalysisRequestThrottleService {
|
||||||
|
private readonly requestWindows = new Map<string, RequestWindow>();
|
||||||
|
|
||||||
|
public assertAllowed(clientKey: string, now = Date.now()): void {
|
||||||
|
const existingWindow = this.requestWindows.get(clientKey);
|
||||||
|
if (!existingWindow || existingWindow.resetAt <= now) {
|
||||||
|
this.requestWindows.set(clientKey, {
|
||||||
|
count: 1,
|
||||||
|
resetAt: now + REQUEST_WINDOW_MS,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (existingWindow.count >= MAX_REQUESTS_PER_WINDOW) {
|
||||||
|
throw new HttpException(
|
||||||
|
'Too many analysis requests.',
|
||||||
|
HttpStatus.TOO_MANY_REQUESTS,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
existingWindow.count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
export const ANALYSIS_QUEUE_NAME = 'analysis';
|
||||||
|
export const SEED_COLLECTION_QUEUE_NAME = 'seed-collection';
|
||||||
|
export const USER_ANALYSIS_JOB_NAME = 'user-analysis';
|
||||||
|
export const FEATURE_RECOMPUTE_JOB_NAME = 'feature-recompute';
|
||||||
|
export const SEED_COLLECTION_JOB_NAME = 'seed-collection';
|
||||||
|
export const BASELINE_COMPUTATION_JOB_NAME = 'baseline-computation';
|
||||||
|
export const ANALYSIS_JOB_ID_FACTORY = Symbol('ANALYSIS_JOB_ID_FACTORY');
|
||||||
|
|
||||||
|
export const DEFAULT_ANALYSIS_MATCH_COUNT = 20;
|
||||||
|
export const MAX_ANALYSIS_MATCH_COUNT = 50;
|
||||||
|
export const DEFAULT_SEED_COLLECTION_MATCH_COUNT = 30;
|
||||||
|
export const DEFAULT_SEED_COLLECTION_QUEUE_TYPE = 'RANKED_SOLO_5x5';
|
||||||
|
export const DEFAULT_SEED_COLLECTION_SOURCE_LIMIT = 50;
|
||||||
|
export const DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE = 100;
|
||||||
|
export const MAX_FEATURE_RECOMPUTE_BATCH_SIZE = 500;
|
||||||
|
|
||||||
|
export const ACTIVE_ANALYSIS_JOB_STATUSES = ['queued', 'processing'] as const;
|
||||||
|
|
||||||
|
export function normalizeRequestedMatchCount(
|
||||||
|
requestedMatchCount: number,
|
||||||
|
): number {
|
||||||
|
if (!Number.isFinite(requestedMatchCount) || requestedMatchCount <= 0) {
|
||||||
|
return DEFAULT_ANALYSIS_MATCH_COUNT;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.min(Math.trunc(requestedMatchCount), MAX_ANALYSIS_MATCH_COUNT);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeFeatureRecomputeBatchSize(batchSize: number): number {
|
||||||
|
if (!Number.isFinite(batchSize) || batchSize <= 0) {
|
||||||
|
return DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedBatchSize = Math.trunc(batchSize);
|
||||||
|
if (normalizedBatchSize <= 0) {
|
||||||
|
return DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.min(normalizedBatchSize, MAX_FEATURE_RECOMPUTE_BATCH_SIZE);
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
HttpCode,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Query,
|
||||||
|
Req,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from '@nestjs/common';
|
||||||
|
import type {
|
||||||
|
AnalysisJobStatusDto,
|
||||||
|
AnalysisRequestAcceptedDto,
|
||||||
|
PlayerAnalysisDto,
|
||||||
|
SimilarPlayersDto,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
|
import {
|
||||||
|
RIOT_PLATFORM_ROUTES,
|
||||||
|
toRegionalRoute,
|
||||||
|
type RiotPlatformRoute,
|
||||||
|
} from '../riot/riot.types';
|
||||||
|
import { SecretService } from '../global/secret/secret.service';
|
||||||
|
import { SEED_SOURCES, type SeedSource } from '../global/database/schemas';
|
||||||
|
import { AnalysisQueueService } from './analysis-queue.service';
|
||||||
|
import {
|
||||||
|
DEFAULT_ANALYSIS_MATCH_COUNT,
|
||||||
|
MAX_ANALYSIS_MATCH_COUNT,
|
||||||
|
normalizeRequestedMatchCount,
|
||||||
|
} from './analysis.constants';
|
||||||
|
import { AnalysisReadService } from './analysis-read.service';
|
||||||
|
import { AnalysisRequestThrottleService } from './analysis-request-throttle.service';
|
||||||
|
import type {
|
||||||
|
SeedCollectionJobData,
|
||||||
|
UserAnalysisJobData,
|
||||||
|
} from './analysis.types';
|
||||||
|
import type { Request } from 'express';
|
||||||
|
import { createHash, timingSafeEqual } from 'node:crypto';
|
||||||
|
|
||||||
|
const MAX_ADMIN_SEED_COLLECTION_SOURCE_LIMIT = 200;
|
||||||
|
|
||||||
|
@Controller()
|
||||||
|
export class AnalysisController {
|
||||||
|
constructor(
|
||||||
|
private readonly analysisQueueService: AnalysisQueueService,
|
||||||
|
private readonly analysisReadService: AnalysisReadService,
|
||||||
|
private readonly analysisRequestThrottleService: AnalysisRequestThrottleService,
|
||||||
|
private readonly secretService: SecretService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Post('analysis/request')
|
||||||
|
@HttpCode(202)
|
||||||
|
public async requestAnalysis(
|
||||||
|
@Body() body: unknown,
|
||||||
|
@Req() request: Request,
|
||||||
|
): Promise<AnalysisRequestAcceptedDto> {
|
||||||
|
const data = this.parseAnalysisRequest(body);
|
||||||
|
this.analysisRequestThrottleService.assertAllowed(
|
||||||
|
this.resolveClientKey(request),
|
||||||
|
);
|
||||||
|
return this.analysisQueueService.enqueueUserAnalysis(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post('admin/seed-collection/request')
|
||||||
|
@HttpCode(202)
|
||||||
|
public async requestSeedCollection(
|
||||||
|
@Body() body: unknown,
|
||||||
|
@Req() request: Request,
|
||||||
|
): Promise<AnalysisRequestAcceptedDto> {
|
||||||
|
await this.assertAdminRequest(request);
|
||||||
|
return this.analysisQueueService.enqueueSeedCollection(
|
||||||
|
this.parseSeedCollectionRequest(body),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('analysis/jobs/:jobId')
|
||||||
|
public async getJobStatus(
|
||||||
|
@Param('jobId') jobId: string,
|
||||||
|
): Promise<AnalysisJobStatusDto> {
|
||||||
|
return this.analysisReadService.getJobStatus(jobId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('players/:puuid/analysis/latest')
|
||||||
|
public async getLatestPlayerAnalysis(
|
||||||
|
@Param('puuid') puuid: string,
|
||||||
|
@Query('queueId') rawQueueId?: string,
|
||||||
|
): Promise<PlayerAnalysisDto> {
|
||||||
|
return this.analysisReadService.getLatestPlayerAnalysis(
|
||||||
|
this.parsePuuid(puuid),
|
||||||
|
this.parseQueueId(rawQueueId),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get('players/:puuid/similar-players')
|
||||||
|
public async getSimilarPlayers(
|
||||||
|
@Param('puuid') puuid: string,
|
||||||
|
@Query('queueId') rawQueueId?: string,
|
||||||
|
@Query('limit') rawLimit?: string,
|
||||||
|
): Promise<SimilarPlayersDto> {
|
||||||
|
return this.analysisReadService.getSimilarPlayers(
|
||||||
|
this.parsePuuid(puuid),
|
||||||
|
this.parseQueueId(rawQueueId),
|
||||||
|
this.parseSimilarPlayersLimit(rawLimit),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseAnalysisRequest(body: unknown): UserAnalysisJobData {
|
||||||
|
const record = this.requireRecord(body);
|
||||||
|
const gameName = this.parseTrimmedString(
|
||||||
|
record.gameName,
|
||||||
|
'gameName',
|
||||||
|
3,
|
||||||
|
16,
|
||||||
|
);
|
||||||
|
const tagLine = this.parseTrimmedString(record.tagLine, 'tagLine', 3, 5);
|
||||||
|
const platformRoute = this.parsePlatformRoute(record.platform ?? 'kr');
|
||||||
|
const requestedMatchCount = this.parseMatchCount(record.matchCount);
|
||||||
|
|
||||||
|
return {
|
||||||
|
gameName,
|
||||||
|
tagLine,
|
||||||
|
platformRoute,
|
||||||
|
regionalRoute: toRegionalRoute(platformRoute),
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseSeedCollectionRequest(body: unknown): SeedCollectionJobData {
|
||||||
|
const record = body === undefined ? {} : this.requireRecord(body);
|
||||||
|
const platformRoute = this.parsePlatformRoute(record.platform ?? 'kr');
|
||||||
|
const queueId = this.parseSeedCollectionQueueId(record.queueId);
|
||||||
|
const sourceLimits = this.parseSeedSourceLimits(record.sourceLimits);
|
||||||
|
|
||||||
|
return {
|
||||||
|
platformRoute,
|
||||||
|
queueId,
|
||||||
|
...(sourceLimits ? { sourceLimits } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private requireRecord(value: unknown): Record<string, unknown> {
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
throw new BadRequestException('Request body must be an object.');
|
||||||
|
}
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseTrimmedString(
|
||||||
|
value: unknown,
|
||||||
|
fieldName: string,
|
||||||
|
minimumLength: number,
|
||||||
|
maximumLength: number,
|
||||||
|
): string {
|
||||||
|
if (typeof value !== 'string') {
|
||||||
|
throw new BadRequestException(`${fieldName} must be a string.`);
|
||||||
|
}
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (trimmed.length < minimumLength || trimmed.length > maximumLength) {
|
||||||
|
throw new BadRequestException(`${fieldName} is out of range.`);
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parsePlatformRoute(value: unknown): RiotPlatformRoute {
|
||||||
|
if (
|
||||||
|
typeof value !== 'string' ||
|
||||||
|
!RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('platform is unsupported.');
|
||||||
|
}
|
||||||
|
return value as RiotPlatformRoute;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseMatchCount(value: unknown): number {
|
||||||
|
if (value === undefined) return DEFAULT_ANALYSIS_MATCH_COUNT;
|
||||||
|
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||||
|
throw new BadRequestException('matchCount must be a finite number.');
|
||||||
|
}
|
||||||
|
return normalizeRequestedMatchCount(
|
||||||
|
Math.min(Math.max(value, 1), MAX_ANALYSIS_MATCH_COUNT),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private parsePuuid(value: string): string {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (trimmed.length === 0 || trimmed.length > 128) {
|
||||||
|
throw new BadRequestException('puuid is out of range.');
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseQueueId(value?: string): number {
|
||||||
|
if (value === undefined) return 420;
|
||||||
|
const queueId = Number(value);
|
||||||
|
if (!Number.isInteger(queueId) || queueId !== 420) {
|
||||||
|
throw new BadRequestException('queueId is unsupported.');
|
||||||
|
}
|
||||||
|
return queueId;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseSeedCollectionQueueId(value: unknown): number {
|
||||||
|
if (value === undefined) return 420;
|
||||||
|
if (
|
||||||
|
typeof value !== 'number' ||
|
||||||
|
!Number.isInteger(value) ||
|
||||||
|
value !== 420
|
||||||
|
) {
|
||||||
|
throw new BadRequestException('queueId is unsupported.');
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseSimilarPlayersLimit(value?: string): number {
|
||||||
|
if (value === undefined) return 10;
|
||||||
|
const limit = Number(value);
|
||||||
|
if (!Number.isInteger(limit) || limit < 1) {
|
||||||
|
throw new BadRequestException('limit is out of range.');
|
||||||
|
}
|
||||||
|
return Math.min(limit, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseSeedSourceLimits(
|
||||||
|
value: unknown,
|
||||||
|
): Partial<Record<SeedSource, number>> | undefined {
|
||||||
|
if (value === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
throw new BadRequestException('sourceLimits must be an object.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceLimits: Partial<Record<SeedSource, number>> = {};
|
||||||
|
for (const [source, limit] of Object.entries(value)) {
|
||||||
|
if (!SEED_SOURCES.includes(source as SeedSource)) {
|
||||||
|
throw new BadRequestException(`sourceLimits.${source} is unsupported.`);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
typeof limit !== 'number' ||
|
||||||
|
!Number.isInteger(limit) ||
|
||||||
|
limit < 0 ||
|
||||||
|
limit > MAX_ADMIN_SEED_COLLECTION_SOURCE_LIMIT
|
||||||
|
) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`sourceLimits.${source} must be an integer between 0 and ${MAX_ADMIN_SEED_COLLECTION_SOURCE_LIMIT}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
sourceLimits[source as SeedSource] = limit;
|
||||||
|
}
|
||||||
|
|
||||||
|
return sourceLimits;
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveClientKey(request: Request): string {
|
||||||
|
return request.ip || request.socket.remoteAddress || 'unknown-client';
|
||||||
|
}
|
||||||
|
|
||||||
|
private async assertAdminRequest(request: Request): Promise<void> {
|
||||||
|
const actualToken = this.extractBearerToken(request);
|
||||||
|
if (!actualToken) {
|
||||||
|
throw new UnauthorizedException('Admin token is required.');
|
||||||
|
}
|
||||||
|
|
||||||
|
let expectedToken: string;
|
||||||
|
try {
|
||||||
|
expectedToken = await this.secretService.get<string>('ADMIN_API_TOKEN');
|
||||||
|
} catch {
|
||||||
|
throw new UnauthorizedException('Admin token is not configured.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.secureTokenEquals(actualToken, expectedToken)) {
|
||||||
|
throw new UnauthorizedException('Admin token is invalid.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private extractBearerToken(request: Request): string | null {
|
||||||
|
const authorization = request.headers.authorization;
|
||||||
|
if (!authorization) return null;
|
||||||
|
const match = authorization.match(/^Bearer\s+(.+)$/i);
|
||||||
|
return match ? match[1]?.trim() || null : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private secureTokenEquals(
|
||||||
|
actualToken: string,
|
||||||
|
expectedToken: string,
|
||||||
|
): boolean {
|
||||||
|
if (expectedToken.length === 0) return false;
|
||||||
|
const actualHash = createHash('sha256').update(actualToken).digest();
|
||||||
|
const expectedHash = createHash('sha256').update(expectedToken).digest();
|
||||||
|
return timingSafeEqual(actualHash, expectedHash);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import { BullModule } from '@nestjs/bullmq';
|
||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { DatabaseModule } from '../global/database/database.module';
|
||||||
|
import { SecretModule } from '../global/secret/secret.module';
|
||||||
|
import { SecretService } from '../global/secret/secret.service';
|
||||||
|
import { RiotModule } from '../riot/riot.module';
|
||||||
|
import { AnalysisController } from './analysis.controller';
|
||||||
|
import { AnalysisReadService } from './analysis-read.service';
|
||||||
|
import { AnalysisRequestThrottleService } from './analysis-request-throttle.service';
|
||||||
|
import { AnalysisQueueService } from './analysis-queue.service';
|
||||||
|
import {
|
||||||
|
ANALYSIS_JOB_ID_FACTORY,
|
||||||
|
ANALYSIS_QUEUE_NAME,
|
||||||
|
SEED_COLLECTION_QUEUE_NAME,
|
||||||
|
} from './analysis.constants';
|
||||||
|
import { AnalysisPipelineService } from './analysis-pipeline.service';
|
||||||
|
import { AnalysisProcessor } from './analysis.processor';
|
||||||
|
import { createBullMqOptions } from './bullmq.config';
|
||||||
|
import { FeatureExtractorService } from './feature-extractor.service';
|
||||||
|
import { MetricBaselineService } from './metric-baseline.service';
|
||||||
|
import { MetricNormalizationService } from './metric-normalization.service';
|
||||||
|
import { ProfileBuilderService } from './profile-builder.service';
|
||||||
|
import { SeedCollectionProcessor } from './seed-collection.processor';
|
||||||
|
import { SeedCollectionService } from './seed-collection.service';
|
||||||
|
import { SimilarPlayerService } from './similar-player.service';
|
||||||
|
import { TimelineDerivedService } from './timeline-derived.service';
|
||||||
|
import { TimelineMetricService } from './timeline-metric.service';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
SecretModule,
|
||||||
|
DatabaseModule,
|
||||||
|
RiotModule,
|
||||||
|
BullModule.forRootAsync({
|
||||||
|
imports: [SecretModule],
|
||||||
|
inject: [SecretService],
|
||||||
|
useFactory: createBullMqOptions,
|
||||||
|
extraOptions: {
|
||||||
|
manualRegistration: process.env.NODE_ENV === 'test',
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: ANALYSIS_QUEUE_NAME,
|
||||||
|
}),
|
||||||
|
BullModule.registerQueue({
|
||||||
|
name: SEED_COLLECTION_QUEUE_NAME,
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
provide: ANALYSIS_JOB_ID_FACTORY,
|
||||||
|
useValue: randomUUID,
|
||||||
|
},
|
||||||
|
AnalysisQueueService,
|
||||||
|
AnalysisReadService,
|
||||||
|
AnalysisRequestThrottleService,
|
||||||
|
AnalysisPipelineService,
|
||||||
|
AnalysisProcessor,
|
||||||
|
SeedCollectionProcessor,
|
||||||
|
FeatureExtractorService,
|
||||||
|
MetricBaselineService,
|
||||||
|
MetricNormalizationService,
|
||||||
|
ProfileBuilderService,
|
||||||
|
SeedCollectionService,
|
||||||
|
SimilarPlayerService,
|
||||||
|
TimelineDerivedService,
|
||||||
|
TimelineMetricService,
|
||||||
|
],
|
||||||
|
controllers: [AnalysisController],
|
||||||
|
exports: [
|
||||||
|
AnalysisQueueService,
|
||||||
|
AnalysisPipelineService,
|
||||||
|
MetricBaselineService,
|
||||||
|
MetricNormalizationService,
|
||||||
|
SeedCollectionService,
|
||||||
|
SimilarPlayerService,
|
||||||
|
],
|
||||||
|
})
|
||||||
|
export class AnalysisModule {}
|
||||||
@@ -0,0 +1,353 @@
|
|||||||
|
import type { Job } from 'bullmq';
|
||||||
|
import {
|
||||||
|
BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE,
|
||||||
|
FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
MAX_FEATURE_RECOMPUTE_BATCH_SIZE,
|
||||||
|
USER_ANALYSIS_JOB_NAME,
|
||||||
|
} from './analysis.constants';
|
||||||
|
import type {
|
||||||
|
BaselineComputationJobData,
|
||||||
|
FeatureRecomputeJobData,
|
||||||
|
UserAnalysisJobData,
|
||||||
|
} from './analysis.types';
|
||||||
|
import { AnalysisPipelineService } from './analysis-pipeline.service';
|
||||||
|
import { AnalysisProcessor } from './analysis.processor';
|
||||||
|
|
||||||
|
function createJobData(
|
||||||
|
overrides: Partial<UserAnalysisJobData> = {},
|
||||||
|
): UserAnalysisJobData {
|
||||||
|
return {
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
platformRoute: 'kr',
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount: 20,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createFeatureRecomputeJobData(
|
||||||
|
overrides: Partial<FeatureRecomputeJobData> = {},
|
||||||
|
): FeatureRecomputeJobData {
|
||||||
|
return {
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
batchSize: 25,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBaselineComputationJobData(
|
||||||
|
overrides: Partial<BaselineComputationJobData> = {},
|
||||||
|
): BaselineComputationJobData {
|
||||||
|
return {
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
cohort: 'MASTER_PLUS',
|
||||||
|
patch: 'ALL',
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('AnalysisProcessor', () => {
|
||||||
|
it('delegates BullMQ jobs to the analysis pipeline', async () => {
|
||||||
|
const processUserAnalysisJob = jest
|
||||||
|
.fn<
|
||||||
|
Promise<void>,
|
||||||
|
[UserAnalysisJobData, string, { isFinalAttempt?: boolean }]
|
||||||
|
>()
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processUserAnalysisJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await processor.process({
|
||||||
|
attemptsMade: 1,
|
||||||
|
id: 'analysis-job-1',
|
||||||
|
name: USER_ANALYSIS_JOB_NAME,
|
||||||
|
opts: { attempts: 2 },
|
||||||
|
data: createJobData(),
|
||||||
|
} as Job<unknown>);
|
||||||
|
|
||||||
|
expect(processUserAnalysisJob).toHaveBeenCalledWith(
|
||||||
|
createJobData(),
|
||||||
|
'analysis-job-1',
|
||||||
|
{ isFinalAttempt: true },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delegates feature recompute jobs to the analysis pipeline', async () => {
|
||||||
|
const processFeatureRecomputeJob = jest
|
||||||
|
.fn<
|
||||||
|
Promise<void>,
|
||||||
|
[FeatureRecomputeJobData, string, { isFinalAttempt?: boolean }]
|
||||||
|
>()
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processFeatureRecomputeJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'recompute-job-1',
|
||||||
|
name: FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
opts: { attempts: 2 },
|
||||||
|
data: createFeatureRecomputeJobData(),
|
||||||
|
} as Job<unknown>);
|
||||||
|
|
||||||
|
expect(processFeatureRecomputeJob).toHaveBeenCalledWith(
|
||||||
|
createFeatureRecomputeJobData(),
|
||||||
|
'recompute-job-1',
|
||||||
|
{ isFinalAttempt: false },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('delegates baseline computation jobs to the analysis pipeline', async () => {
|
||||||
|
const processBaselineComputationJob = jest
|
||||||
|
.fn<
|
||||||
|
Promise<void>,
|
||||||
|
[BaselineComputationJobData, string, { isFinalAttempt?: boolean }]
|
||||||
|
>()
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processBaselineComputationJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'baseline-job-1',
|
||||||
|
name: BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
opts: { attempts: 1 },
|
||||||
|
data: createBaselineComputationJobData(),
|
||||||
|
} as Job<unknown>);
|
||||||
|
|
||||||
|
expect(processBaselineComputationJob).toHaveBeenCalledWith(
|
||||||
|
createBaselineComputationJobData(),
|
||||||
|
'baseline-job-1',
|
||||||
|
{ isFinalAttempt: true },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalizes feature recompute batch size from valid queue payloads', async () => {
|
||||||
|
const processFeatureRecomputeJob = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processFeatureRecomputeJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'recompute-job-1',
|
||||||
|
name: FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
opts: { attempts: 2 },
|
||||||
|
data: createFeatureRecomputeJobData({ batchSize: 999 }),
|
||||||
|
} as Job<unknown>);
|
||||||
|
|
||||||
|
expect(processFeatureRecomputeJob).toHaveBeenCalledWith(
|
||||||
|
createFeatureRecomputeJobData({
|
||||||
|
batchSize: MAX_FEATURE_RECOMPUTE_BATCH_SIZE,
|
||||||
|
}),
|
||||||
|
'recompute-job-1',
|
||||||
|
{ isFinalAttempt: false },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defaults fractional feature recompute batch sizes below one', async () => {
|
||||||
|
const processFeatureRecomputeJob = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processFeatureRecomputeJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'recompute-job-1',
|
||||||
|
name: FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
opts: { attempts: 2 },
|
||||||
|
data: createFeatureRecomputeJobData({ batchSize: 0.5 }),
|
||||||
|
} as Job<unknown>);
|
||||||
|
|
||||||
|
expect(processFeatureRecomputeJob).toHaveBeenCalledWith(
|
||||||
|
createFeatureRecomputeJobData({
|
||||||
|
batchSize: DEFAULT_FEATURE_RECOMPUTE_BATCH_SIZE,
|
||||||
|
}),
|
||||||
|
'recompute-job-1',
|
||||||
|
{ isFinalAttempt: false },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
data: null,
|
||||||
|
expectedError: 'Feature recompute job data must be an object.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createFeatureRecomputeJobData(),
|
||||||
|
platformRoute: 'invalid',
|
||||||
|
},
|
||||||
|
expectedError: 'Analysis job platformRoute is unsupported.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createFeatureRecomputeJobData(),
|
||||||
|
queueId: 430,
|
||||||
|
},
|
||||||
|
expectedError: 'Analysis job queueId is unsupported.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createFeatureRecomputeJobData(),
|
||||||
|
batchSize: Number.NaN,
|
||||||
|
},
|
||||||
|
expectedError: 'Feature recompute job batchSize must be finite.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createFeatureRecomputeJobData(),
|
||||||
|
puuid: ' ',
|
||||||
|
},
|
||||||
|
expectedError: 'Analysis job puuid is out of range.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createFeatureRecomputeJobData(),
|
||||||
|
puuid: 'x'.repeat(129),
|
||||||
|
},
|
||||||
|
expectedError: 'Analysis job puuid is out of range.',
|
||||||
|
},
|
||||||
|
])(
|
||||||
|
'rejects malformed feature recompute payloads',
|
||||||
|
async ({ data, expectedError }) => {
|
||||||
|
const processFeatureRecomputeJob = jest.fn();
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processFeatureRecomputeJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'recompute-job-1',
|
||||||
|
name: FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
opts: { attempts: 2 },
|
||||||
|
data,
|
||||||
|
} as Job<unknown>),
|
||||||
|
).rejects.toThrow(expectedError);
|
||||||
|
expect(processFeatureRecomputeJob).not.toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
data: null,
|
||||||
|
expectedError: 'Baseline computation job data must be an object.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createBaselineComputationJobData(),
|
||||||
|
cohort: 'INVALID',
|
||||||
|
},
|
||||||
|
expectedError: 'Baseline computation job cohort is unsupported.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createBaselineComputationJobData(),
|
||||||
|
patch: ' ',
|
||||||
|
},
|
||||||
|
expectedError: 'Analysis job patch is out of range.',
|
||||||
|
},
|
||||||
|
])(
|
||||||
|
'rejects malformed baseline computation payloads',
|
||||||
|
async ({ data, expectedError }) => {
|
||||||
|
const processBaselineComputationJob = jest.fn();
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processBaselineComputationJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'baseline-job-1',
|
||||||
|
name: BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
opts: { attempts: 1 },
|
||||||
|
data,
|
||||||
|
} as Job<unknown>),
|
||||||
|
).rejects.toThrow(expectedError);
|
||||||
|
expect(processBaselineComputationJob).not.toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('rejects jobs without a BullMQ id', async () => {
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processUserAnalysisJob: jest.fn(),
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
processor.process({
|
||||||
|
data: createJobData(),
|
||||||
|
name: USER_ANALYSIS_JOB_NAME,
|
||||||
|
} as Job<unknown>),
|
||||||
|
).rejects.toThrow('Analysis job is missing a BullMQ job id.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects unsupported job names before processing data', async () => {
|
||||||
|
const processUserAnalysisJob = jest.fn();
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processUserAnalysisJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
processor.process({
|
||||||
|
id: 'analysis-job-1',
|
||||||
|
name: 'unexpected',
|
||||||
|
data: createJobData(),
|
||||||
|
} as Job<unknown>),
|
||||||
|
).rejects.toThrow('Unsupported analysis job name "unexpected".');
|
||||||
|
expect(processUserAnalysisJob).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects malformed Redis payloads', async () => {
|
||||||
|
const processUserAnalysisJob = jest.fn();
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processUserAnalysisJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'analysis-job-1',
|
||||||
|
name: USER_ANALYSIS_JOB_NAME,
|
||||||
|
opts: { attempts: 2 },
|
||||||
|
data: {
|
||||||
|
...createJobData(),
|
||||||
|
regionalRoute: 'americas',
|
||||||
|
},
|
||||||
|
} as Job<unknown>),
|
||||||
|
).rejects.toThrow(
|
||||||
|
'Analysis job regionalRoute does not match platformRoute.',
|
||||||
|
);
|
||||||
|
expect(processUserAnalysisJob).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('normalizes requested match count from valid queue payloads', async () => {
|
||||||
|
const processUserAnalysisJob = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const processor = new AnalysisProcessor({
|
||||||
|
processUserAnalysisJob,
|
||||||
|
} as unknown as AnalysisPipelineService);
|
||||||
|
|
||||||
|
await processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'analysis-job-1',
|
||||||
|
name: USER_ANALYSIS_JOB_NAME,
|
||||||
|
opts: { attempts: 2 },
|
||||||
|
data: createJobData({ requestedMatchCount: 999 }),
|
||||||
|
} as Job<unknown>);
|
||||||
|
|
||||||
|
expect(processUserAnalysisJob).toHaveBeenCalledWith(
|
||||||
|
createJobData({ requestedMatchCount: 50 }),
|
||||||
|
'analysis-job-1',
|
||||||
|
{ isFinalAttempt: false },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||||
|
import type { Job } from 'bullmq';
|
||||||
|
import { BASELINE_COHORTS } from '../global/database/schemas';
|
||||||
|
import {
|
||||||
|
ANALYSIS_QUEUE_NAME,
|
||||||
|
BASELINE_COMPUTATION_JOB_NAME,
|
||||||
|
FEATURE_RECOMPUTE_JOB_NAME,
|
||||||
|
normalizeFeatureRecomputeBatchSize,
|
||||||
|
normalizeRequestedMatchCount,
|
||||||
|
USER_ANALYSIS_JOB_NAME,
|
||||||
|
} from './analysis.constants';
|
||||||
|
import { AnalysisPipelineService } from './analysis-pipeline.service';
|
||||||
|
import type {
|
||||||
|
BaselineComputationJobData,
|
||||||
|
FeatureRecomputeJobData,
|
||||||
|
UserAnalysisJobData,
|
||||||
|
} from './analysis.types';
|
||||||
|
import {
|
||||||
|
RIOT_PLATFORM_ROUTES,
|
||||||
|
RIOT_REGIONAL_ROUTES,
|
||||||
|
toRegionalRoute,
|
||||||
|
type RiotPlatformRoute,
|
||||||
|
type RiotRegionalRoute,
|
||||||
|
} from '../riot/riot.types';
|
||||||
|
|
||||||
|
@Processor(ANALYSIS_QUEUE_NAME)
|
||||||
|
export class AnalysisProcessor extends WorkerHost {
|
||||||
|
constructor(
|
||||||
|
private readonly analysisPipelineService: AnalysisPipelineService,
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async process(job: Job<unknown>): Promise<void> {
|
||||||
|
if (!job.id) {
|
||||||
|
throw new Error('Analysis job is missing a BullMQ job id.');
|
||||||
|
}
|
||||||
|
if (job.name === USER_ANALYSIS_JOB_NAME) {
|
||||||
|
const data = this.parseUserAnalysisJobData(job.data);
|
||||||
|
await this.analysisPipelineService.processUserAnalysisJob(data, job.id, {
|
||||||
|
isFinalAttempt: this.isFinalAttempt(job),
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (job.name === FEATURE_RECOMPUTE_JOB_NAME) {
|
||||||
|
const data = this.parseFeatureRecomputeJobData(job.data);
|
||||||
|
await this.analysisPipelineService.processFeatureRecomputeJob(
|
||||||
|
data,
|
||||||
|
job.id,
|
||||||
|
{
|
||||||
|
isFinalAttempt: this.isFinalAttempt(job),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (job.name === BASELINE_COMPUTATION_JOB_NAME) {
|
||||||
|
const data = this.parseBaselineComputationJobData(job.data);
|
||||||
|
await this.analysisPipelineService.processBaselineComputationJob(
|
||||||
|
data,
|
||||||
|
job.id,
|
||||||
|
{
|
||||||
|
isFinalAttempt: this.isFinalAttempt(job),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error(`Unsupported analysis job name "${job.name}".`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseUserAnalysisJobData(value: unknown): UserAnalysisJobData {
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
throw new Error('Analysis job data must be an object.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = value as Record<string, unknown>;
|
||||||
|
const gameName = this.parseBoundedString(record.gameName, 'gameName', 64);
|
||||||
|
const tagLine = this.parseBoundedString(record.tagLine, 'tagLine', 16);
|
||||||
|
const platformRoute = this.parsePlatformRoute(record.platformRoute);
|
||||||
|
const regionalRoute = this.parseRegionalRoute(record.regionalRoute);
|
||||||
|
if (regionalRoute !== toRegionalRoute(platformRoute)) {
|
||||||
|
throw new Error(
|
||||||
|
'Analysis job regionalRoute does not match platformRoute.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const queueId = this.parseQueueId(record.queueId);
|
||||||
|
const requestedMatchCount = this.parseRequestedMatchCount(
|
||||||
|
record.requestedMatchCount,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
gameName,
|
||||||
|
tagLine,
|
||||||
|
platformRoute,
|
||||||
|
regionalRoute,
|
||||||
|
queueId,
|
||||||
|
requestedMatchCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseFeatureRecomputeJobData(
|
||||||
|
value: unknown,
|
||||||
|
): FeatureRecomputeJobData {
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
throw new Error('Feature recompute job data must be an object.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = value as Record<string, unknown>;
|
||||||
|
const platformRoute = this.parsePlatformRoute(record.platformRoute);
|
||||||
|
const queueId = this.parseQueueId(record.queueId);
|
||||||
|
const batchSize = this.parseFeatureRecomputeBatchSize(record.batchSize);
|
||||||
|
const puuid =
|
||||||
|
record.puuid === undefined
|
||||||
|
? undefined
|
||||||
|
: this.parseBoundedString(record.puuid, 'puuid', 128);
|
||||||
|
|
||||||
|
return {
|
||||||
|
platformRoute,
|
||||||
|
queueId,
|
||||||
|
batchSize,
|
||||||
|
...(puuid ? { puuid } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseBaselineComputationJobData(
|
||||||
|
value: unknown,
|
||||||
|
): BaselineComputationJobData {
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
throw new Error('Baseline computation job data must be an object.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = value as Record<string, unknown>;
|
||||||
|
const platformRoute = this.parsePlatformRoute(record.platformRoute);
|
||||||
|
const queueId = this.parseQueueId(record.queueId);
|
||||||
|
const cohort = this.parseBaselineCohort(record.cohort);
|
||||||
|
const patch =
|
||||||
|
record.patch === undefined
|
||||||
|
? 'ALL'
|
||||||
|
: this.parseBoundedString(record.patch, 'patch', 32);
|
||||||
|
|
||||||
|
return {
|
||||||
|
platformRoute,
|
||||||
|
queueId,
|
||||||
|
cohort,
|
||||||
|
patch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseBoundedString(
|
||||||
|
value: unknown,
|
||||||
|
fieldName: string,
|
||||||
|
maximumLength: number,
|
||||||
|
): string {
|
||||||
|
if (typeof value !== 'string') {
|
||||||
|
throw new Error(`Analysis job ${fieldName} must be a string.`);
|
||||||
|
}
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (trimmed.length === 0 || trimmed.length > maximumLength) {
|
||||||
|
throw new Error(`Analysis job ${fieldName} is out of range.`);
|
||||||
|
}
|
||||||
|
return trimmed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parsePlatformRoute(value: unknown): RiotPlatformRoute {
|
||||||
|
if (
|
||||||
|
typeof value !== 'string' ||
|
||||||
|
!RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
|
||||||
|
) {
|
||||||
|
throw new Error('Analysis job platformRoute is unsupported.');
|
||||||
|
}
|
||||||
|
return value as RiotPlatformRoute;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseRegionalRoute(value: unknown): RiotRegionalRoute {
|
||||||
|
if (
|
||||||
|
typeof value !== 'string' ||
|
||||||
|
!RIOT_REGIONAL_ROUTES.includes(value as RiotRegionalRoute)
|
||||||
|
) {
|
||||||
|
throw new Error('Analysis job regionalRoute is unsupported.');
|
||||||
|
}
|
||||||
|
return value as RiotRegionalRoute;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseQueueId(value: unknown): number {
|
||||||
|
if (value !== 420) {
|
||||||
|
throw new Error('Analysis job queueId is unsupported.');
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseRequestedMatchCount(value: unknown): number {
|
||||||
|
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||||
|
throw new Error('Analysis job requestedMatchCount must be finite.');
|
||||||
|
}
|
||||||
|
return normalizeRequestedMatchCount(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseBaselineCohort(
|
||||||
|
value: unknown,
|
||||||
|
): BaselineComputationJobData['cohort'] {
|
||||||
|
if (value === undefined) {
|
||||||
|
return 'MASTER_PLUS';
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
typeof value !== 'string' ||
|
||||||
|
!BASELINE_COHORTS.includes(
|
||||||
|
value as NonNullable<BaselineComputationJobData['cohort']>,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
throw new Error('Baseline computation job cohort is unsupported.');
|
||||||
|
}
|
||||||
|
return value as NonNullable<BaselineComputationJobData['cohort']>;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseFeatureRecomputeBatchSize(value: unknown): number {
|
||||||
|
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||||
|
throw new Error('Feature recompute job batchSize must be finite.');
|
||||||
|
}
|
||||||
|
return normalizeFeatureRecomputeBatchSize(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isFinalAttempt(job: Job<unknown>): boolean {
|
||||||
|
const attempts =
|
||||||
|
typeof job.opts?.attempts === 'number' && job.opts.attempts > 0
|
||||||
|
? job.opts.attempts
|
||||||
|
: 1;
|
||||||
|
return job.attemptsMade + 1 >= attempts;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,141 @@
|
|||||||
|
import type { MetricId, Role, TierComparison } from '@persona-lenz/shared';
|
||||||
|
import type {
|
||||||
|
BaselineCohort,
|
||||||
|
LaneOpponentRef,
|
||||||
|
NormalizationMethod,
|
||||||
|
SeedSource,
|
||||||
|
TeamPositionOrUnknown,
|
||||||
|
} from '../global/database/schemas';
|
||||||
|
import type { RiotPlatformRoute, RiotRegionalRoute } from '../riot/riot.types';
|
||||||
|
|
||||||
|
export interface UserAnalysisJobData {
|
||||||
|
gameName: string;
|
||||||
|
tagLine: string;
|
||||||
|
platformRoute: RiotPlatformRoute;
|
||||||
|
regionalRoute: RiotRegionalRoute;
|
||||||
|
queueId: number;
|
||||||
|
requestedMatchCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FeatureRecomputeJobData {
|
||||||
|
platformRoute: RiotPlatformRoute;
|
||||||
|
queueId: number;
|
||||||
|
batchSize: number;
|
||||||
|
puuid?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SeedCollectionJobData {
|
||||||
|
platformRoute: RiotPlatformRoute;
|
||||||
|
queueId: number;
|
||||||
|
sourceLimits?: Partial<Record<SeedSource, number>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BaselineComputationJobData {
|
||||||
|
platformRoute: RiotPlatformRoute;
|
||||||
|
queueId: number;
|
||||||
|
cohort?: BaselineCohort;
|
||||||
|
patch?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SeedAccountPipelineData {
|
||||||
|
puuid: string;
|
||||||
|
platformRoute: RiotPlatformRoute;
|
||||||
|
regionalRoute: RiotRegionalRoute;
|
||||||
|
queueId: number;
|
||||||
|
requestedMatchCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SeedAccountPipelineResult {
|
||||||
|
puuid: string;
|
||||||
|
fetchedMatches: number;
|
||||||
|
extractedFeatures: number;
|
||||||
|
profileBuilt: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExtractedPlayerMatchFeature {
|
||||||
|
matchId: string;
|
||||||
|
puuid: string;
|
||||||
|
queueId: number;
|
||||||
|
role: TeamPositionOrUnknown;
|
||||||
|
championId: number;
|
||||||
|
gameCreation: number;
|
||||||
|
gameDurationSec: number;
|
||||||
|
win: boolean;
|
||||||
|
patch: string;
|
||||||
|
features: Record<string, number>;
|
||||||
|
normalized: Record<string, number>;
|
||||||
|
vector: number[];
|
||||||
|
featureSchemaVersion: number;
|
||||||
|
normalizationMethod: NormalizationMethod;
|
||||||
|
confidence: number;
|
||||||
|
timelineProcessed: boolean;
|
||||||
|
laneOpponent?: LaneOpponentRef;
|
||||||
|
derived?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BuiltPlayerProfile {
|
||||||
|
puuid: string;
|
||||||
|
queueId: number;
|
||||||
|
mainRole: Role;
|
||||||
|
roleDistribution: Partial<Record<Role, number>>;
|
||||||
|
sampleGameCount: number;
|
||||||
|
championPool: Array<{
|
||||||
|
championId: number;
|
||||||
|
games: number;
|
||||||
|
wins: number;
|
||||||
|
}>;
|
||||||
|
profile: Record<string, number>;
|
||||||
|
vector: number[];
|
||||||
|
featureSchemaVersion: number;
|
||||||
|
normalizationMethod: NormalizationMethod;
|
||||||
|
confidence: number;
|
||||||
|
patches: string[];
|
||||||
|
lastMatchAt?: Date;
|
||||||
|
isSeed: boolean;
|
||||||
|
tier?: string;
|
||||||
|
division?: string;
|
||||||
|
leaguePoints?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChampionPoolEntry {
|
||||||
|
championId: number;
|
||||||
|
games: number;
|
||||||
|
wins: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SimilarMetric {
|
||||||
|
metricId: MetricId;
|
||||||
|
currentValue: number;
|
||||||
|
otherValue: number;
|
||||||
|
absoluteGap: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LeadMetric {
|
||||||
|
metricId: MetricId;
|
||||||
|
currentValue: number;
|
||||||
|
otherValue: number;
|
||||||
|
lead: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SimilarPlayer {
|
||||||
|
puuid: string;
|
||||||
|
similarityScore: number;
|
||||||
|
finalScore: number;
|
||||||
|
tier?: string;
|
||||||
|
division?: string;
|
||||||
|
leaguePoints?: number;
|
||||||
|
tierComparison: TierComparison;
|
||||||
|
mainRole: Role;
|
||||||
|
mainChampions: ChampionPoolEntry[];
|
||||||
|
sampleGameCount: number;
|
||||||
|
similarMetrics: SimilarMetric[];
|
||||||
|
strongerMetrics: LeadMetric[];
|
||||||
|
weakerMetrics: LeadMetric[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SimilarPlayersResult {
|
||||||
|
puuid: string;
|
||||||
|
queueId: number;
|
||||||
|
profileUpdatedAt: Date;
|
||||||
|
matches: SimilarPlayer[];
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
import {
|
||||||
|
createBullMqOptions,
|
||||||
|
resolveBullMqRedisConnection,
|
||||||
|
} from './bullmq.config';
|
||||||
|
|
||||||
|
describe('BullMQ config', () => {
|
||||||
|
it('parses redis URLs into BullMQ connection options', () => {
|
||||||
|
expect(
|
||||||
|
resolveBullMqRedisConnection('redis://worker:secret@redis.local:6380/2'),
|
||||||
|
).toMatchObject({
|
||||||
|
host: 'redis.local',
|
||||||
|
port: 6380,
|
||||||
|
username: 'worker',
|
||||||
|
password: 'secret',
|
||||||
|
db: 2,
|
||||||
|
maxRetriesPerRequest: null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enables TLS for rediss URLs', () => {
|
||||||
|
expect(resolveBullMqRedisConnection('rediss://redis.local')).toMatchObject({
|
||||||
|
host: 'redis.local',
|
||||||
|
port: 6379,
|
||||||
|
tls: {},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects malformed Redis URLs without an explicit host', () => {
|
||||||
|
expect(() => resolveBullMqRedisConnection('redis:///0')).toThrow(
|
||||||
|
'REDIS_URL must include a hostname.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates root options from SecretService without exposing secrets', async () => {
|
||||||
|
const secretService = {
|
||||||
|
get: jest
|
||||||
|
.fn<Promise<string>, [string]>()
|
||||||
|
.mockResolvedValue('redis://localhost:6379/0'),
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(createBullMqOptions(secretService)).resolves.toMatchObject({
|
||||||
|
connection: {
|
||||||
|
host: 'localhost',
|
||||||
|
port: 6379,
|
||||||
|
db: 0,
|
||||||
|
maxRetriesPerRequest: null,
|
||||||
|
},
|
||||||
|
defaultJobOptions: {
|
||||||
|
attempts: 2,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(secretService.get).toHaveBeenCalledWith('REDIS_URL');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import type { BullRootModuleOptions } from '@nestjs/bullmq';
|
||||||
|
import type { QueueOptions } from 'bullmq';
|
||||||
|
import type { SecretService } from '../global/secret/secret.service';
|
||||||
|
|
||||||
|
export type BullMqConnectionOptions = NonNullable<QueueOptions['connection']>;
|
||||||
|
|
||||||
|
function parseRedisDatabase(pathname: string): number {
|
||||||
|
const trimmedPath = pathname.replace(/^\/+/u, '');
|
||||||
|
if (!trimmedPath) return 0;
|
||||||
|
|
||||||
|
const database = Number(trimmedPath);
|
||||||
|
if (!Number.isInteger(database) || database < 0) {
|
||||||
|
throw new Error('REDIS_URL must include a non-negative integer database.');
|
||||||
|
}
|
||||||
|
return database;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveBullMqRedisConnection(
|
||||||
|
redisUrl: string,
|
||||||
|
): BullMqConnectionOptions {
|
||||||
|
const parsedUrl = new URL(redisUrl);
|
||||||
|
if (parsedUrl.protocol !== 'redis:' && parsedUrl.protocol !== 'rediss:') {
|
||||||
|
throw new Error('REDIS_URL must use redis:// or rediss://.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!parsedUrl.hostname) {
|
||||||
|
throw new Error('REDIS_URL must include a hostname.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const connection: BullMqConnectionOptions = {
|
||||||
|
host: parsedUrl.hostname,
|
||||||
|
port: parsedUrl.port ? Number(parsedUrl.port) : 6379,
|
||||||
|
db: parseRedisDatabase(parsedUrl.pathname),
|
||||||
|
maxRetriesPerRequest: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (parsedUrl.username) {
|
||||||
|
connection.username = decodeURIComponent(parsedUrl.username);
|
||||||
|
}
|
||||||
|
if (parsedUrl.password) {
|
||||||
|
connection.password = decodeURIComponent(parsedUrl.password);
|
||||||
|
}
|
||||||
|
if (parsedUrl.protocol === 'rediss:') {
|
||||||
|
connection.tls = {};
|
||||||
|
}
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createBullMqOptions(
|
||||||
|
secretService: Pick<SecretService, 'get'>,
|
||||||
|
): Promise<BullRootModuleOptions> {
|
||||||
|
const redisUrl = await secretService.get<string>('REDIS_URL');
|
||||||
|
|
||||||
|
return {
|
||||||
|
connection: resolveBullMqRedisConnection(redisUrl),
|
||||||
|
defaultJobOptions: {
|
||||||
|
attempts: 2,
|
||||||
|
backoff: {
|
||||||
|
type: 'exponential',
|
||||||
|
delay: 1_000,
|
||||||
|
},
|
||||||
|
removeOnComplete: {
|
||||||
|
age: 86_400,
|
||||||
|
count: 1_000,
|
||||||
|
},
|
||||||
|
removeOnFail: {
|
||||||
|
age: 604_800,
|
||||||
|
count: 5_000,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,275 @@
|
|||||||
|
import { FEATURE_SCHEMA_VERSION, VECTOR_METRICS } from '@persona-lenz/shared';
|
||||||
|
import { FeatureExtractorService } from './feature-extractor.service';
|
||||||
|
|
||||||
|
function createMatchPayload(overrides: Record<string, unknown> = {}) {
|
||||||
|
const currentPlayer = {
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: 'MIDDLE',
|
||||||
|
championId: 103,
|
||||||
|
kills: 6,
|
||||||
|
deaths: 2,
|
||||||
|
assists: 8,
|
||||||
|
totalDamageDealtToChampions: 24_000,
|
||||||
|
goldEarned: 12_000,
|
||||||
|
totalMinionsKilled: 210,
|
||||||
|
neutralMinionsKilled: 12,
|
||||||
|
visionScore: 24,
|
||||||
|
wardsKilled: 4,
|
||||||
|
detectorWardsPlaced: 3,
|
||||||
|
win: true,
|
||||||
|
challenges: {
|
||||||
|
kda: 7,
|
||||||
|
killParticipation: 0.7,
|
||||||
|
teamDamagePercentage: 0.32,
|
||||||
|
damagePerMinute: 800,
|
||||||
|
goldPerMinute: 400,
|
||||||
|
visionScorePerMinute: 0.8,
|
||||||
|
controlWardsPlaced: 3,
|
||||||
|
dragonTakedowns: 1,
|
||||||
|
baronTakedowns: 1,
|
||||||
|
riftHeraldTakedowns: 0,
|
||||||
|
soloKills: 2,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
metadata: {
|
||||||
|
matchId: 'KR_1',
|
||||||
|
participants: ['target-puuid', 'ally-puuid', 'enemy-puuid'],
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
gameCreation: 1_700_000_000_000,
|
||||||
|
gameDuration: 1800,
|
||||||
|
gameVersion: '26.13.123.456',
|
||||||
|
queueId: 420,
|
||||||
|
participants: [
|
||||||
|
currentPlayer,
|
||||||
|
{
|
||||||
|
puuid: 'ally-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: 'JUNGLE',
|
||||||
|
championId: 64,
|
||||||
|
kills: 10,
|
||||||
|
totalDamageDealtToChampions: 30_000,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
puuid: 'enemy-puuid',
|
||||||
|
teamId: 200,
|
||||||
|
teamPosition: 'MIDDLE',
|
||||||
|
championId: 134,
|
||||||
|
kills: 4,
|
||||||
|
totalDamageDealtToChampions: 16_000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
...overrides,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('FeatureExtractorService', () => {
|
||||||
|
const service = new FeatureExtractorService();
|
||||||
|
|
||||||
|
it('extracts MVP 1 raw metrics and vector values in registry order', () => {
|
||||||
|
const feature = service.extractPlayerMatchFeature(
|
||||||
|
createMatchPayload(),
|
||||||
|
'target-puuid',
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(feature.matchId).toBe('KR_1');
|
||||||
|
expect(feature.role).toBe('MIDDLE');
|
||||||
|
expect(feature.laneOpponent).toEqual({
|
||||||
|
puuid: 'enemy-puuid',
|
||||||
|
championId: 134,
|
||||||
|
});
|
||||||
|
expect(feature.patch).toBe('26.13');
|
||||||
|
expect(feature.features).toMatchObject({
|
||||||
|
kda: 7,
|
||||||
|
killParticipation: 0.7,
|
||||||
|
damageShare: 0.32,
|
||||||
|
damagePerMin: 800,
|
||||||
|
goldPerMin: 400,
|
||||||
|
csPerMin: 7.4,
|
||||||
|
visionScorePerMin: 0.8,
|
||||||
|
wardsKilledPerMin: 4 / 30,
|
||||||
|
controlWardsPlaced: 3,
|
||||||
|
deathsPerMin: 2 / 30,
|
||||||
|
objectiveParticipation: 2,
|
||||||
|
soloKills: 2,
|
||||||
|
});
|
||||||
|
expect(feature.vector).toEqual(
|
||||||
|
VECTOR_METRICS.map((metric) => feature.normalized[metric.id] ?? 0),
|
||||||
|
);
|
||||||
|
expect(feature.vector).toHaveLength(VECTOR_METRICS.length);
|
||||||
|
expect(feature.featureSchemaVersion).toBe(FEATURE_SCHEMA_VERSION);
|
||||||
|
expect(feature.confidence).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('leaves registry metrics without raw observations out of normalized values', () => {
|
||||||
|
const actualShared = jest.requireActual<
|
||||||
|
typeof import('@persona-lenz/shared')
|
||||||
|
>('@persona-lenz/shared');
|
||||||
|
const metrics = [
|
||||||
|
...actualShared.METRICS,
|
||||||
|
{
|
||||||
|
id: 'futureTimelineMetric',
|
||||||
|
label: 'Future timeline metric',
|
||||||
|
direction: 'higherIsBetter' as const,
|
||||||
|
kind: 'scalar' as const,
|
||||||
|
includeInVector: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const vectorMetrics = metrics.filter((metric) => metric.includeInVector);
|
||||||
|
|
||||||
|
let feature:
|
||||||
|
| ReturnType<FeatureExtractorService['extractPlayerMatchFeature']>
|
||||||
|
| undefined;
|
||||||
|
|
||||||
|
jest.isolateModules(() => {
|
||||||
|
jest.doMock('@persona-lenz/shared', () => ({
|
||||||
|
...actualShared,
|
||||||
|
FEATURE_SCHEMA_VERSION: 99,
|
||||||
|
METRICS: metrics,
|
||||||
|
VECTOR_METRICS: vectorMetrics,
|
||||||
|
}));
|
||||||
|
const { FeatureExtractorService: MockedFeatureExtractorService } =
|
||||||
|
jest.requireActual<typeof import('./feature-extractor.service')>(
|
||||||
|
'./feature-extractor.service',
|
||||||
|
);
|
||||||
|
|
||||||
|
feature = new MockedFeatureExtractorService().extractPlayerMatchFeature(
|
||||||
|
createMatchPayload(),
|
||||||
|
'target-puuid',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
jest.dontMock('@persona-lenz/shared');
|
||||||
|
|
||||||
|
expect(feature?.features.futureTimelineMetric).toBeUndefined();
|
||||||
|
expect(feature?.normalized.futureTimelineMetric).toBeUndefined();
|
||||||
|
expect(feature?.vector).toHaveLength(vectorMetrics.length);
|
||||||
|
expect(feature?.vector.at(-1)).toBe(0);
|
||||||
|
expect(feature?.featureSchemaVersion).toBe(99);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to manual calculations when challenges are missing', () => {
|
||||||
|
const payload = createMatchPayload({
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: 'MIDDLE',
|
||||||
|
championId: 103,
|
||||||
|
kills: 6,
|
||||||
|
deaths: 2,
|
||||||
|
assists: 8,
|
||||||
|
totalDamageDealtToChampions: 24_000,
|
||||||
|
goldEarned: 12_000,
|
||||||
|
totalMinionsKilled: 210,
|
||||||
|
neutralMinionsKilled: 12,
|
||||||
|
visionScore: 24,
|
||||||
|
wardsKilled: 4,
|
||||||
|
detectorWardsPlaced: 3,
|
||||||
|
win: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
puuid: 'ally-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: 'JUNGLE',
|
||||||
|
championId: 64,
|
||||||
|
kills: 14,
|
||||||
|
totalDamageDealtToChampions: 36_000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const feature = service.extractPlayerMatchFeature(payload, 'target-puuid');
|
||||||
|
|
||||||
|
expect(feature.features.kda).toBe(7);
|
||||||
|
expect(feature.features.killParticipation).toBe(0.7);
|
||||||
|
expect(feature.features.damageShare).toBe(0.4);
|
||||||
|
expect(feature.features.damagePerMin).toBe(800);
|
||||||
|
expect(feature.features.goldPerMin).toBe(400);
|
||||||
|
expect(feature.features.controlWardsPlaced).toBe(3);
|
||||||
|
expect(feature.features.objectiveParticipation).toBe(0);
|
||||||
|
expect(feature.features.soloKills).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks unknown roles and short games with lower confidence', () => {
|
||||||
|
const payload = createMatchPayload({
|
||||||
|
gameDuration: 900,
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: '',
|
||||||
|
championId: 103,
|
||||||
|
kills: 1,
|
||||||
|
deaths: 2,
|
||||||
|
assists: 1,
|
||||||
|
totalDamageDealtToChampions: 5_000,
|
||||||
|
goldEarned: 6_000,
|
||||||
|
totalMinionsKilled: 100,
|
||||||
|
neutralMinionsKilled: 0,
|
||||||
|
visionScore: 10,
|
||||||
|
wardsKilled: 1,
|
||||||
|
detectorWardsPlaced: 0,
|
||||||
|
win: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const feature = service.extractPlayerMatchFeature(payload, 'target-puuid');
|
||||||
|
|
||||||
|
expect(feature.role).toBe('UNKNOWN');
|
||||||
|
expect(feature.confidence).toBe(0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits lane opponent and lowers confidence when same-position enemy is missing', () => {
|
||||||
|
const payload = createMatchPayload({
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: 'MIDDLE',
|
||||||
|
championId: 103,
|
||||||
|
kills: 6,
|
||||||
|
deaths: 2,
|
||||||
|
assists: 8,
|
||||||
|
totalDamageDealtToChampions: 24_000,
|
||||||
|
goldEarned: 12_000,
|
||||||
|
totalMinionsKilled: 210,
|
||||||
|
neutralMinionsKilled: 12,
|
||||||
|
visionScore: 24,
|
||||||
|
wardsKilled: 4,
|
||||||
|
detectorWardsPlaced: 3,
|
||||||
|
win: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
puuid: 'enemy-puuid',
|
||||||
|
teamId: 200,
|
||||||
|
teamPosition: 'TOP',
|
||||||
|
championId: 266,
|
||||||
|
kills: 4,
|
||||||
|
totalDamageDealtToChampions: 16_000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const feature = service.extractPlayerMatchFeature(payload, 'target-puuid');
|
||||||
|
|
||||||
|
expect(feature.laneOpponent).toBeUndefined();
|
||||||
|
expect(feature.confidence).toBe(0.7);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks known-role short games with short-game confidence only', () => {
|
||||||
|
const payload = createMatchPayload({
|
||||||
|
gameDuration: 900,
|
||||||
|
});
|
||||||
|
|
||||||
|
const feature = service.extractPlayerMatchFeature(payload, 'target-puuid');
|
||||||
|
|
||||||
|
expect(feature.role).toBe('MIDDLE');
|
||||||
|
expect(feature.confidence).toBe(0.8);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,260 @@
|
|||||||
|
import {
|
||||||
|
FEATURE_SCHEMA_VERSION,
|
||||||
|
METRICS,
|
||||||
|
VECTOR_METRICS,
|
||||||
|
type MetricDefinition,
|
||||||
|
type Role,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import type {
|
||||||
|
LaneOpponentRef,
|
||||||
|
TeamPositionOrUnknown,
|
||||||
|
} from '../global/database/schemas';
|
||||||
|
import type { ExtractedPlayerMatchFeature } from './analysis.types';
|
||||||
|
|
||||||
|
interface MatchParticipant {
|
||||||
|
assists?: number;
|
||||||
|
challenges?: Record<string, unknown>;
|
||||||
|
championId?: number;
|
||||||
|
deaths?: number;
|
||||||
|
detectorWardsPlaced?: number;
|
||||||
|
goldEarned?: number;
|
||||||
|
kills?: number;
|
||||||
|
neutralMinionsKilled?: number;
|
||||||
|
puuid?: string;
|
||||||
|
teamId?: number;
|
||||||
|
teamPosition?: string;
|
||||||
|
totalDamageDealtToChampions?: number;
|
||||||
|
totalMinionsKilled?: number;
|
||||||
|
visionScore?: number;
|
||||||
|
wardsKilled?: number;
|
||||||
|
win?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MatchInfo {
|
||||||
|
gameCreation?: number;
|
||||||
|
gameDuration?: number;
|
||||||
|
gameVersion?: string;
|
||||||
|
participants?: MatchParticipant[];
|
||||||
|
queueId?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MatchPayload {
|
||||||
|
info?: MatchInfo;
|
||||||
|
metadata?: {
|
||||||
|
matchId?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const TEAM_POSITIONS = new Set<Role>([
|
||||||
|
'TOP',
|
||||||
|
'JUNGLE',
|
||||||
|
'MIDDLE',
|
||||||
|
'BOTTOM',
|
||||||
|
'UTILITY',
|
||||||
|
]);
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Record<string, unknown> {
|
||||||
|
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function asNumber(value: unknown, fallback = 0): number {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asFiniteMetricValue(value: number | undefined): number | undefined {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? value
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function fromChallenge(
|
||||||
|
challenges: Record<string, unknown>,
|
||||||
|
key: string,
|
||||||
|
): number | undefined {
|
||||||
|
const value = challenges[key];
|
||||||
|
return typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? value
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ratio(numerator: number, denominator: number): number {
|
||||||
|
if (denominator <= 0) return 0;
|
||||||
|
return numerator / denominator;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeMetric(
|
||||||
|
metric: MetricDefinition,
|
||||||
|
role: Role,
|
||||||
|
rawValue: number,
|
||||||
|
): number {
|
||||||
|
const baseline = metric.baseline?.[role];
|
||||||
|
if (!baseline) return Math.max(0, Math.min(1, rawValue));
|
||||||
|
return Math.max(
|
||||||
|
0,
|
||||||
|
Math.min(1, (rawValue - baseline.min) / (baseline.max - baseline.min)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveRole(teamPosition: string | undefined): TeamPositionOrUnknown {
|
||||||
|
return TEAM_POSITIONS.has(teamPosition as Role)
|
||||||
|
? (teamPosition as Role)
|
||||||
|
: 'UNKNOWN';
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveNormalizationRole(role: TeamPositionOrUnknown): Role {
|
||||||
|
return role === 'UNKNOWN' ? 'MIDDLE' : role;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolvePatch(gameVersion: string | undefined): string {
|
||||||
|
const [major, minor] = (gameVersion ?? 'unknown').split('.');
|
||||||
|
if (!major || !minor) return 'unknown';
|
||||||
|
return `${major}.${minor}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveLaneOpponent(
|
||||||
|
participant: MatchParticipant,
|
||||||
|
participants: MatchParticipant[],
|
||||||
|
role: TeamPositionOrUnknown,
|
||||||
|
): LaneOpponentRef | undefined {
|
||||||
|
if (role === 'UNKNOWN' || participant.teamId === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const opponent = participants.find(
|
||||||
|
(candidate) =>
|
||||||
|
candidate.teamId !== participant.teamId &&
|
||||||
|
candidate.teamPosition === role &&
|
||||||
|
typeof candidate.puuid === 'string',
|
||||||
|
);
|
||||||
|
if (!opponent?.puuid) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
puuid: opponent.puuid,
|
||||||
|
championId: asNumber(opponent.championId),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class FeatureExtractorService {
|
||||||
|
public extractPlayerMatchFeature(
|
||||||
|
rawMatch: Record<string, unknown>,
|
||||||
|
puuid: string,
|
||||||
|
): ExtractedPlayerMatchFeature {
|
||||||
|
const payload = rawMatch as MatchPayload;
|
||||||
|
const info = payload.info ?? {};
|
||||||
|
const participants = info.participants ?? [];
|
||||||
|
const participant = participants.find(
|
||||||
|
(candidate) => candidate.puuid === puuid,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!participant) {
|
||||||
|
throw new Error(`Participant not found for puuid="${puuid}".`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const gameDurationSec = asNumber(info.gameDuration);
|
||||||
|
const gameMinutes = Math.max(gameDurationSec / 60, 1);
|
||||||
|
const teamId = participant.teamId;
|
||||||
|
const teamParticipants = participants.filter(
|
||||||
|
(candidate) => candidate.teamId === teamId,
|
||||||
|
);
|
||||||
|
const teamKills = teamParticipants.reduce(
|
||||||
|
(sum, candidate) => sum + asNumber(candidate.kills),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const teamDamage = teamParticipants.reduce(
|
||||||
|
(sum, candidate) => sum + asNumber(candidate.totalDamageDealtToChampions),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
const challenges = asRecord(participant.challenges);
|
||||||
|
const kills = asNumber(participant.kills);
|
||||||
|
const deaths = asNumber(participant.deaths);
|
||||||
|
const assists = asNumber(participant.assists);
|
||||||
|
const damage = asNumber(participant.totalDamageDealtToChampions);
|
||||||
|
const gold = asNumber(participant.goldEarned);
|
||||||
|
const minions =
|
||||||
|
asNumber(participant.totalMinionsKilled) +
|
||||||
|
asNumber(participant.neutralMinionsKilled);
|
||||||
|
|
||||||
|
const features: Record<string, number> = {
|
||||||
|
kda:
|
||||||
|
fromChallenge(challenges, 'kda') ??
|
||||||
|
(kills + assists) / Math.max(deaths, 1),
|
||||||
|
killParticipation:
|
||||||
|
fromChallenge(challenges, 'killParticipation') ??
|
||||||
|
ratio(kills + assists, teamKills),
|
||||||
|
damageShare:
|
||||||
|
fromChallenge(challenges, 'teamDamagePercentage') ??
|
||||||
|
ratio(damage, teamDamage),
|
||||||
|
damagePerMin:
|
||||||
|
fromChallenge(challenges, 'damagePerMinute') ?? damage / gameMinutes,
|
||||||
|
goldPerMin:
|
||||||
|
fromChallenge(challenges, 'goldPerMinute') ?? gold / gameMinutes,
|
||||||
|
csPerMin: minions / gameMinutes,
|
||||||
|
visionScorePerMin:
|
||||||
|
fromChallenge(challenges, 'visionScorePerMinute') ??
|
||||||
|
asNumber(participant.visionScore) / gameMinutes,
|
||||||
|
wardsKilledPerMin: asNumber(participant.wardsKilled) / gameMinutes,
|
||||||
|
controlWardsPlaced:
|
||||||
|
fromChallenge(challenges, 'controlWardsPlaced') ??
|
||||||
|
asNumber(participant.detectorWardsPlaced),
|
||||||
|
deathsPerMin: deaths / gameMinutes,
|
||||||
|
objectiveParticipation:
|
||||||
|
asNumber(challenges.dragonTakedowns) +
|
||||||
|
asNumber(challenges.baronTakedowns) +
|
||||||
|
asNumber(challenges.riftHeraldTakedowns),
|
||||||
|
soloKills: fromChallenge(challenges, 'soloKills') ?? 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
const role = resolveRole(participant.teamPosition);
|
||||||
|
const laneOpponent = resolveLaneOpponent(participant, participants, role);
|
||||||
|
const normalizationRole = resolveNormalizationRole(role);
|
||||||
|
const normalized = Object.fromEntries(
|
||||||
|
METRICS.flatMap((metric) => {
|
||||||
|
const rawValue = asFiniteMetricValue(features[metric.id]);
|
||||||
|
return rawValue === undefined
|
||||||
|
? []
|
||||||
|
: [[metric.id, normalizeMetric(metric, normalizationRole, rawValue)]];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
matchId: payload.metadata?.matchId ?? '',
|
||||||
|
puuid,
|
||||||
|
queueId: asNumber(info.queueId),
|
||||||
|
role,
|
||||||
|
championId: asNumber(participant.championId),
|
||||||
|
gameCreation: asNumber(info.gameCreation),
|
||||||
|
gameDurationSec,
|
||||||
|
win: participant.win === true,
|
||||||
|
patch: resolvePatch(info.gameVersion),
|
||||||
|
features,
|
||||||
|
normalized,
|
||||||
|
vector: VECTOR_METRICS.map((metric) => normalized[metric.id] ?? 0),
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
normalizationMethod: 'registry-baseline',
|
||||||
|
confidence: this.resolveConfidence(role, gameDurationSec, laneOpponent),
|
||||||
|
timelineProcessed: false,
|
||||||
|
...(laneOpponent ? { laneOpponent } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveConfidence(
|
||||||
|
role: TeamPositionOrUnknown,
|
||||||
|
gameDurationSec: number,
|
||||||
|
laneOpponent: LaneOpponentRef | undefined,
|
||||||
|
): number {
|
||||||
|
let confidence = 1;
|
||||||
|
if (role === 'UNKNOWN') confidence = Math.min(confidence, 0.5);
|
||||||
|
if (role !== 'UNKNOWN' && !laneOpponent)
|
||||||
|
confidence = Math.min(confidence, 0.7);
|
||||||
|
if (gameDurationSec < 1200) confidence = Math.min(confidence, 0.8);
|
||||||
|
return confidence;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
import { FEATURE_SCHEMA_VERSION } from '@persona-lenz/shared';
|
||||||
|
import type { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { PlayerMatchFeature } from '../global/database/schemas';
|
||||||
|
import { MetricBaselineService } from './metric-baseline.service';
|
||||||
|
|
||||||
|
interface ExecQuery<T> {
|
||||||
|
exec: jest.Mock<Promise<T>, []>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type AcknowledgedUpdate = { acknowledged: boolean };
|
||||||
|
type AggregateMock = jest.Mock<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>;
|
||||||
|
type UpdateOneMock = jest.Mock<
|
||||||
|
ExecQuery<AcknowledgedUpdate>,
|
||||||
|
[Record<string, unknown>, Record<string, unknown>, Record<string, unknown>?]
|
||||||
|
>;
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Record<string, unknown> {
|
||||||
|
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function execResolved<T>(value: T): ExecQuery<T> {
|
||||||
|
return { exec: jest.fn<Promise<T>, []>().mockResolvedValue(value) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function createStoredFeature(
|
||||||
|
overrides: Partial<PlayerMatchFeature> = {},
|
||||||
|
): PlayerMatchFeature {
|
||||||
|
return {
|
||||||
|
createdAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
matchId: 'KR_1',
|
||||||
|
puuid: 'seed-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
role: 'MIDDLE',
|
||||||
|
championId: 103,
|
||||||
|
gameCreation: 1_700_000_000_000,
|
||||||
|
gameDurationSec: 1_800,
|
||||||
|
win: true,
|
||||||
|
patch: '26.13',
|
||||||
|
features: {
|
||||||
|
csPerMin: 8,
|
||||||
|
kda: 3,
|
||||||
|
},
|
||||||
|
normalized: {},
|
||||||
|
vector: [],
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
normalizationMethod: 'registry-baseline',
|
||||||
|
confidence: 1,
|
||||||
|
timelineProcessed: true,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MetricBaselineService', () => {
|
||||||
|
it('computes p5-p95 breakpoints from seed raw feature values', async () => {
|
||||||
|
const seedFeatures = [10, 20, 30, 40, 50].map((kda, index) =>
|
||||||
|
createStoredFeature({
|
||||||
|
matchId: `KR_${index + 1}`,
|
||||||
|
features: {
|
||||||
|
kda,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const aggregate: AggregateMock = jest
|
||||||
|
.fn<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>()
|
||||||
|
.mockReturnValue(execResolved(seedFeatures));
|
||||||
|
const updateOne: UpdateOneMock = jest
|
||||||
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
||||||
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'playerMatchFeature'
|
||||||
|
? { aggregate }
|
||||||
|
: {
|
||||||
|
updateOne,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new MetricBaselineService(connectionService);
|
||||||
|
const computedAt = new Date('2026-07-03T12:00:00.000Z');
|
||||||
|
|
||||||
|
const result = await service.computeMetricBaselines({
|
||||||
|
cohort: 'MASTER_PLUS',
|
||||||
|
computedAt,
|
||||||
|
patch: 'ALL',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toEqual({
|
||||||
|
baselinesWritten: 1,
|
||||||
|
cohort: 'MASTER_PLUS',
|
||||||
|
computedAt,
|
||||||
|
patch: 'ALL',
|
||||||
|
samplesRead: 5,
|
||||||
|
});
|
||||||
|
const aggregatePipeline = aggregate.mock.calls[0]?.[0];
|
||||||
|
expect(aggregatePipeline).toContainEqual({
|
||||||
|
$match: {
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
role: {
|
||||||
|
$in: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(aggregatePipeline).toContainEqual({
|
||||||
|
$lookup: {
|
||||||
|
as: 'account',
|
||||||
|
foreignField: 'puuid',
|
||||||
|
from: 'account',
|
||||||
|
localField: 'puuid',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(updateOne).toHaveBeenCalledTimes(1);
|
||||||
|
const [, update, options] = updateOne.mock.calls[0];
|
||||||
|
const updateSet = asRecord(asRecord(update).$set);
|
||||||
|
expect(updateSet).toMatchObject({
|
||||||
|
cohort: 'MASTER_PLUS',
|
||||||
|
computedAt,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
metricId: 'kda',
|
||||||
|
patch: 'ALL',
|
||||||
|
role: 'MIDDLE',
|
||||||
|
sampleCount: 5,
|
||||||
|
});
|
||||||
|
const breakpoints = updateSet.percentileBreakpoints;
|
||||||
|
expect(Array.isArray(breakpoints)).toBe(true);
|
||||||
|
const numericBreakpoints = (breakpoints as unknown[]).filter(
|
||||||
|
(value): value is number => typeof value === 'number',
|
||||||
|
);
|
||||||
|
expect(numericBreakpoints).toHaveLength(19);
|
||||||
|
expect(numericBreakpoints[0]).toBe(12);
|
||||||
|
expect(numericBreakpoints[9]).toBe(30);
|
||||||
|
expect(numericBreakpoints[18]).toBe(48);
|
||||||
|
expect(options).toEqual({ upsert: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('groups baseline values by metric and role and skips unknown roles', async () => {
|
||||||
|
const seedFeatures = [
|
||||||
|
createStoredFeature({
|
||||||
|
role: 'MIDDLE',
|
||||||
|
features: {
|
||||||
|
csPerMin: 8,
|
||||||
|
kda: 3,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
createStoredFeature({
|
||||||
|
matchId: 'KR_2',
|
||||||
|
role: 'MIDDLE',
|
||||||
|
features: {
|
||||||
|
csPerMin: 9,
|
||||||
|
kda: 5,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
createStoredFeature({
|
||||||
|
matchId: 'KR_3',
|
||||||
|
role: 'TOP',
|
||||||
|
features: {
|
||||||
|
kda: 2,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
createStoredFeature({
|
||||||
|
matchId: 'KR_4',
|
||||||
|
role: 'UNKNOWN',
|
||||||
|
features: {
|
||||||
|
kda: 99,
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
const aggregate: AggregateMock = jest
|
||||||
|
.fn<ExecQuery<PlayerMatchFeature[]>, [unknown[]]>()
|
||||||
|
.mockReturnValue(execResolved(seedFeatures));
|
||||||
|
const updateOne: UpdateOneMock = jest
|
||||||
|
.fn<ExecQuery<AcknowledgedUpdate>, Parameters<UpdateOneMock>>()
|
||||||
|
.mockReturnValue(execResolved({ acknowledged: true }));
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'playerMatchFeature'
|
||||||
|
? { aggregate }
|
||||||
|
: {
|
||||||
|
updateOne,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new MetricBaselineService(connectionService);
|
||||||
|
|
||||||
|
await service.computeMetricBaselines({
|
||||||
|
cohort: 'MASTER_PLUS',
|
||||||
|
patch: '26.13',
|
||||||
|
});
|
||||||
|
|
||||||
|
const writtenBaselines = updateOne.mock.calls.map(([filter]) => filter);
|
||||||
|
expect(writtenBaselines).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
expect.objectContaining({ metricId: 'kda', role: 'MIDDLE' }),
|
||||||
|
expect.objectContaining({ metricId: 'csPerMin', role: 'MIDDLE' }),
|
||||||
|
expect.objectContaining({ metricId: 'kda', role: 'TOP' }),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(writtenBaselines).not.toContainEqual(
|
||||||
|
expect.objectContaining({ role: 'UNKNOWN' }),
|
||||||
|
);
|
||||||
|
expect(aggregate.mock.calls[0]?.[0]).toContainEqual({
|
||||||
|
$match: {
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
patch: '26.13',
|
||||||
|
role: {
|
||||||
|
$in: ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { FEATURE_SCHEMA_VERSION, METRICS, ROLES } from '@persona-lenz/shared';
|
||||||
|
import type { PipelineStage } from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type {
|
||||||
|
BaselineCohort,
|
||||||
|
PlayerMatchFeature,
|
||||||
|
TeamPosition,
|
||||||
|
} from '../global/database/schemas';
|
||||||
|
import { DEFAULT_SEED_COLLECTION_QUEUE_TYPE } from './analysis.constants';
|
||||||
|
|
||||||
|
export interface MetricBaselineComputationOptions {
|
||||||
|
cohort?: BaselineCohort;
|
||||||
|
computedAt?: Date;
|
||||||
|
patch?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MetricBaselineComputationResult {
|
||||||
|
baselinesWritten: number;
|
||||||
|
cohort: BaselineCohort;
|
||||||
|
computedAt: Date;
|
||||||
|
patch: string;
|
||||||
|
samplesRead: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
type BaselineFeatureSample = Pick<
|
||||||
|
PlayerMatchFeature,
|
||||||
|
'features' | 'patch' | 'role'
|
||||||
|
>;
|
||||||
|
|
||||||
|
const BASELINE_PERCENTILES = Array.from(
|
||||||
|
{ length: 19 },
|
||||||
|
(_, index) => (index + 1) * 0.05,
|
||||||
|
);
|
||||||
|
const MASTER_PLUS_TIERS = ['MASTER', 'GRANDMASTER', 'CHALLENGER'];
|
||||||
|
|
||||||
|
function isTeamPosition(value: unknown): value is TeamPosition {
|
||||||
|
return typeof value === 'string' && ROLES.includes(value as TeamPosition);
|
||||||
|
}
|
||||||
|
|
||||||
|
function finiteNumber(value: unknown): number | undefined {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? value
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function baselineKey(metricId: string, role: TeamPosition): string {
|
||||||
|
return `${metricId}\u0000${role}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function percentile(sortedValues: number[], percentileRank: number): number {
|
||||||
|
if (sortedValues.length === 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (sortedValues.length === 1) {
|
||||||
|
return sortedValues[0] ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rankIndex = (sortedValues.length - 1) * percentileRank;
|
||||||
|
const lowerIndex = Math.floor(rankIndex);
|
||||||
|
const upperIndex = Math.ceil(rankIndex);
|
||||||
|
const lowerValue = sortedValues[lowerIndex] ?? 0;
|
||||||
|
const upperValue = sortedValues[upperIndex] ?? lowerValue;
|
||||||
|
return lowerValue + (upperValue - lowerValue) * (rankIndex - lowerIndex);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MetricBaselineService {
|
||||||
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
|
public async computeMetricBaselines(
|
||||||
|
options: MetricBaselineComputationOptions = {},
|
||||||
|
): Promise<MetricBaselineComputationResult> {
|
||||||
|
const cohort = options.cohort ?? 'MASTER_PLUS';
|
||||||
|
const computedAt = options.computedAt ?? new Date();
|
||||||
|
const patch = options.patch ?? 'ALL';
|
||||||
|
const samples = await this.findBaselineFeatureSamples(cohort, patch);
|
||||||
|
const groupedMetricValues = this.groupMetricValues(samples);
|
||||||
|
const metricBaselineModel =
|
||||||
|
await this.connectionService.getModel('metricBaseline');
|
||||||
|
|
||||||
|
let baselinesWritten = 0;
|
||||||
|
for (const [key, values] of groupedMetricValues.entries()) {
|
||||||
|
const [metricId, role] = key.split('\u0000') as [string, TeamPosition];
|
||||||
|
const sortedValues = [...values].sort((left, right) => left - right);
|
||||||
|
const percentileBreakpoints = BASELINE_PERCENTILES.map((percentileRank) =>
|
||||||
|
percentile(sortedValues, percentileRank),
|
||||||
|
);
|
||||||
|
|
||||||
|
await metricBaselineModel
|
||||||
|
.updateOne(
|
||||||
|
{
|
||||||
|
metricId,
|
||||||
|
role,
|
||||||
|
cohort,
|
||||||
|
patch,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
metricId,
|
||||||
|
role,
|
||||||
|
cohort,
|
||||||
|
patch,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
sampleCount: sortedValues.length,
|
||||||
|
percentileBreakpoints,
|
||||||
|
computedAt,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ upsert: true },
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
baselinesWritten += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
baselinesWritten,
|
||||||
|
cohort,
|
||||||
|
computedAt,
|
||||||
|
patch,
|
||||||
|
samplesRead: samples.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findBaselineFeatureSamples(
|
||||||
|
cohort: BaselineCohort,
|
||||||
|
patch: string,
|
||||||
|
): Promise<BaselineFeatureSample[]> {
|
||||||
|
const playerMatchFeatureModel =
|
||||||
|
await this.connectionService.getModel('playerMatchFeature');
|
||||||
|
return playerMatchFeatureModel
|
||||||
|
.aggregate<BaselineFeatureSample>(this.baselineAggregation(cohort, patch))
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
private baselineAggregation(
|
||||||
|
cohort: BaselineCohort,
|
||||||
|
patch: string,
|
||||||
|
): PipelineStage[] {
|
||||||
|
const matchStage: Record<string, unknown> = {
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
role: {
|
||||||
|
$in: [...ROLES],
|
||||||
|
},
|
||||||
|
...(patch === 'ALL' ? {} : { patch }),
|
||||||
|
};
|
||||||
|
const accountMatchStage: Record<string, unknown> = {
|
||||||
|
'account.isSeed': true,
|
||||||
|
...(cohort === 'MASTER_PLUS'
|
||||||
|
? {
|
||||||
|
'account.tiers': {
|
||||||
|
$elemMatch: {
|
||||||
|
queueType: DEFAULT_SEED_COLLECTION_QUEUE_TYPE,
|
||||||
|
tier: {
|
||||||
|
$in: MASTER_PLUS_TIERS,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
$match: matchStage,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$lookup: {
|
||||||
|
from: 'account',
|
||||||
|
localField: 'puuid',
|
||||||
|
foreignField: 'puuid',
|
||||||
|
as: 'account',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$unwind: '$account',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$match: accountMatchStage,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
features: 1,
|
||||||
|
patch: 1,
|
||||||
|
role: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private groupMetricValues(
|
||||||
|
samples: BaselineFeatureSample[],
|
||||||
|
): Map<string, number[]> {
|
||||||
|
const metricValuesByKey = new Map<string, number[]>();
|
||||||
|
for (const sample of samples) {
|
||||||
|
if (!isTeamPosition(sample.role)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const metric of METRICS) {
|
||||||
|
const value = finiteNumber(sample.features[metric.id]);
|
||||||
|
if (value === undefined) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const key = baselineKey(metric.id, sample.role);
|
||||||
|
const values = metricValuesByKey.get(key) ?? [];
|
||||||
|
values.push(value);
|
||||||
|
metricValuesByKey.set(key, values);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return metricValuesByKey;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
import { FEATURE_SCHEMA_VERSION, VECTOR_METRICS } from '@persona-lenz/shared';
|
||||||
|
import type { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { MetricBaseline } from '../global/database/schemas';
|
||||||
|
import type { ExtractedPlayerMatchFeature } from './analysis.types';
|
||||||
|
import { MetricNormalizationService } from './metric-normalization.service';
|
||||||
|
|
||||||
|
interface ExecQuery<T> {
|
||||||
|
exec: jest.Mock<Promise<T>, []>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function leanExecResolved<T>(value: T) {
|
||||||
|
return {
|
||||||
|
lean: jest.fn((): ExecQuery<T> => ({
|
||||||
|
exec: jest.fn<Promise<T>, []>().mockResolvedValue(value),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createFeature(
|
||||||
|
overrides: Partial<ExtractedPlayerMatchFeature> = {},
|
||||||
|
): ExtractedPlayerMatchFeature {
|
||||||
|
return {
|
||||||
|
matchId: 'KR_1',
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
role: 'MIDDLE',
|
||||||
|
championId: 103,
|
||||||
|
gameCreation: 1_700_000_000_000,
|
||||||
|
gameDurationSec: 1_800,
|
||||||
|
win: true,
|
||||||
|
patch: '26.13',
|
||||||
|
features: {
|
||||||
|
csPerMin: 8,
|
||||||
|
kda: 30,
|
||||||
|
},
|
||||||
|
normalized: {
|
||||||
|
csPerMin: 0.5,
|
||||||
|
kda: 0.5,
|
||||||
|
},
|
||||||
|
vector: VECTOR_METRICS.map((metric) =>
|
||||||
|
metric.id === 'kda' || metric.id === 'csPerMin' ? 0.5 : 0,
|
||||||
|
),
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
normalizationMethod: 'registry-baseline',
|
||||||
|
confidence: 1,
|
||||||
|
timelineProcessed: true,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBaseline(
|
||||||
|
metricId: string,
|
||||||
|
overrides: Partial<MetricBaseline> = {},
|
||||||
|
): MetricBaseline {
|
||||||
|
return {
|
||||||
|
createdAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
metricId,
|
||||||
|
role: 'MIDDLE',
|
||||||
|
cohort: 'MASTER_PLUS',
|
||||||
|
patch: 'ALL',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
sampleCount: 100,
|
||||||
|
percentileBreakpoints: [
|
||||||
|
10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160,
|
||||||
|
170, 180, 190,
|
||||||
|
],
|
||||||
|
computedAt: new Date('2026-07-03T12:00:00.000Z'),
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('MetricNormalizationService', () => {
|
||||||
|
it('normalizes observed metrics with population percentile baselines', async () => {
|
||||||
|
const find = jest.fn().mockReturnValue(
|
||||||
|
leanExecResolved([
|
||||||
|
createBaseline('kda'),
|
||||||
|
createBaseline('csPerMin', {
|
||||||
|
percentileBreakpoints: [
|
||||||
|
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
|
||||||
|
],
|
||||||
|
patch: '26.13',
|
||||||
|
}),
|
||||||
|
createBaseline('csPerMin', {
|
||||||
|
percentileBreakpoints: [
|
||||||
|
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18,
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue({ find }),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new MetricNormalizationService(connectionService);
|
||||||
|
|
||||||
|
const normalizedFeature = await service.normalizeFeature(createFeature());
|
||||||
|
|
||||||
|
expect(find).toHaveBeenCalledWith({
|
||||||
|
cohort: 'MASTER_PLUS',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
metricId: {
|
||||||
|
$in: ['csPerMin', 'kda'],
|
||||||
|
},
|
||||||
|
patch: {
|
||||||
|
$in: ['26.13', 'ALL'],
|
||||||
|
},
|
||||||
|
role: 'MIDDLE',
|
||||||
|
});
|
||||||
|
expect(normalizedFeature.normalizationMethod).toBe('population-percentile');
|
||||||
|
expect(normalizedFeature.normalized.kda).toBeCloseTo(0.15);
|
||||||
|
expect(normalizedFeature.normalized.csPerMin).toBeCloseTo(0.4);
|
||||||
|
expect(normalizedFeature.vector).toEqual(
|
||||||
|
VECTOR_METRICS.map(
|
||||||
|
(metric) => normalizedFeature.normalized[metric.id] ?? 0,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps registry normalization when a baseline is missing', async () => {
|
||||||
|
const find = jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue(leanExecResolved([createBaseline('kda')]));
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue({ find }),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new MetricNormalizationService(connectionService);
|
||||||
|
const feature = createFeature();
|
||||||
|
|
||||||
|
const normalizedFeature = await service.normalizeFeature(feature);
|
||||||
|
|
||||||
|
expect(normalizedFeature).toBe(feature);
|
||||||
|
expect(normalizedFeature.normalizationMethod).toBe('registry-baseline');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps registry normalization for unknown roles', async () => {
|
||||||
|
const find = jest.fn();
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue({ find }),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const service = new MetricNormalizationService(connectionService);
|
||||||
|
const feature = createFeature({ role: 'UNKNOWN' });
|
||||||
|
|
||||||
|
const normalizedFeature = await service.normalizeFeature(feature);
|
||||||
|
|
||||||
|
expect(normalizedFeature).toBe(feature);
|
||||||
|
expect(find).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,166 @@
|
|||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import { FEATURE_SCHEMA_VERSION, VECTOR_METRICS } from '@persona-lenz/shared';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type {
|
||||||
|
BaselineCohort,
|
||||||
|
MetricBaseline,
|
||||||
|
TeamPosition,
|
||||||
|
} from '../global/database/schemas';
|
||||||
|
import type { ExtractedPlayerMatchFeature } from './analysis.types';
|
||||||
|
|
||||||
|
interface NormalizeFeatureOptions {
|
||||||
|
cohort?: BaselineCohort;
|
||||||
|
}
|
||||||
|
|
||||||
|
const BASELINE_PERCENTILE_RANKS = Array.from(
|
||||||
|
{ length: 19 },
|
||||||
|
(_, index) => (index + 1) * 0.05,
|
||||||
|
);
|
||||||
|
const TEAM_POSITIONS = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'];
|
||||||
|
|
||||||
|
function isTeamPosition(value: unknown): value is TeamPosition {
|
||||||
|
return typeof value === 'string' && TEAM_POSITIONS.includes(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function finiteNumber(value: unknown): number | undefined {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? value
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function percentileRank(
|
||||||
|
rawValue: number,
|
||||||
|
percentileBreakpoints: number[],
|
||||||
|
): number {
|
||||||
|
const breakpoints = percentileBreakpoints.filter((value) =>
|
||||||
|
Number.isFinite(value),
|
||||||
|
);
|
||||||
|
if (breakpoints.length !== BASELINE_PERCENTILE_RANKS.length) {
|
||||||
|
return Number.NaN;
|
||||||
|
}
|
||||||
|
if (breakpoints[0] === breakpoints[breakpoints.length - 1]) {
|
||||||
|
return 0.5;
|
||||||
|
}
|
||||||
|
if (rawValue < (breakpoints[0] ?? 0)) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (rawValue > (breakpoints[breakpoints.length - 1] ?? 0)) {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let index = 0; index < breakpoints.length; index += 1) {
|
||||||
|
const currentBreakpoint = breakpoints[index] ?? 0;
|
||||||
|
const currentRank = BASELINE_PERCENTILE_RANKS[index] ?? 0;
|
||||||
|
if (rawValue === currentBreakpoint) {
|
||||||
|
return currentRank;
|
||||||
|
}
|
||||||
|
if (rawValue < currentBreakpoint) {
|
||||||
|
const previousBreakpoint = breakpoints[index - 1] ?? currentBreakpoint;
|
||||||
|
const previousRank = BASELINE_PERCENTILE_RANKS[index - 1] ?? 0;
|
||||||
|
if (currentBreakpoint === previousBreakpoint) {
|
||||||
|
return currentRank;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
previousRank +
|
||||||
|
((rawValue - previousBreakpoint) /
|
||||||
|
(currentBreakpoint - previousBreakpoint)) *
|
||||||
|
(currentRank - previousRank)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class MetricNormalizationService {
|
||||||
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
|
public async normalizeFeature(
|
||||||
|
feature: ExtractedPlayerMatchFeature,
|
||||||
|
options: NormalizeFeatureOptions = {},
|
||||||
|
): Promise<ExtractedPlayerMatchFeature> {
|
||||||
|
if (!isTeamPosition(feature.role)) {
|
||||||
|
return feature;
|
||||||
|
}
|
||||||
|
|
||||||
|
const observedMetricIds = Object.keys(feature.normalized).filter(
|
||||||
|
(metricId) => finiteNumber(feature.features[metricId]) !== undefined,
|
||||||
|
);
|
||||||
|
if (observedMetricIds.length === 0) {
|
||||||
|
return feature;
|
||||||
|
}
|
||||||
|
|
||||||
|
const baselinesByMetricId = await this.findBaselinesByMetricId({
|
||||||
|
cohort: options.cohort ?? 'MASTER_PLUS',
|
||||||
|
metricIds: observedMetricIds,
|
||||||
|
patch: feature.patch,
|
||||||
|
role: feature.role,
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
observedMetricIds.some(
|
||||||
|
(metricId) => baselinesByMetricId.get(metricId) === undefined,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return feature;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalized = { ...feature.normalized };
|
||||||
|
for (const metricId of observedMetricIds) {
|
||||||
|
const rawValue = finiteNumber(feature.features[metricId]);
|
||||||
|
const baseline = baselinesByMetricId.get(metricId);
|
||||||
|
if (rawValue === undefined || !baseline) {
|
||||||
|
return feature;
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedValue = percentileRank(
|
||||||
|
rawValue,
|
||||||
|
baseline.percentileBreakpoints,
|
||||||
|
);
|
||||||
|
if (!Number.isFinite(normalizedValue)) {
|
||||||
|
return feature;
|
||||||
|
}
|
||||||
|
normalized[metricId] = Math.max(0, Math.min(1, normalizedValue));
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...feature,
|
||||||
|
normalized,
|
||||||
|
vector: VECTOR_METRICS.map((metric) => normalized[metric.id] ?? 0),
|
||||||
|
normalizationMethod: 'population-percentile',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async findBaselinesByMetricId(params: {
|
||||||
|
cohort: BaselineCohort;
|
||||||
|
metricIds: string[];
|
||||||
|
patch: string;
|
||||||
|
role: TeamPosition;
|
||||||
|
}): Promise<Map<string, MetricBaseline>> {
|
||||||
|
const metricBaselineModel =
|
||||||
|
await this.connectionService.getModel('metricBaseline');
|
||||||
|
const baselines = await metricBaselineModel
|
||||||
|
.find({
|
||||||
|
metricId: {
|
||||||
|
$in: params.metricIds,
|
||||||
|
},
|
||||||
|
role: params.role,
|
||||||
|
cohort: params.cohort,
|
||||||
|
patch: {
|
||||||
|
$in: [params.patch, 'ALL'],
|
||||||
|
},
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
})
|
||||||
|
.lean<MetricBaseline[]>()
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
const baselinesByMetricId = new Map<string, MetricBaseline>();
|
||||||
|
for (const baseline of baselines) {
|
||||||
|
const existingBaseline = baselinesByMetricId.get(baseline.metricId);
|
||||||
|
if (!existingBaseline || baseline.patch === params.patch) {
|
||||||
|
baselinesByMetricId.set(baseline.metricId, baseline);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return baselinesByMetricId;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,335 @@
|
|||||||
|
import {
|
||||||
|
FEATURE_SCHEMA_VERSION,
|
||||||
|
METRICS,
|
||||||
|
VECTOR_METRICS,
|
||||||
|
type MetricDefinition,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
|
import type { PlayerMatchFeature } from '../global/database/schemas';
|
||||||
|
import {
|
||||||
|
buildProfileMetricValues,
|
||||||
|
ProfileBuilderService,
|
||||||
|
} from './profile-builder.service';
|
||||||
|
|
||||||
|
function createFeature(
|
||||||
|
overrides: Partial<PlayerMatchFeature> = {},
|
||||||
|
): PlayerMatchFeature {
|
||||||
|
const normalized = Object.fromEntries(
|
||||||
|
METRICS.map((metric) => [metric.id, 0.5]),
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
createdAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
matchId: 'KR_1',
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
role: 'MIDDLE',
|
||||||
|
championId: 103,
|
||||||
|
gameCreation: 1_700_000_000_000,
|
||||||
|
gameDurationSec: 1800,
|
||||||
|
win: true,
|
||||||
|
patch: '26.13',
|
||||||
|
features: {},
|
||||||
|
normalized,
|
||||||
|
vector: METRICS.map((metric) => normalized[metric.id]),
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
normalizationMethod: 'registry-baseline',
|
||||||
|
confidence: 1,
|
||||||
|
timelineProcessed: true,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ProfileBuilderService', () => {
|
||||||
|
const service = new ProfileBuilderService();
|
||||||
|
|
||||||
|
it('builds a confidence-weighted profile in registry vector order', () => {
|
||||||
|
const firstNormalized = Object.fromEntries(
|
||||||
|
METRICS.map((metric, index) => [metric.id, 0.8 - index * 0.01]),
|
||||||
|
);
|
||||||
|
const secondNormalized = Object.fromEntries(
|
||||||
|
METRICS.map((metric, index) => [metric.id, 0.2 + index * 0.01]),
|
||||||
|
);
|
||||||
|
const firstFeature = createFeature({
|
||||||
|
matchId: 'KR_1',
|
||||||
|
role: 'MIDDLE',
|
||||||
|
championId: 103,
|
||||||
|
win: true,
|
||||||
|
normalized: firstNormalized,
|
||||||
|
confidence: 1,
|
||||||
|
patch: '26.13',
|
||||||
|
gameCreation: 1_700_000_000_000,
|
||||||
|
});
|
||||||
|
firstFeature.vector = METRICS.map(
|
||||||
|
(metric) => firstFeature.normalized[metric.id],
|
||||||
|
);
|
||||||
|
|
||||||
|
const secondFeature = createFeature({
|
||||||
|
matchId: 'KR_2',
|
||||||
|
role: 'BOTTOM',
|
||||||
|
championId: 22,
|
||||||
|
win: false,
|
||||||
|
normalized: secondNormalized,
|
||||||
|
confidence: 0.5,
|
||||||
|
patch: '26.14',
|
||||||
|
gameCreation: 1_700_100_000_000,
|
||||||
|
});
|
||||||
|
secondFeature.vector = METRICS.map(
|
||||||
|
(metric) => secondFeature.normalized[metric.id],
|
||||||
|
);
|
||||||
|
|
||||||
|
const profile = service.buildProfile({
|
||||||
|
features: [firstFeature, secondFeature],
|
||||||
|
isSeed: false,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(profile.mainRole).toBe('MIDDLE');
|
||||||
|
expect(profile.sampleGameCount).toBe(2);
|
||||||
|
for (const metric of METRICS.filter((metric) => metric.kind === 'scalar')) {
|
||||||
|
expect(profile.profile[metric.id]).toBeCloseTo(
|
||||||
|
(firstNormalized[metric.id] + secondNormalized[metric.id] * 0.5) / 1.5,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for (const metric of METRICS.filter((metric) => metric.kind === 'ratio')) {
|
||||||
|
expect(profile.profile[metric.id]).toBeUndefined();
|
||||||
|
}
|
||||||
|
expect(profile.vector).toEqual(
|
||||||
|
VECTOR_METRICS.map((metric) => profile.profile[metric.id] ?? 0),
|
||||||
|
);
|
||||||
|
expect(profile.championPool).toEqual([
|
||||||
|
{ championId: 103, games: 1, wins: 1 },
|
||||||
|
{ championId: 22, games: 1, wins: 0 },
|
||||||
|
]);
|
||||||
|
expect(profile.patches).toEqual(['26.13', '26.14']);
|
||||||
|
expect(profile.lastMatchAt).toEqual(new Date(1_700_100_000_000));
|
||||||
|
expect(profile.confidence).toBeCloseTo(0.3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws when no features are available', () => {
|
||||||
|
expect(() =>
|
||||||
|
service.buildProfile({
|
||||||
|
features: [],
|
||||||
|
isSeed: false,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
}),
|
||||||
|
).toThrow('Cannot build a profile without match features.');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('discounts profile confidence when timeline metrics are missing', () => {
|
||||||
|
const profile = service.buildProfile({
|
||||||
|
features: [
|
||||||
|
createFeature({ timelineProcessed: true }),
|
||||||
|
createFeature({ matchId: 'KR_2', timelineProcessed: false }),
|
||||||
|
],
|
||||||
|
isSeed: false,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(profile.confidence).toBeCloseTo(0.34);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks profiles as population percentile only when every feature uses it', () => {
|
||||||
|
const populationProfile = service.buildProfile({
|
||||||
|
features: [
|
||||||
|
createFeature({ normalizationMethod: 'population-percentile' }),
|
||||||
|
createFeature({
|
||||||
|
matchId: 'KR_2',
|
||||||
|
normalizationMethod: 'population-percentile',
|
||||||
|
}),
|
||||||
|
],
|
||||||
|
isSeed: false,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
});
|
||||||
|
|
||||||
|
const mixedProfile = service.buildProfile({
|
||||||
|
features: [
|
||||||
|
createFeature({ normalizationMethod: 'population-percentile' }),
|
||||||
|
createFeature({ matchId: 'KR_2' }),
|
||||||
|
],
|
||||||
|
isSeed: false,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(populationProfile.normalizationMethod).toBe('population-percentile');
|
||||||
|
expect(mixedProfile.normalizationMethod).toBe('registry-baseline');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('denormalizes ranked solo tier fields into built profiles', () => {
|
||||||
|
const profile = service.buildProfile({
|
||||||
|
features: [createFeature()],
|
||||||
|
isSeed: true,
|
||||||
|
puuid: 'seed-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
division: '',
|
||||||
|
leaguePoints: 987,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(profile).toMatchObject({
|
||||||
|
isSeed: true,
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
division: '',
|
||||||
|
leaguePoints: 987,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aggregates ratio metrics from raw numerator and denominator counts', () => {
|
||||||
|
const metrics: MetricDefinition[] = [
|
||||||
|
{
|
||||||
|
id: 'scalarMetric',
|
||||||
|
label: 'Scalar metric',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
kind: 'scalar',
|
||||||
|
includeInVector: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'rareEventRate',
|
||||||
|
label: 'Rare event rate',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
kind: 'ratio',
|
||||||
|
includeInVector: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const firstFeature = createFeature({
|
||||||
|
features: {
|
||||||
|
rareEventRateNumerator: 1,
|
||||||
|
rareEventRateDenominator: 2,
|
||||||
|
},
|
||||||
|
normalized: { scalarMetric: 0.8 },
|
||||||
|
confidence: 1,
|
||||||
|
});
|
||||||
|
const secondFeature = createFeature({
|
||||||
|
features: {
|
||||||
|
rareEventRateNumerator: 2,
|
||||||
|
rareEventRateDenominator: 3,
|
||||||
|
},
|
||||||
|
normalized: { scalarMetric: 0.2 },
|
||||||
|
confidence: 0.5,
|
||||||
|
});
|
||||||
|
|
||||||
|
const profile = buildProfileMetricValues(
|
||||||
|
[firstFeature, secondFeature],
|
||||||
|
metrics,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(profile.scalarMetric).toBeCloseTo((0.8 + 0.2 * 0.5) / 1.5);
|
||||||
|
expect(profile.rareEventRate).toBeCloseTo(3 / 5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aggregates scalar metrics only from features with observed normalized values', () => {
|
||||||
|
const metrics: MetricDefinition[] = [
|
||||||
|
{
|
||||||
|
id: 'observedScalar',
|
||||||
|
label: 'Observed scalar',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
kind: 'scalar',
|
||||||
|
includeInVector: true,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const firstFeature = createFeature({
|
||||||
|
normalized: {},
|
||||||
|
confidence: 1,
|
||||||
|
});
|
||||||
|
const secondFeature = createFeature({
|
||||||
|
normalized: { observedScalar: 0.4 },
|
||||||
|
confidence: 0.5,
|
||||||
|
});
|
||||||
|
|
||||||
|
const profile = buildProfileMetricValues(
|
||||||
|
[firstFeature, secondFeature],
|
||||||
|
metrics,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(profile.observedScalar).toBe(0.4);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds profile vectors from included metrics while retaining insight metrics', () => {
|
||||||
|
const actualShared = jest.requireActual<
|
||||||
|
typeof import('@persona-lenz/shared')
|
||||||
|
>('@persona-lenz/shared');
|
||||||
|
const metrics: MetricDefinition[] = [
|
||||||
|
{
|
||||||
|
id: 'scalarMetric',
|
||||||
|
label: 'Scalar metric',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
kind: 'scalar',
|
||||||
|
includeInVector: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'vectorRate',
|
||||||
|
label: 'Vector rate',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
kind: 'ratio',
|
||||||
|
includeInVector: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'insightRate',
|
||||||
|
label: 'Insight rate',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
kind: 'ratio',
|
||||||
|
includeInVector: false,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
let profile: ReturnType<ProfileBuilderService['buildProfile']> | undefined;
|
||||||
|
|
||||||
|
jest.isolateModules(() => {
|
||||||
|
jest.doMock('@persona-lenz/shared', () => ({
|
||||||
|
...actualShared,
|
||||||
|
FEATURE_SCHEMA_VERSION: 99,
|
||||||
|
METRICS: metrics,
|
||||||
|
VECTOR_METRICS: metrics.filter((metric) => metric.includeInVector),
|
||||||
|
}));
|
||||||
|
const { ProfileBuilderService: MockedProfileBuilderService } =
|
||||||
|
jest.requireActual<typeof import('./profile-builder.service')>(
|
||||||
|
'./profile-builder.service',
|
||||||
|
);
|
||||||
|
const serviceWithMockedRegistry = new MockedProfileBuilderService();
|
||||||
|
const firstFeature = createFeature({
|
||||||
|
features: {
|
||||||
|
vectorRateNumerator: 1,
|
||||||
|
vectorRateDenominator: 2,
|
||||||
|
insightRateNumerator: 2,
|
||||||
|
insightRateDenominator: 4,
|
||||||
|
},
|
||||||
|
normalized: { scalarMetric: 0.8 },
|
||||||
|
confidence: 1,
|
||||||
|
});
|
||||||
|
const secondFeature = createFeature({
|
||||||
|
features: {
|
||||||
|
vectorRateNumerator: 3,
|
||||||
|
vectorRateDenominator: 4,
|
||||||
|
insightRateNumerator: 1,
|
||||||
|
insightRateDenominator: 1,
|
||||||
|
},
|
||||||
|
normalized: { scalarMetric: 0.2 },
|
||||||
|
confidence: 0.5,
|
||||||
|
});
|
||||||
|
|
||||||
|
profile = serviceWithMockedRegistry.buildProfile({
|
||||||
|
features: [firstFeature, secondFeature],
|
||||||
|
isSeed: false,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
jest.dontMock('@persona-lenz/shared');
|
||||||
|
|
||||||
|
expect(profile).toBeDefined();
|
||||||
|
expect(profile?.profile.scalarMetric).toBeCloseTo((0.8 + 0.2 * 0.5) / 1.5);
|
||||||
|
expect(profile?.profile.vectorRate).toBeCloseTo(4 / 6);
|
||||||
|
expect(profile?.profile.insightRate).toBeCloseTo(3 / 5);
|
||||||
|
expect(profile?.vector).toEqual([
|
||||||
|
profile?.profile.scalarMetric,
|
||||||
|
profile?.profile.vectorRate,
|
||||||
|
]);
|
||||||
|
expect(profile?.featureSchemaVersion).toBe(99);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,230 @@
|
|||||||
|
import {
|
||||||
|
FEATURE_SCHEMA_VERSION,
|
||||||
|
METRICS,
|
||||||
|
VECTOR_METRICS,
|
||||||
|
type MetricDefinition,
|
||||||
|
type Role,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
import type {
|
||||||
|
NormalizationMethod,
|
||||||
|
PlayerMatchFeature,
|
||||||
|
} from '../global/database/schemas';
|
||||||
|
import type { BuiltPlayerProfile } from './analysis.types';
|
||||||
|
|
||||||
|
type ProfileSourceFeature = Pick<
|
||||||
|
PlayerMatchFeature,
|
||||||
|
| 'championId'
|
||||||
|
| 'confidence'
|
||||||
|
| 'features'
|
||||||
|
| 'gameCreation'
|
||||||
|
| 'normalized'
|
||||||
|
| 'normalizationMethod'
|
||||||
|
| 'patch'
|
||||||
|
| 'role'
|
||||||
|
| 'timelineProcessed'
|
||||||
|
| 'win'
|
||||||
|
>;
|
||||||
|
|
||||||
|
export interface BuildProfileParams {
|
||||||
|
division?: string;
|
||||||
|
features: ProfileSourceFeature[];
|
||||||
|
isSeed: boolean;
|
||||||
|
leaguePoints?: number;
|
||||||
|
puuid: string;
|
||||||
|
queueId: number;
|
||||||
|
tier?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ROLE_ORDER: Role[] = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'];
|
||||||
|
|
||||||
|
function toFiniteMetricValue(value: number | undefined): number {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function aggregateScalarMetric(
|
||||||
|
features: readonly ProfileSourceFeature[],
|
||||||
|
metricId: string,
|
||||||
|
): number | undefined {
|
||||||
|
let weightedSum = 0;
|
||||||
|
let confidenceSum = 0;
|
||||||
|
|
||||||
|
for (const feature of features) {
|
||||||
|
const metricValue = feature.normalized[metricId];
|
||||||
|
if (typeof metricValue !== 'number' || !Number.isFinite(metricValue)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
weightedSum += metricValue * feature.confidence;
|
||||||
|
confidenceSum += feature.confidence;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (confidenceSum <= 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return weightedSum / confidenceSum;
|
||||||
|
}
|
||||||
|
|
||||||
|
function aggregateRatioMetric(
|
||||||
|
features: readonly ProfileSourceFeature[],
|
||||||
|
metricId: string,
|
||||||
|
): number | undefined {
|
||||||
|
const numeratorKey = `${metricId}Numerator`;
|
||||||
|
const denominatorKey = `${metricId}Denominator`;
|
||||||
|
const numerator = features.reduce(
|
||||||
|
(sum, feature) => sum + toFiniteMetricValue(feature.features[numeratorKey]),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const denominator = features.reduce(
|
||||||
|
(sum, feature) =>
|
||||||
|
sum + toFiniteMetricValue(feature.features[denominatorKey]),
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (denominator <= 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return numerator / denominator;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildProfileMetricValues(
|
||||||
|
features: readonly ProfileSourceFeature[],
|
||||||
|
metrics: readonly MetricDefinition[],
|
||||||
|
): Record<string, number> {
|
||||||
|
const profile: Record<string, number> = {};
|
||||||
|
|
||||||
|
for (const metric of metrics) {
|
||||||
|
const metricValue =
|
||||||
|
metric.kind === 'ratio'
|
||||||
|
? aggregateRatioMetric(features, metric.id)
|
||||||
|
: aggregateScalarMetric(features, metric.id);
|
||||||
|
if (metricValue !== undefined) {
|
||||||
|
profile[metric.id] = metricValue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return profile;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRole(value: string): value is Role {
|
||||||
|
return ROLE_ORDER.includes(value as Role);
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveProfileNormalizationMethod(
|
||||||
|
features: readonly ProfileSourceFeature[],
|
||||||
|
): NormalizationMethod {
|
||||||
|
return features.every(
|
||||||
|
(feature) => feature.normalizationMethod === 'population-percentile',
|
||||||
|
)
|
||||||
|
? 'population-percentile'
|
||||||
|
: 'registry-baseline';
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class ProfileBuilderService {
|
||||||
|
public buildProfile(params: BuildProfileParams): BuiltPlayerProfile {
|
||||||
|
if (params.features.length === 0) {
|
||||||
|
throw new Error('Cannot build a profile without match features.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const totalConfidence = params.features.reduce(
|
||||||
|
(sum, feature) => sum + feature.confidence,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const profile = buildProfileMetricValues(params.features, METRICS);
|
||||||
|
|
||||||
|
const roleCounts = new Map<Role, number>();
|
||||||
|
const championPool = new Map<
|
||||||
|
number,
|
||||||
|
{ championId: number; games: number; wins: number }
|
||||||
|
>();
|
||||||
|
|
||||||
|
for (const feature of params.features) {
|
||||||
|
if (isRole(feature.role)) {
|
||||||
|
roleCounts.set(feature.role, (roleCounts.get(feature.role) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const championEntry = championPool.get(feature.championId) ?? {
|
||||||
|
championId: feature.championId,
|
||||||
|
games: 0,
|
||||||
|
wins: 0,
|
||||||
|
};
|
||||||
|
championEntry.games += 1;
|
||||||
|
if (feature.win) championEntry.wins += 1;
|
||||||
|
championPool.set(feature.championId, championEntry);
|
||||||
|
}
|
||||||
|
|
||||||
|
const knownRoleGameCount = [...roleCounts.values()].reduce(
|
||||||
|
(sum, count) => sum + count,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
const roleDistribution = Object.fromEntries(
|
||||||
|
[...roleCounts.entries()].map(([role, count]) => [
|
||||||
|
role,
|
||||||
|
count / Math.max(knownRoleGameCount, 1),
|
||||||
|
]),
|
||||||
|
) as Partial<Record<Role, number>>;
|
||||||
|
|
||||||
|
const averageConfidence = totalConfidence / params.features.length;
|
||||||
|
const sampleSizeConfidenceMultiplier = Math.min(
|
||||||
|
params.features.length / 5,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
const timelineCoverageMultiplier =
|
||||||
|
0.7 +
|
||||||
|
0.3 *
|
||||||
|
(params.features.filter((feature) => feature.timelineProcessed).length /
|
||||||
|
params.features.length);
|
||||||
|
|
||||||
|
return {
|
||||||
|
puuid: params.puuid,
|
||||||
|
queueId: params.queueId,
|
||||||
|
mainRole: this.resolveMainRole(roleCounts),
|
||||||
|
roleDistribution,
|
||||||
|
sampleGameCount: params.features.length,
|
||||||
|
championPool: [...championPool.values()].sort(
|
||||||
|
(left, right) =>
|
||||||
|
right.games - left.games ||
|
||||||
|
right.wins - left.wins ||
|
||||||
|
left.championId - right.championId,
|
||||||
|
),
|
||||||
|
profile,
|
||||||
|
vector: VECTOR_METRICS.map((metric) => profile[metric.id] ?? 0),
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
normalizationMethod: resolveProfileNormalizationMethod(params.features),
|
||||||
|
confidence:
|
||||||
|
averageConfidence *
|
||||||
|
sampleSizeConfidenceMultiplier *
|
||||||
|
timelineCoverageMultiplier,
|
||||||
|
patches: [
|
||||||
|
...new Set(params.features.map((feature) => feature.patch)),
|
||||||
|
].sort(),
|
||||||
|
lastMatchAt: new Date(
|
||||||
|
Math.max(...params.features.map((feature) => feature.gameCreation)),
|
||||||
|
),
|
||||||
|
isSeed: params.isSeed,
|
||||||
|
...(params.tier ? { tier: params.tier } : {}),
|
||||||
|
...(params.division !== undefined ? { division: params.division } : {}),
|
||||||
|
...(params.leaguePoints !== undefined
|
||||||
|
? { leaguePoints: params.leaguePoints }
|
||||||
|
: {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveMainRole(roleCounts: Map<Role, number>): Role {
|
||||||
|
let selectedRole: Role = 'MIDDLE';
|
||||||
|
let selectedCount = -1;
|
||||||
|
|
||||||
|
for (const role of ROLE_ORDER) {
|
||||||
|
const count = roleCounts.get(role) ?? 0;
|
||||||
|
if (count > selectedCount) {
|
||||||
|
selectedRole = role;
|
||||||
|
selectedCount = count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return selectedRole;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
import type { Job } from 'bullmq';
|
||||||
|
import type { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { AnalysisPipelineService } from './analysis-pipeline.service';
|
||||||
|
import type { SeedCollectionService } from './seed-collection.service';
|
||||||
|
import {
|
||||||
|
DEFAULT_SEED_COLLECTION_MATCH_COUNT,
|
||||||
|
SEED_COLLECTION_JOB_NAME,
|
||||||
|
} from './analysis.constants';
|
||||||
|
import type { SeedCollectionJobData } from './analysis.types';
|
||||||
|
import { SeedCollectionProcessor } from './seed-collection.processor';
|
||||||
|
|
||||||
|
function createSeedCollectionJobData(
|
||||||
|
overrides: Partial<SeedCollectionJobData> = {},
|
||||||
|
): SeedCollectionJobData {
|
||||||
|
return {
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: 50,
|
||||||
|
grandmaster: 50,
|
||||||
|
master: 50,
|
||||||
|
},
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createUpdateOneMock() {
|
||||||
|
return jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue({ acknowledged: true }),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Record<string, unknown> {
|
||||||
|
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SeedCollectionProcessor', () => {
|
||||||
|
it('delegates seed collection jobs and marks them completed', async () => {
|
||||||
|
const collectSeedAccounts = jest.fn().mockResolvedValue({
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
selectedEntries: 150,
|
||||||
|
storedSeedAccounts: [
|
||||||
|
{
|
||||||
|
puuid: 'seed-puuid-1',
|
||||||
|
source: 'challenger',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
storedAccounts: 149,
|
||||||
|
skippedAccounts: 1,
|
||||||
|
});
|
||||||
|
const processSeedAccountPipeline = jest.fn().mockResolvedValue({
|
||||||
|
puuid: 'seed-puuid-1',
|
||||||
|
fetchedMatches: 30,
|
||||||
|
extractedFeatures: 30,
|
||||||
|
profileBuilt: true,
|
||||||
|
});
|
||||||
|
const updateOne = createUpdateOneMock();
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue({ updateOne }),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const processor = new SeedCollectionProcessor(
|
||||||
|
{
|
||||||
|
collectSeedAccounts,
|
||||||
|
} as unknown as SeedCollectionService,
|
||||||
|
{
|
||||||
|
processSeedAccountPipeline,
|
||||||
|
} as unknown as AnalysisPipelineService,
|
||||||
|
connectionService,
|
||||||
|
);
|
||||||
|
|
||||||
|
await processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'seed-job-1',
|
||||||
|
name: SEED_COLLECTION_JOB_NAME,
|
||||||
|
opts: { attempts: 1 },
|
||||||
|
data: createSeedCollectionJobData(),
|
||||||
|
} as Job<unknown>);
|
||||||
|
|
||||||
|
expect(collectSeedAccounts).toHaveBeenCalledWith({
|
||||||
|
platformRoute: 'kr',
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: 50,
|
||||||
|
grandmaster: 50,
|
||||||
|
master: 50,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(processSeedAccountPipeline).toHaveBeenCalledWith(
|
||||||
|
{
|
||||||
|
puuid: 'seed-puuid-1',
|
||||||
|
platformRoute: 'kr',
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount: DEFAULT_SEED_COLLECTION_MATCH_COUNT,
|
||||||
|
},
|
||||||
|
'seed-job-1',
|
||||||
|
);
|
||||||
|
expect(updateOne).toHaveBeenCalledWith(
|
||||||
|
{ jobId: 'seed-job-1' },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'processing',
|
||||||
|
stage: 'collect-seed-accounts',
|
||||||
|
progress: {
|
||||||
|
fetchedMatches: 0,
|
||||||
|
totalMatches: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const completedUpdate = updateOne.mock.calls.find(
|
||||||
|
([, update]) => asRecord(asRecord(update).$set).status === 'completed',
|
||||||
|
);
|
||||||
|
expect(completedUpdate).toBeDefined();
|
||||||
|
expect(asRecord(asRecord(completedUpdate?.[1]).$set)).toMatchObject({
|
||||||
|
status: 'completed',
|
||||||
|
stage: 'completed',
|
||||||
|
progress: {
|
||||||
|
fetchedMatches: 149,
|
||||||
|
totalMatches: 150,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
asRecord(asRecord(completedUpdate?.[1]).$set).completedAt,
|
||||||
|
).toBeInstanceOf(Date);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
data: null,
|
||||||
|
expectedError: 'Seed collection job data must be an object.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createSeedCollectionJobData(),
|
||||||
|
platformRoute: 'invalid',
|
||||||
|
},
|
||||||
|
expectedError: 'Seed collection job platformRoute is unsupported.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createSeedCollectionJobData(),
|
||||||
|
queueId: 430,
|
||||||
|
},
|
||||||
|
expectedError: 'Seed collection job queueId is unsupported.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createSeedCollectionJobData(),
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: Number.NaN,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expectedError:
|
||||||
|
'Seed collection job sourceLimits.challenger must be a non-negative finite number.',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
data: {
|
||||||
|
...createSeedCollectionJobData(),
|
||||||
|
sourceLimits: {
|
||||||
|
diamond: 50,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
expectedError: 'Seed collection job sourceLimits.diamond is unsupported.',
|
||||||
|
},
|
||||||
|
])(
|
||||||
|
'rejects malformed seed collection payloads',
|
||||||
|
async ({ data, expectedError }) => {
|
||||||
|
const collectSeedAccounts = jest.fn();
|
||||||
|
const processSeedAccountPipeline = jest.fn();
|
||||||
|
const updateOne = createUpdateOneMock();
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue({ updateOne }),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const processor = new SeedCollectionProcessor(
|
||||||
|
{
|
||||||
|
collectSeedAccounts,
|
||||||
|
} as unknown as SeedCollectionService,
|
||||||
|
{
|
||||||
|
processSeedAccountPipeline,
|
||||||
|
} as unknown as AnalysisPipelineService,
|
||||||
|
connectionService,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'seed-job-1',
|
||||||
|
name: SEED_COLLECTION_JOB_NAME,
|
||||||
|
opts: { attempts: 1 },
|
||||||
|
data,
|
||||||
|
} as Job<unknown>),
|
||||||
|
).rejects.toThrow(expectedError);
|
||||||
|
expect(collectSeedAccounts).not.toHaveBeenCalled();
|
||||||
|
expect(processSeedAccountPipeline).not.toHaveBeenCalled();
|
||||||
|
expect(updateOne).not.toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('marks final-attempt failures as failed', async () => {
|
||||||
|
const collectSeedAccounts = jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValue(new Error('Riot unavailable'));
|
||||||
|
const processSeedAccountPipeline = jest.fn();
|
||||||
|
const updateOne = createUpdateOneMock();
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue({ updateOne }),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const processor = new SeedCollectionProcessor(
|
||||||
|
{
|
||||||
|
collectSeedAccounts,
|
||||||
|
} as unknown as SeedCollectionService,
|
||||||
|
{
|
||||||
|
processSeedAccountPipeline,
|
||||||
|
} as unknown as AnalysisPipelineService,
|
||||||
|
connectionService,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
processor.process({
|
||||||
|
attemptsMade: 0,
|
||||||
|
id: 'seed-job-1',
|
||||||
|
name: SEED_COLLECTION_JOB_NAME,
|
||||||
|
opts: { attempts: 1 },
|
||||||
|
data: createSeedCollectionJobData(),
|
||||||
|
} as Job<unknown>),
|
||||||
|
).rejects.toThrow('Riot unavailable');
|
||||||
|
|
||||||
|
expect(processSeedAccountPipeline).not.toHaveBeenCalled();
|
||||||
|
expect(updateOne).toHaveBeenCalledWith(
|
||||||
|
{ jobId: 'seed-job-1' },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
status: 'failed',
|
||||||
|
error: 'Seed collection failed during processing.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects unsupported job names', async () => {
|
||||||
|
const processor = new SeedCollectionProcessor(
|
||||||
|
{
|
||||||
|
collectSeedAccounts: jest.fn(),
|
||||||
|
} as unknown as SeedCollectionService,
|
||||||
|
{
|
||||||
|
processSeedAccountPipeline: jest.fn(),
|
||||||
|
} as unknown as AnalysisPipelineService,
|
||||||
|
{
|
||||||
|
getModel: jest.fn(),
|
||||||
|
} as unknown as ConnectionService,
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
processor.process({
|
||||||
|
id: 'seed-job-1',
|
||||||
|
name: 'unexpected',
|
||||||
|
data: createSeedCollectionJobData(),
|
||||||
|
} as Job<unknown>),
|
||||||
|
).rejects.toThrow('Unsupported seed collection job name "unexpected".');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||||
|
import type { Job } from 'bullmq';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { SEED_SOURCES, type SeedSource } from '../global/database/schemas';
|
||||||
|
import {
|
||||||
|
DEFAULT_SEED_COLLECTION_MATCH_COUNT,
|
||||||
|
SEED_COLLECTION_JOB_NAME,
|
||||||
|
SEED_COLLECTION_QUEUE_NAME,
|
||||||
|
} from './analysis.constants';
|
||||||
|
import type { SeedCollectionJobData } from './analysis.types';
|
||||||
|
import {
|
||||||
|
RIOT_PLATFORM_ROUTES,
|
||||||
|
type RiotPlatformRoute,
|
||||||
|
} from '../riot/riot.types';
|
||||||
|
import { AnalysisPipelineService } from './analysis-pipeline.service';
|
||||||
|
import { SeedCollectionService } from './seed-collection.service';
|
||||||
|
|
||||||
|
@Processor(SEED_COLLECTION_QUEUE_NAME, { concurrency: 1 })
|
||||||
|
export class SeedCollectionProcessor extends WorkerHost {
|
||||||
|
constructor(
|
||||||
|
private readonly seedCollectionService: SeedCollectionService,
|
||||||
|
private readonly analysisPipelineService: AnalysisPipelineService,
|
||||||
|
private readonly connectionService: ConnectionService,
|
||||||
|
) {
|
||||||
|
super();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async process(job: Job<unknown>): Promise<void> {
|
||||||
|
if (!job.id) {
|
||||||
|
throw new Error('Seed collection job is missing a BullMQ job id.');
|
||||||
|
}
|
||||||
|
if (job.name !== SEED_COLLECTION_JOB_NAME) {
|
||||||
|
throw new Error(`Unsupported seed collection job name "${job.name}".`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = this.parseSeedCollectionJobData(job.data);
|
||||||
|
try {
|
||||||
|
await this.updateJob(job.id, {
|
||||||
|
status: 'processing',
|
||||||
|
stage: 'collect-seed-accounts',
|
||||||
|
progress: {
|
||||||
|
fetchedMatches: 0,
|
||||||
|
totalMatches: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await this.seedCollectionService.collectSeedAccounts({
|
||||||
|
platformRoute: data.platformRoute,
|
||||||
|
...(data.sourceLimits ? { sourceLimits: data.sourceLimits } : {}),
|
||||||
|
});
|
||||||
|
for (const storedSeedAccount of result.storedSeedAccounts) {
|
||||||
|
await this.analysisPipelineService.processSeedAccountPipeline(
|
||||||
|
{
|
||||||
|
puuid: storedSeedAccount.puuid,
|
||||||
|
platformRoute: data.platformRoute,
|
||||||
|
regionalRoute: result.regionalRoute,
|
||||||
|
queueId: data.queueId,
|
||||||
|
requestedMatchCount: DEFAULT_SEED_COLLECTION_MATCH_COUNT,
|
||||||
|
},
|
||||||
|
job.id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.updateJob(job.id, {
|
||||||
|
status: 'completed',
|
||||||
|
stage: 'completed',
|
||||||
|
progress: {
|
||||||
|
fetchedMatches: result.storedAccounts,
|
||||||
|
totalMatches: result.selectedEntries,
|
||||||
|
},
|
||||||
|
completedAt: new Date(),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (this.isFinalAttempt(job)) {
|
||||||
|
await this.updateJob(job.id, {
|
||||||
|
status: 'failed',
|
||||||
|
error: this.publicErrorMessage(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseSeedCollectionJobData(value: unknown): SeedCollectionJobData {
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
throw new Error('Seed collection job data must be an object.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = value as Record<string, unknown>;
|
||||||
|
const platformRoute = this.parsePlatformRoute(record.platformRoute);
|
||||||
|
const queueId = this.parseQueueId(record.queueId);
|
||||||
|
const sourceLimits = this.parseSourceLimits(record.sourceLimits);
|
||||||
|
|
||||||
|
return {
|
||||||
|
platformRoute,
|
||||||
|
queueId,
|
||||||
|
...(sourceLimits ? { sourceLimits } : {}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private parsePlatformRoute(value: unknown): RiotPlatformRoute {
|
||||||
|
if (
|
||||||
|
typeof value !== 'string' ||
|
||||||
|
!RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute)
|
||||||
|
) {
|
||||||
|
throw new Error('Seed collection job platformRoute is unsupported.');
|
||||||
|
}
|
||||||
|
return value as RiotPlatformRoute;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseQueueId(value: unknown): number {
|
||||||
|
if (value !== 420) {
|
||||||
|
throw new Error('Seed collection job queueId is unsupported.');
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseSourceLimits(
|
||||||
|
value: unknown,
|
||||||
|
): Partial<Record<SeedSource, number>> | undefined {
|
||||||
|
if (value === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
throw new Error('Seed collection job sourceLimits must be an object.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const sourceLimits = value as Record<string, unknown>;
|
||||||
|
const parsedSourceLimits: Partial<Record<SeedSource, number>> = {};
|
||||||
|
for (const [source, limit] of Object.entries(sourceLimits)) {
|
||||||
|
if (!SEED_SOURCES.includes(source as SeedSource)) {
|
||||||
|
throw new Error(
|
||||||
|
`Seed collection job sourceLimits.${source} is unsupported.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0) {
|
||||||
|
throw new Error(
|
||||||
|
`Seed collection job sourceLimits.${source} must be a non-negative finite number.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
parsedSourceLimits[source as SeedSource] = Math.trunc(limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsedSourceLimits;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updateJob(
|
||||||
|
jobId: string,
|
||||||
|
updates: Record<string, unknown>,
|
||||||
|
): Promise<void> {
|
||||||
|
const analysisJobModel =
|
||||||
|
await this.connectionService.getModel('analysisJob');
|
||||||
|
await analysisJobModel
|
||||||
|
.updateOne(
|
||||||
|
{ jobId },
|
||||||
|
{
|
||||||
|
$set: updates,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
}
|
||||||
|
|
||||||
|
private isFinalAttempt(job: Job<unknown>): boolean {
|
||||||
|
const attempts =
|
||||||
|
typeof job.opts?.attempts === 'number' && job.opts.attempts > 0
|
||||||
|
? job.opts.attempts
|
||||||
|
: 1;
|
||||||
|
return job.attemptsMade + 1 >= attempts;
|
||||||
|
}
|
||||||
|
|
||||||
|
private publicErrorMessage(): string {
|
||||||
|
return 'Seed collection failed during processing.';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,417 @@
|
|||||||
|
import { Logger } from '@nestjs/common';
|
||||||
|
import type { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { Account } from '../global/database/schemas';
|
||||||
|
import type {
|
||||||
|
RiotAccountDto,
|
||||||
|
RiotApexLeagueEntryDto,
|
||||||
|
RiotApexLeagueListDto,
|
||||||
|
RiotApiClient,
|
||||||
|
RiotLeagueEntryDto,
|
||||||
|
RiotSummonerDto,
|
||||||
|
} from '../riot/riot-api.client';
|
||||||
|
import { SeedCollectionService } from './seed-collection.service';
|
||||||
|
|
||||||
|
interface ExecQuery<T> {
|
||||||
|
exec: jest.Mock<Promise<T>, []>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type FindOneAndUpdateAccountMock = jest.Mock<
|
||||||
|
LeanAccountQuery,
|
||||||
|
[Record<string, unknown>, Record<string, unknown>, Record<string, unknown>?]
|
||||||
|
>;
|
||||||
|
|
||||||
|
interface LeanAccountQuery {
|
||||||
|
lean: jest.Mock<ExecQuery<Account>, []>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Record<string, unknown> {
|
||||||
|
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function execResolved<T>(value: T): ExecQuery<T> {
|
||||||
|
return { exec: jest.fn<Promise<T>, []>().mockResolvedValue(value) };
|
||||||
|
}
|
||||||
|
|
||||||
|
function leanExecResolved<T>(value: T) {
|
||||||
|
return {
|
||||||
|
lean: jest.fn(() => execResolved(value)),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectLeanExecResolved<T>(value: T) {
|
||||||
|
const exec = jest.fn<Promise<T>, []>().mockResolvedValue(value);
|
||||||
|
const lean = jest.fn(() => ({ exec }));
|
||||||
|
const select = jest.fn(() => ({ lean }));
|
||||||
|
return {
|
||||||
|
chain: { select },
|
||||||
|
exec,
|
||||||
|
lean,
|
||||||
|
select,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createApexEntry(
|
||||||
|
puuid: string,
|
||||||
|
overrides: Partial<RiotApexLeagueEntryDto> = {},
|
||||||
|
): RiotApexLeagueEntryDto {
|
||||||
|
return {
|
||||||
|
freshBlood: false,
|
||||||
|
hotStreak: false,
|
||||||
|
inactive: false,
|
||||||
|
leaguePoints: 100,
|
||||||
|
losses: 20,
|
||||||
|
puuid,
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
rank: '',
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
veteran: false,
|
||||||
|
wins: 40,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createAccount(puuid: string): RiotAccountDto {
|
||||||
|
return {
|
||||||
|
puuid,
|
||||||
|
gameName: `Game ${puuid}`,
|
||||||
|
tagLine: 'KR1',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSummoner(puuid: string): RiotSummonerDto {
|
||||||
|
return {
|
||||||
|
profileIconId: 5935,
|
||||||
|
puuid,
|
||||||
|
summonerLevel: 550,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createLeagueEntry(
|
||||||
|
puuid: string,
|
||||||
|
overrides: Partial<RiotLeagueEntryDto> = {},
|
||||||
|
): RiotLeagueEntryDto {
|
||||||
|
return {
|
||||||
|
freshBlood: false,
|
||||||
|
hotStreak: false,
|
||||||
|
inactive: false,
|
||||||
|
leaguePoints: 123,
|
||||||
|
losses: 10,
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
rank: '',
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
veteran: false,
|
||||||
|
wins: 20,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createStoredAccount(overrides: Partial<Account> = {}): Account {
|
||||||
|
return {
|
||||||
|
createdAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
puuid: 'seed-puuid',
|
||||||
|
gameName: 'Seed Player',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
platformRoute: 'kr',
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
profileIconId: 5935,
|
||||||
|
summonerLevel: 550,
|
||||||
|
tiers: [],
|
||||||
|
isSeed: true,
|
||||||
|
seedSource: 'challenger',
|
||||||
|
seedAddedAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
lastSeedCollectedAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createHarness(options: { existingSeedAddedAt?: Date } = {}) {
|
||||||
|
const findOneAccount = jest
|
||||||
|
.fn()
|
||||||
|
.mockReturnValue(
|
||||||
|
selectLeanExecResolved(
|
||||||
|
options.existingSeedAddedAt
|
||||||
|
? { seedAddedAt: options.existingSeedAddedAt }
|
||||||
|
: null,
|
||||||
|
).chain,
|
||||||
|
);
|
||||||
|
const findOneAndUpdateAccount: FindOneAndUpdateAccountMock = jest
|
||||||
|
.fn<LeanAccountQuery, Parameters<FindOneAndUpdateAccountMock>>()
|
||||||
|
.mockImplementation((query) => {
|
||||||
|
const puuid = asRecord(query).puuid;
|
||||||
|
return leanExecResolved(
|
||||||
|
createStoredAccount({
|
||||||
|
puuid: typeof puuid === 'string' ? puuid : 'seed-puuid',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
const accountModel = {
|
||||||
|
findOne: findOneAccount,
|
||||||
|
findOneAndUpdate: findOneAndUpdateAccount,
|
||||||
|
};
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockResolvedValue(accountModel),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
|
||||||
|
const getAccountByPuuid = jest.fn<Promise<RiotAccountDto>, [string, string]>(
|
||||||
|
(puuid) => Promise.resolve(createAccount(puuid)),
|
||||||
|
);
|
||||||
|
const getChallengerLeagueByQueue = jest
|
||||||
|
.fn<Promise<RiotApexLeagueListDto>, [string, string]>()
|
||||||
|
.mockResolvedValue({
|
||||||
|
entries: [],
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
});
|
||||||
|
const getGrandmasterLeagueByQueue = jest
|
||||||
|
.fn<Promise<RiotApexLeagueListDto>, [string, string]>()
|
||||||
|
.mockResolvedValue({
|
||||||
|
entries: [],
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'GRANDMASTER',
|
||||||
|
});
|
||||||
|
const getLeagueEntriesByPuuid = jest.fn<
|
||||||
|
Promise<RiotLeagueEntryDto[]>,
|
||||||
|
[string, string]
|
||||||
|
>((puuid) => Promise.resolve([createLeagueEntry(puuid)]));
|
||||||
|
const getMasterLeagueByQueue = jest
|
||||||
|
.fn<Promise<RiotApexLeagueListDto>, [string, string]>()
|
||||||
|
.mockResolvedValue({
|
||||||
|
entries: [],
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'MASTER',
|
||||||
|
});
|
||||||
|
const getSummonerByPuuid = jest.fn<
|
||||||
|
Promise<RiotSummonerDto>,
|
||||||
|
[string, string]
|
||||||
|
>((puuid) => Promise.resolve(createSummoner(puuid)));
|
||||||
|
const riotApiClient = {
|
||||||
|
getAccountByPuuid,
|
||||||
|
getChallengerLeagueByQueue,
|
||||||
|
getGrandmasterLeagueByQueue,
|
||||||
|
getLeagueEntriesByPuuid,
|
||||||
|
getMasterLeagueByQueue,
|
||||||
|
getSummonerByPuuid,
|
||||||
|
} as unknown as RiotApiClient;
|
||||||
|
|
||||||
|
return {
|
||||||
|
accountModel,
|
||||||
|
connectionService,
|
||||||
|
findOneAccount,
|
||||||
|
findOneAndUpdateAccount,
|
||||||
|
getAccountByPuuid,
|
||||||
|
getChallengerLeagueByQueue,
|
||||||
|
getGrandmasterLeagueByQueue,
|
||||||
|
getLeagueEntriesByPuuid,
|
||||||
|
getMasterLeagueByQueue,
|
||||||
|
getSummonerByPuuid,
|
||||||
|
riotApiClient,
|
||||||
|
service: new SeedCollectionService(connectionService, riotApiClient),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SeedCollectionService', () => {
|
||||||
|
it('collects bounded high-tier seed account metadata', async () => {
|
||||||
|
const collectedAt = new Date('2026-07-03T12:00:00.000Z');
|
||||||
|
const harness = createHarness();
|
||||||
|
harness.getChallengerLeagueByQueue.mockResolvedValue({
|
||||||
|
entries: [
|
||||||
|
createApexEntry('challenger-low', { leaguePoints: 10, wins: 5 }),
|
||||||
|
createApexEntry('challenger-high', { leaguePoints: 500, wins: 50 }),
|
||||||
|
],
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
});
|
||||||
|
harness.getGrandmasterLeagueByQueue.mockResolvedValue({
|
||||||
|
entries: [createApexEntry('grandmaster-one', { tier: 'GRANDMASTER' })],
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'GRANDMASTER',
|
||||||
|
});
|
||||||
|
harness.getMasterLeagueByQueue.mockResolvedValue({
|
||||||
|
entries: [createApexEntry('master-one', { tier: 'MASTER' })],
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'MASTER',
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await harness.service.collectSeedAccounts({
|
||||||
|
collectedAt,
|
||||||
|
platformRoute: 'kr',
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: 1,
|
||||||
|
grandmaster: 1,
|
||||||
|
master: 1,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
platformRoute: 'kr',
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
storedAccounts: 3,
|
||||||
|
storedSeedAccounts: [
|
||||||
|
{
|
||||||
|
puuid: 'challenger-high',
|
||||||
|
source: 'challenger',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
puuid: 'grandmaster-one',
|
||||||
|
source: 'grandmaster',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
puuid: 'master-one',
|
||||||
|
source: 'master',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
skippedAccounts: 0,
|
||||||
|
sourceResults: [
|
||||||
|
{
|
||||||
|
discoveredEntries: 2,
|
||||||
|
selectedEntries: 1,
|
||||||
|
source: 'challenger',
|
||||||
|
storedAccounts: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
discoveredEntries: 1,
|
||||||
|
selectedEntries: 1,
|
||||||
|
source: 'grandmaster',
|
||||||
|
storedAccounts: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
discoveredEntries: 1,
|
||||||
|
selectedEntries: 1,
|
||||||
|
source: 'master',
|
||||||
|
storedAccounts: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(harness.getAccountByPuuid).toHaveBeenCalledWith(
|
||||||
|
'challenger-high',
|
||||||
|
'asia',
|
||||||
|
);
|
||||||
|
expect(harness.findOneAndUpdateAccount).toHaveBeenCalledTimes(3);
|
||||||
|
const challengerUpdate = harness.findOneAndUpdateAccount.mock.calls.find(
|
||||||
|
([query]) => asRecord(query).puuid === 'challenger-high',
|
||||||
|
);
|
||||||
|
expect(challengerUpdate).toBeDefined();
|
||||||
|
expect(challengerUpdate?.[1]).toMatchObject({
|
||||||
|
$set: {
|
||||||
|
gameName: 'Game challenger-high',
|
||||||
|
isSeed: true,
|
||||||
|
lastSeedCollectedAt: collectedAt,
|
||||||
|
platformRoute: 'kr',
|
||||||
|
puuid: 'challenger-high',
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
seedAddedAt: collectedAt,
|
||||||
|
seedSource: 'challenger',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
tiers: [
|
||||||
|
{
|
||||||
|
fetchedAt: collectedAt,
|
||||||
|
leaguePoints: 123,
|
||||||
|
losses: 10,
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
rank: '',
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
wins: 20,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
tiersFetchedAt: collectedAt,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(challengerUpdate?.[2]).toEqual({
|
||||||
|
new: true,
|
||||||
|
setDefaultsOnInsert: true,
|
||||||
|
upsert: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('preserves the first seedAddedAt timestamp when refreshing a seed account', async () => {
|
||||||
|
const existingSeedAddedAt = new Date('2026-07-01T00:00:00.000Z');
|
||||||
|
const collectedAt = new Date('2026-07-03T12:00:00.000Z');
|
||||||
|
const harness = createHarness({ existingSeedAddedAt });
|
||||||
|
harness.getChallengerLeagueByQueue.mockResolvedValue({
|
||||||
|
entries: [createApexEntry('challenger-one')],
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
});
|
||||||
|
|
||||||
|
await harness.service.collectSeedAccounts({
|
||||||
|
collectedAt,
|
||||||
|
platformRoute: 'kr',
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: 1,
|
||||||
|
grandmaster: 0,
|
||||||
|
master: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const challengerUpdate = harness.findOneAndUpdateAccount.mock.calls.find(
|
||||||
|
([query]) => asRecord(query).puuid === 'challenger-one',
|
||||||
|
);
|
||||||
|
expect(challengerUpdate).toBeDefined();
|
||||||
|
expect(challengerUpdate?.[1]).toMatchObject({
|
||||||
|
$set: {
|
||||||
|
lastSeedCollectedAt: collectedAt,
|
||||||
|
seedAddedAt: existingSeedAddedAt,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips failed candidate accounts without aborting the collection pass', async () => {
|
||||||
|
const loggerWarn = jest
|
||||||
|
.spyOn(Logger.prototype, 'warn')
|
||||||
|
.mockImplementation(() => undefined);
|
||||||
|
const harness = createHarness();
|
||||||
|
harness.getChallengerLeagueByQueue.mockResolvedValue({
|
||||||
|
entries: [
|
||||||
|
createApexEntry('broken-puuid', { leaguePoints: 500 }),
|
||||||
|
createApexEntry('stored-puuid', { leaguePoints: 400 }),
|
||||||
|
],
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
});
|
||||||
|
harness.getAccountByPuuid.mockImplementation((puuid) => {
|
||||||
|
if (puuid === 'broken-puuid') {
|
||||||
|
return Promise.reject(new Error('Riot account lookup failed'));
|
||||||
|
}
|
||||||
|
return Promise.resolve(createAccount(puuid));
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await harness.service.collectSeedAccounts({
|
||||||
|
platformRoute: 'kr',
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: 2,
|
||||||
|
grandmaster: 0,
|
||||||
|
master: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
storedAccounts: 1,
|
||||||
|
storedSeedAccounts: [
|
||||||
|
{
|
||||||
|
puuid: 'stored-puuid',
|
||||||
|
source: 'challenger',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
skippedAccounts: 1,
|
||||||
|
sourceResults: [
|
||||||
|
expect.objectContaining({
|
||||||
|
skippedAccounts: 1,
|
||||||
|
storedAccounts: 1,
|
||||||
|
}),
|
||||||
|
expect.any(Object),
|
||||||
|
expect.any(Object),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(harness.findOneAndUpdateAccount).toHaveBeenCalledTimes(1);
|
||||||
|
expect(harness.findOneAndUpdateAccount.mock.calls[0]?.[0]).toEqual({
|
||||||
|
puuid: 'stored-puuid',
|
||||||
|
});
|
||||||
|
|
||||||
|
loggerWarn.mockRestore();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,351 @@
|
|||||||
|
import { Injectable, Logger } from '@nestjs/common';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type { Account, SeedSource, TierInfo } from '../global/database/schemas';
|
||||||
|
import { SEED_SOURCES } from '../global/database/schemas';
|
||||||
|
import {
|
||||||
|
RiotApiClient,
|
||||||
|
type RiotApexLeagueEntryDto,
|
||||||
|
type RiotApexLeagueListDto,
|
||||||
|
type RiotLeagueEntryDto,
|
||||||
|
} from '../riot/riot-api.client';
|
||||||
|
import {
|
||||||
|
toRegionalRoute,
|
||||||
|
type RiotPlatformRoute,
|
||||||
|
type RiotRegionalRoute,
|
||||||
|
} from '../riot/riot.types';
|
||||||
|
import {
|
||||||
|
DEFAULT_SEED_COLLECTION_QUEUE_TYPE,
|
||||||
|
DEFAULT_SEED_COLLECTION_SOURCE_LIMIT,
|
||||||
|
} from './analysis.constants';
|
||||||
|
|
||||||
|
export interface SeedCollectionOptions {
|
||||||
|
collectedAt?: Date;
|
||||||
|
platformRoute: RiotPlatformRoute;
|
||||||
|
queueType?: string;
|
||||||
|
sourceLimits?: Partial<Record<SeedSource, number>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SeedCollectionSourceResult {
|
||||||
|
source: SeedSource;
|
||||||
|
discoveredEntries: number;
|
||||||
|
selectedEntries: number;
|
||||||
|
storedAccounts: number;
|
||||||
|
skippedAccounts: number;
|
||||||
|
duplicateAccounts: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SeedCollectionStoredAccount {
|
||||||
|
puuid: string;
|
||||||
|
source: SeedSource;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SeedCollectionResult {
|
||||||
|
platformRoute: RiotPlatformRoute;
|
||||||
|
regionalRoute: RiotRegionalRoute;
|
||||||
|
queueType: string;
|
||||||
|
sourceResults: SeedCollectionSourceResult[];
|
||||||
|
discoveredEntries: number;
|
||||||
|
selectedEntries: number;
|
||||||
|
storedAccounts: number;
|
||||||
|
skippedAccounts: number;
|
||||||
|
duplicateAccounts: number;
|
||||||
|
storedSeedAccounts: SeedCollectionStoredAccount[];
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SeedCollectionService {
|
||||||
|
private readonly logger = new Logger(SeedCollectionService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly connectionService: ConnectionService,
|
||||||
|
private readonly riotApiClient: RiotApiClient,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public async collectSeedAccounts(
|
||||||
|
options: SeedCollectionOptions,
|
||||||
|
): Promise<SeedCollectionResult> {
|
||||||
|
const collectedAt = options.collectedAt ?? new Date();
|
||||||
|
const platformRoute = options.platformRoute;
|
||||||
|
const regionalRoute = toRegionalRoute(platformRoute);
|
||||||
|
const queueType = options.queueType ?? DEFAULT_SEED_COLLECTION_QUEUE_TYPE;
|
||||||
|
const sourceResults: SeedCollectionSourceResult[] = [];
|
||||||
|
const storedSeedAccounts: SeedCollectionStoredAccount[] = [];
|
||||||
|
const seenPuuids = new Set<string>();
|
||||||
|
|
||||||
|
for (const source of SEED_SOURCES) {
|
||||||
|
const sourceLimit = this.normalizeSourceLimit(
|
||||||
|
options.sourceLimits?.[source],
|
||||||
|
);
|
||||||
|
const leagueList = await this.fetchSeedLeagueList(
|
||||||
|
source,
|
||||||
|
queueType,
|
||||||
|
platformRoute,
|
||||||
|
);
|
||||||
|
const selectedEntries = this.selectCandidateEntries(
|
||||||
|
source,
|
||||||
|
leagueList.entries,
|
||||||
|
sourceLimit,
|
||||||
|
);
|
||||||
|
const sourceResult: SeedCollectionSourceResult = {
|
||||||
|
source,
|
||||||
|
discoveredEntries: leagueList.entries.length,
|
||||||
|
selectedEntries: selectedEntries.length,
|
||||||
|
storedAccounts: 0,
|
||||||
|
skippedAccounts: 0,
|
||||||
|
duplicateAccounts: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const selectedEntry of selectedEntries) {
|
||||||
|
if (seenPuuids.has(selectedEntry.puuid)) {
|
||||||
|
sourceResult.duplicateAccounts += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seenPuuids.add(selectedEntry.puuid);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const storedAccount = await this.storeSeedAccount({
|
||||||
|
collectedAt,
|
||||||
|
platformRoute,
|
||||||
|
puuid: selectedEntry.puuid,
|
||||||
|
regionalRoute,
|
||||||
|
source,
|
||||||
|
});
|
||||||
|
storedSeedAccounts.push({
|
||||||
|
puuid: storedAccount.puuid,
|
||||||
|
source,
|
||||||
|
});
|
||||||
|
sourceResult.storedAccounts += 1;
|
||||||
|
} catch (error) {
|
||||||
|
sourceResult.skippedAccounts += 1;
|
||||||
|
this.logger.warn(
|
||||||
|
`Skipping seed puuid="${this.safeLogText(selectedEntry.puuid)}" source="${source}" after collection failure: ${this.safeLogText(this.errorMessage(error))}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sourceResults.push(sourceResult);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
platformRoute,
|
||||||
|
regionalRoute,
|
||||||
|
queueType,
|
||||||
|
sourceResults,
|
||||||
|
discoveredEntries: this.sumSourceResults(
|
||||||
|
sourceResults,
|
||||||
|
'discoveredEntries',
|
||||||
|
),
|
||||||
|
selectedEntries: this.sumSourceResults(sourceResults, 'selectedEntries'),
|
||||||
|
storedAccounts: this.sumSourceResults(sourceResults, 'storedAccounts'),
|
||||||
|
skippedAccounts: this.sumSourceResults(sourceResults, 'skippedAccounts'),
|
||||||
|
duplicateAccounts: this.sumSourceResults(
|
||||||
|
sourceResults,
|
||||||
|
'duplicateAccounts',
|
||||||
|
),
|
||||||
|
storedSeedAccounts,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchSeedLeagueList(
|
||||||
|
source: SeedSource,
|
||||||
|
queueType: string,
|
||||||
|
platformRoute: RiotPlatformRoute,
|
||||||
|
): Promise<RiotApexLeagueListDto> {
|
||||||
|
if (source === 'challenger') {
|
||||||
|
return this.riotApiClient.getChallengerLeagueByQueue(
|
||||||
|
queueType,
|
||||||
|
platformRoute,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (source === 'grandmaster') {
|
||||||
|
return this.riotApiClient.getGrandmasterLeagueByQueue(
|
||||||
|
queueType,
|
||||||
|
platformRoute,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return this.riotApiClient.getMasterLeagueByQueue(queueType, platformRoute);
|
||||||
|
}
|
||||||
|
|
||||||
|
private selectCandidateEntries(
|
||||||
|
source: SeedSource,
|
||||||
|
entries: RiotApexLeagueEntryDto[],
|
||||||
|
sourceLimit: number,
|
||||||
|
): RiotApexLeagueEntryDto[] {
|
||||||
|
if (sourceLimit <= 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortedEntries = this.deduplicateEntries(entries).sort((left, right) =>
|
||||||
|
this.compareApexEntries(left, right),
|
||||||
|
);
|
||||||
|
if (source === 'master' && sortedEntries.length > sourceLimit) {
|
||||||
|
return this.shuffleEntries(sortedEntries).slice(0, sourceLimit);
|
||||||
|
}
|
||||||
|
return sortedEntries.slice(0, sourceLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
private deduplicateEntries(
|
||||||
|
entries: RiotApexLeagueEntryDto[],
|
||||||
|
): RiotApexLeagueEntryDto[] {
|
||||||
|
const bestEntriesByPuuid = new Map<string, RiotApexLeagueEntryDto>();
|
||||||
|
for (const entry of entries) {
|
||||||
|
const existingEntry = bestEntriesByPuuid.get(entry.puuid);
|
||||||
|
if (!existingEntry || this.compareApexEntries(entry, existingEntry) < 0) {
|
||||||
|
bestEntriesByPuuid.set(entry.puuid, entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return [...bestEntriesByPuuid.values()];
|
||||||
|
}
|
||||||
|
|
||||||
|
private compareApexEntries(
|
||||||
|
left: RiotApexLeagueEntryDto,
|
||||||
|
right: RiotApexLeagueEntryDto,
|
||||||
|
): number {
|
||||||
|
if (right.leaguePoints !== left.leaguePoints) {
|
||||||
|
return right.leaguePoints - left.leaguePoints;
|
||||||
|
}
|
||||||
|
if (right.wins !== left.wins) {
|
||||||
|
return right.wins - left.wins;
|
||||||
|
}
|
||||||
|
if (left.losses !== right.losses) {
|
||||||
|
return left.losses - right.losses;
|
||||||
|
}
|
||||||
|
return left.puuid.localeCompare(right.puuid);
|
||||||
|
}
|
||||||
|
|
||||||
|
private shuffleEntries(
|
||||||
|
entries: RiotApexLeagueEntryDto[],
|
||||||
|
): RiotApexLeagueEntryDto[] {
|
||||||
|
const shuffledEntries = [...entries];
|
||||||
|
for (
|
||||||
|
let currentIndex = shuffledEntries.length - 1;
|
||||||
|
currentIndex > 0;
|
||||||
|
currentIndex -= 1
|
||||||
|
) {
|
||||||
|
const swapIndex = Math.floor(Math.random() * (currentIndex + 1));
|
||||||
|
const currentEntry = shuffledEntries[currentIndex];
|
||||||
|
const swapEntry = shuffledEntries[swapIndex];
|
||||||
|
if (!currentEntry || !swapEntry) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
shuffledEntries[currentIndex] = swapEntry;
|
||||||
|
shuffledEntries[swapIndex] = currentEntry;
|
||||||
|
}
|
||||||
|
return shuffledEntries;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async storeSeedAccount(params: {
|
||||||
|
collectedAt: Date;
|
||||||
|
platformRoute: RiotPlatformRoute;
|
||||||
|
puuid: string;
|
||||||
|
regionalRoute: RiotRegionalRoute;
|
||||||
|
source: SeedSource;
|
||||||
|
}): Promise<Account> {
|
||||||
|
const account = await this.riotApiClient.getAccountByPuuid(
|
||||||
|
params.puuid,
|
||||||
|
params.regionalRoute,
|
||||||
|
);
|
||||||
|
const [summoner, leagueEntries] = await Promise.all([
|
||||||
|
this.riotApiClient.getSummonerByPuuid(
|
||||||
|
account.puuid,
|
||||||
|
params.platformRoute,
|
||||||
|
),
|
||||||
|
this.riotApiClient.getLeagueEntriesByPuuid(
|
||||||
|
account.puuid,
|
||||||
|
params.platformRoute,
|
||||||
|
),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const accountModel = await this.connectionService.getModel('account');
|
||||||
|
const existingAccount = await accountModel
|
||||||
|
.findOne({ puuid: account.puuid })
|
||||||
|
.select('seedAddedAt')
|
||||||
|
.lean<Pick<Account, 'seedAddedAt'> | null>()
|
||||||
|
.exec();
|
||||||
|
const seedAddedAt = existingAccount?.seedAddedAt ?? params.collectedAt;
|
||||||
|
|
||||||
|
const storedAccount = await accountModel
|
||||||
|
.findOneAndUpdate(
|
||||||
|
{ puuid: account.puuid },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
puuid: account.puuid,
|
||||||
|
gameName: account.gameName,
|
||||||
|
tagLine: account.tagLine,
|
||||||
|
platformRoute: params.platformRoute,
|
||||||
|
regionalRoute: params.regionalRoute,
|
||||||
|
profileIconId: summoner.profileIconId,
|
||||||
|
summonerLevel: summoner.summonerLevel,
|
||||||
|
tiers: this.toTierInfo(leagueEntries, params.collectedAt),
|
||||||
|
tiersFetchedAt: params.collectedAt,
|
||||||
|
isSeed: true,
|
||||||
|
seedSource: params.source,
|
||||||
|
seedAddedAt,
|
||||||
|
lastSeedCollectedAt: params.collectedAt,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
new: true,
|
||||||
|
setDefaultsOnInsert: true,
|
||||||
|
upsert: true,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.lean<Account>()
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
if (!storedAccount) {
|
||||||
|
throw new Error('Failed to store seed Riot account.');
|
||||||
|
}
|
||||||
|
return storedAccount;
|
||||||
|
}
|
||||||
|
|
||||||
|
private toTierInfo(
|
||||||
|
entries: RiotLeagueEntryDto[],
|
||||||
|
fetchedAt: Date,
|
||||||
|
): TierInfo[] {
|
||||||
|
return entries.map((entry) => ({
|
||||||
|
queueType: entry.queueType,
|
||||||
|
tier: entry.tier,
|
||||||
|
rank: entry.rank,
|
||||||
|
leaguePoints: entry.leaguePoints,
|
||||||
|
wins: entry.wins,
|
||||||
|
losses: entry.losses,
|
||||||
|
fetchedAt,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeSourceLimit(limit: number | undefined): number {
|
||||||
|
if (limit === undefined) {
|
||||||
|
return DEFAULT_SEED_COLLECTION_SOURCE_LIMIT;
|
||||||
|
}
|
||||||
|
if (!Number.isFinite(limit) || limit < 0) {
|
||||||
|
return DEFAULT_SEED_COLLECTION_SOURCE_LIMIT;
|
||||||
|
}
|
||||||
|
return Math.trunc(limit);
|
||||||
|
}
|
||||||
|
|
||||||
|
private sumSourceResults(
|
||||||
|
sourceResults: SeedCollectionSourceResult[],
|
||||||
|
key: keyof Pick<
|
||||||
|
SeedCollectionSourceResult,
|
||||||
|
| 'discoveredEntries'
|
||||||
|
| 'selectedEntries'
|
||||||
|
| 'storedAccounts'
|
||||||
|
| 'skippedAccounts'
|
||||||
|
| 'duplicateAccounts'
|
||||||
|
>,
|
||||||
|
): number {
|
||||||
|
return sourceResults.reduce(
|
||||||
|
(total, sourceResult) => total + sourceResult[key],
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private errorMessage(error: unknown): string {
|
||||||
|
return error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
private safeLogText(value: string): string {
|
||||||
|
return value.replace(/[\n\r\t]/g, ' ').slice(0, 500);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
import { FEATURE_SCHEMA_VERSION, VECTOR_DIMENSION } from '@persona-lenz/shared';
|
||||||
|
import type { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import { SimilarPlayerService } from './similar-player.service';
|
||||||
|
|
||||||
|
function createLeanExec<T>(value: T) {
|
||||||
|
return {
|
||||||
|
lean: jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createAggregateExec<T>(value: T) {
|
||||||
|
return {
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createSortedLeanExec<T>(value: T) {
|
||||||
|
return {
|
||||||
|
sort: jest.fn(() => ({
|
||||||
|
lean: jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createUpdateExec<T>(value: T) {
|
||||||
|
return {
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createVector(fillValue = 0.5): number[] {
|
||||||
|
return Array.from({ length: VECTOR_DIMENSION }, () => fillValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createProfile(overrides: Record<string, unknown> = {}) {
|
||||||
|
return {
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
sampleGameCount: 35,
|
||||||
|
championPool: [
|
||||||
|
{ championId: 103, games: 8, wins: 5 },
|
||||||
|
{ championId: 84, games: 6, wins: 4 },
|
||||||
|
{ championId: 7, games: 5, wins: 2 },
|
||||||
|
],
|
||||||
|
profile: {
|
||||||
|
kda: 0.3,
|
||||||
|
killParticipation: 0.5,
|
||||||
|
goldPerMin: 0.5,
|
||||||
|
csPerMin: 0.5,
|
||||||
|
deathsPerMin: 0.7,
|
||||||
|
},
|
||||||
|
vector: createVector(),
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
lastMatchAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
tier: 'DIAMOND',
|
||||||
|
isSeed: false,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('SimilarPlayerService', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
jest.useFakeTimers().setSystemTime(new Date('2026-07-03T00:00:00.000Z'));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
jest.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('queries similar profiles without tier filters and ranks by style similarity', async () => {
|
||||||
|
const currentProfile = createProfile();
|
||||||
|
const findOne = jest.fn(() => createLeanExec(currentProfile));
|
||||||
|
const recommendationFindOne = jest.fn(() => createSortedLeanExec(null));
|
||||||
|
const updateOne = jest.fn(() => createUpdateExec({ acknowledged: true }));
|
||||||
|
const aggregate = jest.fn(() =>
|
||||||
|
createAggregateExec([
|
||||||
|
createProfile({
|
||||||
|
puuid: 'lower-style-better-context',
|
||||||
|
championPool: [
|
||||||
|
{ championId: 103, games: 12, wins: 8 },
|
||||||
|
{ championId: 84, games: 5, wins: 4 },
|
||||||
|
{ championId: 777, games: 5, wins: 3 },
|
||||||
|
],
|
||||||
|
profile: {
|
||||||
|
kda: 0.9,
|
||||||
|
killParticipation: 0.49,
|
||||||
|
goldPerMin: 0.8,
|
||||||
|
csPerMin: 0.51,
|
||||||
|
deathsPerMin: 0.2,
|
||||||
|
},
|
||||||
|
sampleGameCount: 20,
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
leaguePoints: 900,
|
||||||
|
lastMatchAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
score: 0.8,
|
||||||
|
}),
|
||||||
|
createProfile({
|
||||||
|
puuid: 'higher-style-similar-player',
|
||||||
|
championPool: [{ championId: 222, games: 30, wins: 20 }],
|
||||||
|
profile: {
|
||||||
|
kda: 0.4,
|
||||||
|
killParticipation: 0.52,
|
||||||
|
goldPerMin: 0.55,
|
||||||
|
csPerMin: 0.7,
|
||||||
|
deathsPerMin: 0.6,
|
||||||
|
},
|
||||||
|
sampleGameCount: 30,
|
||||||
|
tier: 'PLATINUM',
|
||||||
|
lastMatchAt: new Date('2026-06-19T00:00:00.000Z'),
|
||||||
|
score: 0.9,
|
||||||
|
}),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const service = new SimilarPlayerService({
|
||||||
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'playerProfile'
|
||||||
|
? { findOne, aggregate }
|
||||||
|
: { findOne: recommendationFindOne, updateOne },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
const result = await service.findSimilarPlayers('target-puuid', 420, 2);
|
||||||
|
|
||||||
|
expect(findOne).toHaveBeenCalledWith({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
});
|
||||||
|
expect(aggregate).toHaveBeenCalledWith([
|
||||||
|
{
|
||||||
|
$vectorSearch: {
|
||||||
|
index: 'player_profile_vector_index',
|
||||||
|
path: 'vector',
|
||||||
|
queryVector: currentProfile.vector,
|
||||||
|
numCandidates: 200,
|
||||||
|
limit: 50,
|
||||||
|
filter: {
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
queueId: 420,
|
||||||
|
sampleGameCount: { $gte: 20 },
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ $match: { puuid: { $ne: 'target-puuid' } } },
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
puuid: 1,
|
||||||
|
queueId: 1,
|
||||||
|
mainRole: 1,
|
||||||
|
sampleGameCount: 1,
|
||||||
|
championPool: 1,
|
||||||
|
profile: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
lastMatchAt: 1,
|
||||||
|
tier: 1,
|
||||||
|
division: 1,
|
||||||
|
leaguePoints: 1,
|
||||||
|
score: { $meta: 'vectorSearchScore' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(result.profileUpdatedAt).toEqual(
|
||||||
|
new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
);
|
||||||
|
// 스타일 유사도(0.9)가 컨텍스트(챔피언 풀·최근성)보다 랭킹을 지배한다.
|
||||||
|
expect(result.matches.map((match) => match.puuid)).toEqual([
|
||||||
|
'higher-style-similar-player',
|
||||||
|
'lower-style-better-context',
|
||||||
|
]);
|
||||||
|
expect(result.matches[0].finalScore).toBeCloseTo(0.69, 6);
|
||||||
|
expect(result.matches[1].finalScore).toBeCloseTo(0.67, 6);
|
||||||
|
expect(result.matches[0].tierComparison).toBe('lower');
|
||||||
|
expect(result.matches[1].tierComparison).toBe('higher');
|
||||||
|
expect(result.matches[0].similarMetrics).toEqual([
|
||||||
|
{
|
||||||
|
metricId: 'killParticipation',
|
||||||
|
currentValue: 0.5,
|
||||||
|
otherValue: 0.52,
|
||||||
|
absoluteGap: 0.02,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
metricId: 'goldPerMin',
|
||||||
|
currentValue: 0.5,
|
||||||
|
otherValue: 0.55,
|
||||||
|
absoluteGap: 0.05,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
metricId: 'kda',
|
||||||
|
currentValue: 0.3,
|
||||||
|
otherValue: 0.4,
|
||||||
|
absoluteGap: 0.1,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(result.matches[0].strongerMetrics).toEqual([
|
||||||
|
{
|
||||||
|
metricId: 'csPerMin',
|
||||||
|
currentValue: 0.5,
|
||||||
|
otherValue: 0.7,
|
||||||
|
lead: 0.2,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
metricId: 'kda',
|
||||||
|
currentValue: 0.3,
|
||||||
|
otherValue: 0.4,
|
||||||
|
lead: 0.1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
metricId: 'deathsPerMin',
|
||||||
|
currentValue: 0.7,
|
||||||
|
otherValue: 0.6,
|
||||||
|
lead: 0.1,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(result.matches[0].weakerMetrics).toEqual([]);
|
||||||
|
expect(result.matches[1].strongerMetrics).toEqual([
|
||||||
|
{
|
||||||
|
metricId: 'kda',
|
||||||
|
currentValue: 0.3,
|
||||||
|
otherValue: 0.9,
|
||||||
|
lead: 0.6,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
metricId: 'deathsPerMin',
|
||||||
|
currentValue: 0.7,
|
||||||
|
otherValue: 0.2,
|
||||||
|
lead: 0.5,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
metricId: 'goldPerMin',
|
||||||
|
currentValue: 0.5,
|
||||||
|
otherValue: 0.8,
|
||||||
|
lead: 0.3,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(result.matches[1].weakerMetrics).toEqual([
|
||||||
|
{
|
||||||
|
metricId: 'killParticipation',
|
||||||
|
currentValue: 0.5,
|
||||||
|
otherValue: 0.49,
|
||||||
|
lead: 0.01,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
expect(updateOne).toHaveBeenCalledWith(
|
||||||
|
{
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
type: 'similar-player',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
type: 'similar-player',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
result: { matches: result.matches },
|
||||||
|
evidence: {
|
||||||
|
candidateCount: 2,
|
||||||
|
vectorSearchIndex: 'player_profile_vector_index',
|
||||||
|
},
|
||||||
|
generatedAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ upsert: true },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('recomputes when the cached similar-player result is empty', async () => {
|
||||||
|
const currentProfile = createProfile();
|
||||||
|
const candidateProfile = createProfile({
|
||||||
|
puuid: 'newly-indexed-similar-player',
|
||||||
|
score: 0.92,
|
||||||
|
});
|
||||||
|
const findOne = jest.fn(() => createLeanExec(currentProfile));
|
||||||
|
const aggregate = jest.fn(() => createAggregateExec([candidateProfile]));
|
||||||
|
const recommendationFindOne = jest.fn(() =>
|
||||||
|
createSortedLeanExec({
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
result: { matches: [] },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const updateOne = jest.fn(() => createUpdateExec({ acknowledged: true }));
|
||||||
|
const service = new SimilarPlayerService({
|
||||||
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'playerProfile'
|
||||||
|
? { findOne, aggregate }
|
||||||
|
: { findOne: recommendationFindOne, updateOne },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
const result = await service.findSimilarPlayers('target-puuid', 420, 10);
|
||||||
|
|
||||||
|
expect(aggregate).toHaveBeenCalledTimes(1);
|
||||||
|
expect(updateOne).toHaveBeenCalledTimes(1);
|
||||||
|
expect(result.matches).toHaveLength(1);
|
||||||
|
expect(result.matches[0]?.puuid).toBe('newly-indexed-similar-player');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns a fresh cached similar-player recommendation without running vector search', async () => {
|
||||||
|
const currentProfile = createProfile();
|
||||||
|
const cachedMatch = {
|
||||||
|
puuid: 'cached-similar-player',
|
||||||
|
similarityScore: 0.87,
|
||||||
|
finalScore: 0.81,
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
tierComparison: 'higher',
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
|
||||||
|
sampleGameCount: 40,
|
||||||
|
similarMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'kda',
|
||||||
|
currentValue: 0.3,
|
||||||
|
otherValue: 0.31,
|
||||||
|
absoluteGap: 0.01,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
strongerMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'goldPerMin',
|
||||||
|
currentValue: 0.5,
|
||||||
|
otherValue: 0.8,
|
||||||
|
lead: 0.3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
weakerMetrics: [],
|
||||||
|
};
|
||||||
|
const findOne = jest.fn(() => createLeanExec(currentProfile));
|
||||||
|
const aggregate = jest.fn();
|
||||||
|
const recommendationFindOne = jest.fn(() =>
|
||||||
|
createSortedLeanExec({
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
result: { matches: [cachedMatch] },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const updateOne = jest.fn();
|
||||||
|
const service = new SimilarPlayerService({
|
||||||
|
getModel: jest.fn((modelKey: string) =>
|
||||||
|
Promise.resolve(
|
||||||
|
modelKey === 'playerProfile'
|
||||||
|
? { findOne, aggregate }
|
||||||
|
: { findOne: recommendationFindOne, updateOne },
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
const result = await service.findSimilarPlayers('target-puuid', 420, 10);
|
||||||
|
|
||||||
|
expect(recommendationFindOne).toHaveBeenCalledWith({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
type: 'similar-player',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
});
|
||||||
|
expect(aggregate).not.toHaveBeenCalled();
|
||||||
|
expect(updateOne).not.toHaveBeenCalled();
|
||||||
|
expect(result).toEqual({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
matches: [cachedMatch],
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('throws when the player profile has not been built yet', async () => {
|
||||||
|
const findOne = jest.fn(() => createLeanExec(null));
|
||||||
|
const aggregate = jest.fn();
|
||||||
|
const service = new SimilarPlayerService({
|
||||||
|
getModel: jest.fn().mockResolvedValue({ findOne, aggregate }),
|
||||||
|
} as unknown as ConnectionService);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.findSimilarPlayers('missing-puuid', 420),
|
||||||
|
).rejects.toThrow('Player profile not found.');
|
||||||
|
expect(aggregate).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,488 @@
|
|||||||
|
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
FEATURE_SCHEMA_VERSION,
|
||||||
|
METRICS,
|
||||||
|
ROLES,
|
||||||
|
VECTOR_DIMENSION,
|
||||||
|
type MetricDefinition,
|
||||||
|
type Role,
|
||||||
|
type TierComparison,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
|
import type { PipelineStage } from 'mongoose';
|
||||||
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
|
import type {
|
||||||
|
ChampionPoolEntry,
|
||||||
|
LeadMetric,
|
||||||
|
SimilarMetric,
|
||||||
|
SimilarPlayer,
|
||||||
|
SimilarPlayersResult,
|
||||||
|
} from './analysis.types';
|
||||||
|
|
||||||
|
const SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME = 'player_profile_vector_index';
|
||||||
|
const SIMILAR_PLAYER_VECTOR_SEARCH_NUM_CANDIDATES = 200;
|
||||||
|
const SIMILAR_PLAYER_VECTOR_SEARCH_LIMIT = 50;
|
||||||
|
const DEFAULT_SIMILAR_PLAYER_LIMIT = 10;
|
||||||
|
const MINIMUM_SAMPLE_GAME_COUNT = 20;
|
||||||
|
const LOW_SAMPLE_GAME_COUNT_THRESHOLD = 30;
|
||||||
|
const LOW_SAMPLE_PENALTY = 0.1;
|
||||||
|
const RECENCY_HALF_LIFE_MS = 14 * 24 * 60 * 60 * 1000;
|
||||||
|
const TIER_ORDER = [
|
||||||
|
'IRON',
|
||||||
|
'BRONZE',
|
||||||
|
'SILVER',
|
||||||
|
'GOLD',
|
||||||
|
'PLATINUM',
|
||||||
|
'EMERALD',
|
||||||
|
'DIAMOND',
|
||||||
|
'MASTER',
|
||||||
|
'GRANDMASTER',
|
||||||
|
'CHALLENGER',
|
||||||
|
];
|
||||||
|
const TIER_COMPARISONS: TierComparison[] = [
|
||||||
|
'higher',
|
||||||
|
'same',
|
||||||
|
'lower',
|
||||||
|
'unknown',
|
||||||
|
];
|
||||||
|
|
||||||
|
interface PlayerProfileRecord {
|
||||||
|
puuid: string;
|
||||||
|
queueId: number;
|
||||||
|
mainRole: Role;
|
||||||
|
sampleGameCount: number;
|
||||||
|
championPool: ChampionPoolEntry[];
|
||||||
|
profile: Record<string, number>;
|
||||||
|
vector: number[];
|
||||||
|
updatedAt: Date;
|
||||||
|
lastMatchAt?: Date;
|
||||||
|
tier?: string;
|
||||||
|
division?: string;
|
||||||
|
leaguePoints?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface VectorSearchRecord extends Omit<PlayerProfileRecord, 'vector'> {
|
||||||
|
score?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RecommendationCacheRecord {
|
||||||
|
result?: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 나와 플레이스타일 벡터가 가까운 유저를 찾는다. 목적은 "따라 할 멘토"가 아니라
|
||||||
|
* "스타일은 비슷한데 왜 점수(티어)가 다른가"라는 인사이트 제공이므로,
|
||||||
|
* 후보를 티어로 거르지 않고 유사도 중심으로 랭킹한 뒤 티어 관계와
|
||||||
|
* 지표 우위(양방향)를 함께 반환한다.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class SimilarPlayerService {
|
||||||
|
constructor(private readonly connectionService: ConnectionService) {}
|
||||||
|
|
||||||
|
public async findSimilarPlayers(
|
||||||
|
puuid: string,
|
||||||
|
queueId: number,
|
||||||
|
requestedLimit = DEFAULT_SIMILAR_PLAYER_LIMIT,
|
||||||
|
): Promise<SimilarPlayersResult> {
|
||||||
|
const playerProfileModel =
|
||||||
|
await this.connectionService.getModel('playerProfile');
|
||||||
|
const recommendationModel =
|
||||||
|
await this.connectionService.getModel('recommendation');
|
||||||
|
const normalizedLimit = this.normalizeLimit(requestedLimit);
|
||||||
|
const currentProfile = await playerProfileModel
|
||||||
|
.findOne({ puuid, queueId, featureSchemaVersion: FEATURE_SCHEMA_VERSION })
|
||||||
|
.lean<PlayerProfileRecord>()
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
if (!currentProfile) {
|
||||||
|
throw new NotFoundException('Player profile not found.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cacheFilter = this.createRecommendationFilter(
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
currentProfile.updatedAt,
|
||||||
|
);
|
||||||
|
const cachedRecommendation = await recommendationModel
|
||||||
|
.findOne(cacheFilter)
|
||||||
|
.sort({ generatedAt: -1 })
|
||||||
|
.lean<RecommendationCacheRecord>()
|
||||||
|
.exec();
|
||||||
|
const cachedMatches = this.extractCachedMatches(cachedRecommendation);
|
||||||
|
if (cachedMatches) {
|
||||||
|
return {
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
profileUpdatedAt: currentProfile.updatedAt,
|
||||||
|
matches: cachedMatches.slice(0, normalizedLimit),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (currentProfile.vector.length !== VECTOR_DIMENSION) {
|
||||||
|
return {
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
profileUpdatedAt: currentProfile.updatedAt,
|
||||||
|
matches: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const candidates = await playerProfileModel
|
||||||
|
.aggregate<VectorSearchRecord>(
|
||||||
|
this.createCandidatePipeline(currentProfile, puuid, queueId),
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
const matches = candidates
|
||||||
|
.map((candidate) => this.toSimilarPlayer(currentProfile, candidate))
|
||||||
|
.sort((left, right) => right.finalScore - left.finalScore)
|
||||||
|
.slice(0, normalizedLimit);
|
||||||
|
|
||||||
|
await recommendationModel
|
||||||
|
.updateOne(
|
||||||
|
cacheFilter,
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
type: 'similar-player',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt: currentProfile.updatedAt,
|
||||||
|
result: { matches },
|
||||||
|
evidence: {
|
||||||
|
candidateCount: candidates.length,
|
||||||
|
vectorSearchIndex: SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME,
|
||||||
|
},
|
||||||
|
generatedAt: new Date(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ upsert: true },
|
||||||
|
)
|
||||||
|
.exec();
|
||||||
|
|
||||||
|
return {
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
profileUpdatedAt: currentProfile.updatedAt,
|
||||||
|
matches,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private createRecommendationFilter(
|
||||||
|
puuid: string,
|
||||||
|
queueId: number,
|
||||||
|
profileUpdatedAt: Date,
|
||||||
|
): {
|
||||||
|
puuid: string;
|
||||||
|
queueId: number;
|
||||||
|
type: 'similar-player';
|
||||||
|
featureSchemaVersion: number;
|
||||||
|
profileUpdatedAt: Date;
|
||||||
|
} {
|
||||||
|
return {
|
||||||
|
puuid,
|
||||||
|
queueId,
|
||||||
|
type: 'similar-player',
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
profileUpdatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private createCandidatePipeline(
|
||||||
|
currentProfile: PlayerProfileRecord,
|
||||||
|
puuid: string,
|
||||||
|
queueId: number,
|
||||||
|
): PipelineStage[] {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
$vectorSearch: {
|
||||||
|
index: SIMILAR_PLAYER_VECTOR_SEARCH_INDEX_NAME,
|
||||||
|
path: 'vector',
|
||||||
|
queryVector: currentProfile.vector,
|
||||||
|
numCandidates: SIMILAR_PLAYER_VECTOR_SEARCH_NUM_CANDIDATES,
|
||||||
|
limit: SIMILAR_PLAYER_VECTOR_SEARCH_LIMIT,
|
||||||
|
filter: {
|
||||||
|
mainRole: currentProfile.mainRole,
|
||||||
|
queueId,
|
||||||
|
sampleGameCount: { $gte: MINIMUM_SAMPLE_GAME_COUNT },
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ $match: { puuid: { $ne: puuid } } },
|
||||||
|
{
|
||||||
|
$project: {
|
||||||
|
puuid: 1,
|
||||||
|
queueId: 1,
|
||||||
|
mainRole: 1,
|
||||||
|
sampleGameCount: 1,
|
||||||
|
championPool: 1,
|
||||||
|
profile: 1,
|
||||||
|
updatedAt: 1,
|
||||||
|
lastMatchAt: 1,
|
||||||
|
tier: 1,
|
||||||
|
division: 1,
|
||||||
|
leaguePoints: 1,
|
||||||
|
score: { $meta: 'vectorSearchScore' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private toSimilarPlayer(
|
||||||
|
currentProfile: PlayerProfileRecord,
|
||||||
|
candidate: VectorSearchRecord,
|
||||||
|
): SimilarPlayer {
|
||||||
|
const similarityScore = this.clamp01(candidate.score ?? 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
puuid: candidate.puuid,
|
||||||
|
similarityScore,
|
||||||
|
finalScore: this.calculateFinalScore(
|
||||||
|
currentProfile,
|
||||||
|
candidate,
|
||||||
|
similarityScore,
|
||||||
|
),
|
||||||
|
tier: candidate.tier,
|
||||||
|
division: candidate.division,
|
||||||
|
leaguePoints: candidate.leaguePoints,
|
||||||
|
tierComparison: this.compareTier(currentProfile.tier, candidate.tier),
|
||||||
|
mainRole: candidate.mainRole,
|
||||||
|
mainChampions: candidate.championPool.slice(0, 3),
|
||||||
|
sampleGameCount: candidate.sampleGameCount,
|
||||||
|
similarMetrics: this.resolveSimilarMetrics(
|
||||||
|
currentProfile.profile,
|
||||||
|
candidate.profile,
|
||||||
|
),
|
||||||
|
strongerMetrics: this.resolveLeadMetrics(
|
||||||
|
currentProfile.profile,
|
||||||
|
candidate.profile,
|
||||||
|
'other',
|
||||||
|
),
|
||||||
|
weakerMetrics: this.resolveLeadMetrics(
|
||||||
|
currentProfile.profile,
|
||||||
|
candidate.profile,
|
||||||
|
'current',
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private calculateFinalScore(
|
||||||
|
currentProfile: PlayerProfileRecord,
|
||||||
|
candidate: VectorSearchRecord,
|
||||||
|
similarityScore: number,
|
||||||
|
): number {
|
||||||
|
const championPoolSimilarity = this.calculateChampionPoolSimilarity(
|
||||||
|
currentProfile.championPool,
|
||||||
|
candidate.championPool,
|
||||||
|
);
|
||||||
|
const recencyScore = this.calculateRecencyScore(candidate.lastMatchAt);
|
||||||
|
const lowSamplePenalty =
|
||||||
|
candidate.sampleGameCount < LOW_SAMPLE_GAME_COUNT_THRESHOLD
|
||||||
|
? LOW_SAMPLE_PENALTY
|
||||||
|
: 0;
|
||||||
|
|
||||||
|
// 유사도가 랭킹을 지배해야 한다 — 티어는 랭킹 요소가 아니라 인사이트(tierComparison)로만 쓴다.
|
||||||
|
return this.clamp01(
|
||||||
|
0.7 * similarityScore +
|
||||||
|
0.18 * championPoolSimilarity +
|
||||||
|
0.12 * recencyScore -
|
||||||
|
lowSamplePenalty,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private compareTier(
|
||||||
|
currentTier: string | undefined,
|
||||||
|
otherTier: string | undefined,
|
||||||
|
): TierComparison {
|
||||||
|
const currentTierRank = TIER_ORDER.indexOf(currentTier ?? '');
|
||||||
|
const otherTierRank = TIER_ORDER.indexOf(otherTier ?? '');
|
||||||
|
if (currentTierRank < 0 || otherTierRank < 0) return 'unknown';
|
||||||
|
if (otherTierRank > currentTierRank) return 'higher';
|
||||||
|
if (otherTierRank < currentTierRank) return 'lower';
|
||||||
|
return 'same';
|
||||||
|
}
|
||||||
|
|
||||||
|
private calculateChampionPoolSimilarity(
|
||||||
|
currentChampionPool: ChampionPoolEntry[],
|
||||||
|
otherChampionPool: ChampionPoolEntry[],
|
||||||
|
): number {
|
||||||
|
const currentChampionIds = new Set(
|
||||||
|
currentChampionPool.slice(0, 5).map((entry) => entry.championId),
|
||||||
|
);
|
||||||
|
const otherChampionIds = new Set(
|
||||||
|
otherChampionPool.slice(0, 5).map((entry) => entry.championId),
|
||||||
|
);
|
||||||
|
const unionChampionIds = new Set([
|
||||||
|
...currentChampionIds,
|
||||||
|
...otherChampionIds,
|
||||||
|
]);
|
||||||
|
if (unionChampionIds.size === 0) return 0;
|
||||||
|
|
||||||
|
let sharedChampionCount = 0;
|
||||||
|
currentChampionIds.forEach((championId) => {
|
||||||
|
if (otherChampionIds.has(championId)) sharedChampionCount += 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
return sharedChampionCount / unionChampionIds.size;
|
||||||
|
}
|
||||||
|
|
||||||
|
private calculateRecencyScore(lastMatchAt: Date | undefined): number {
|
||||||
|
if (!lastMatchAt) return 0;
|
||||||
|
const ageMs = Date.now() - lastMatchAt.getTime();
|
||||||
|
if (ageMs <= 0) return 1;
|
||||||
|
return this.clamp01(Math.pow(0.5, ageMs / RECENCY_HALF_LIFE_MS));
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveSimilarMetrics(
|
||||||
|
currentProfile: Record<string, number>,
|
||||||
|
otherProfile: Record<string, number>,
|
||||||
|
): SimilarMetric[] {
|
||||||
|
return METRICS.flatMap((metric) => {
|
||||||
|
const comparison = this.createMetricValues(
|
||||||
|
currentProfile,
|
||||||
|
otherProfile,
|
||||||
|
metric,
|
||||||
|
);
|
||||||
|
if (!comparison) return [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
metricId: metric.id,
|
||||||
|
currentValue: comparison.currentValue,
|
||||||
|
otherValue: comparison.otherValue,
|
||||||
|
absoluteGap: this.roundMetricGap(
|
||||||
|
Math.abs(comparison.otherValue - comparison.currentValue),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((left, right) => left.absoluteGap - right.absoluteGap)
|
||||||
|
.slice(0, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveLeadMetrics(
|
||||||
|
currentProfile: Record<string, number>,
|
||||||
|
otherProfile: Record<string, number>,
|
||||||
|
leader: 'current' | 'other',
|
||||||
|
): LeadMetric[] {
|
||||||
|
return METRICS.flatMap((metric) => {
|
||||||
|
const comparison = this.createMetricValues(
|
||||||
|
currentProfile,
|
||||||
|
otherProfile,
|
||||||
|
metric,
|
||||||
|
);
|
||||||
|
if (!comparison) return [];
|
||||||
|
|
||||||
|
const otherAdvantage =
|
||||||
|
metric.direction === 'lowerIsBetter'
|
||||||
|
? comparison.currentValue - comparison.otherValue
|
||||||
|
: comparison.otherValue - comparison.currentValue;
|
||||||
|
const lead = leader === 'other' ? otherAdvantage : -otherAdvantage;
|
||||||
|
if (lead <= 0) return [];
|
||||||
|
|
||||||
|
return {
|
||||||
|
metricId: metric.id,
|
||||||
|
currentValue: comparison.currentValue,
|
||||||
|
otherValue: comparison.otherValue,
|
||||||
|
lead: this.roundMetricGap(lead),
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((left, right) => right.lead - left.lead)
|
||||||
|
.slice(0, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
private createMetricValues(
|
||||||
|
currentProfile: Record<string, number>,
|
||||||
|
otherProfile: Record<string, number>,
|
||||||
|
metric: MetricDefinition,
|
||||||
|
): { currentValue: number; otherValue: number } | null {
|
||||||
|
const currentValue = currentProfile[metric.id];
|
||||||
|
const otherValue = otherProfile[metric.id];
|
||||||
|
if (!Number.isFinite(currentValue) || !Number.isFinite(otherValue)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
currentValue: this.clamp01(currentValue),
|
||||||
|
otherValue: this.clamp01(otherValue),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeLimit(requestedLimit: number): number {
|
||||||
|
if (!Number.isInteger(requestedLimit) || requestedLimit < 1) {
|
||||||
|
return DEFAULT_SIMILAR_PLAYER_LIMIT;
|
||||||
|
}
|
||||||
|
return Math.min(requestedLimit, DEFAULT_SIMILAR_PLAYER_LIMIT);
|
||||||
|
}
|
||||||
|
|
||||||
|
private roundMetricGap(value: number): number {
|
||||||
|
return Math.round(value * 1_000_000) / 1_000_000;
|
||||||
|
}
|
||||||
|
|
||||||
|
private clamp01(value: number): number {
|
||||||
|
if (!Number.isFinite(value)) return 0;
|
||||||
|
return Math.max(0, Math.min(1, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
private extractCachedMatches(
|
||||||
|
recommendation: RecommendationCacheRecord | null,
|
||||||
|
): SimilarPlayer[] | null {
|
||||||
|
const matches = recommendation?.result?.matches;
|
||||||
|
if (!Array.isArray(matches)) return null;
|
||||||
|
if (matches.length === 0) return null;
|
||||||
|
if (!matches.every((match) => this.isCachedSimilarPlayer(match))) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isCachedSimilarPlayer(value: unknown): value is SimilarPlayer {
|
||||||
|
const record = this.asRecord(value);
|
||||||
|
if (!record) return false;
|
||||||
|
|
||||||
|
return (
|
||||||
|
typeof record.puuid === 'string' &&
|
||||||
|
this.isFiniteNumber(record.similarityScore) &&
|
||||||
|
this.isFiniteNumber(record.finalScore) &&
|
||||||
|
typeof record.tierComparison === 'string' &&
|
||||||
|
TIER_COMPARISONS.includes(record.tierComparison as TierComparison) &&
|
||||||
|
typeof record.mainRole === 'string' &&
|
||||||
|
ROLES.includes(record.mainRole as Role) &&
|
||||||
|
Array.isArray(record.mainChampions) &&
|
||||||
|
this.isFiniteNumber(record.sampleGameCount) &&
|
||||||
|
this.isCachedMetricComparisonArray(
|
||||||
|
record.similarMetrics,
|
||||||
|
'absoluteGap',
|
||||||
|
) &&
|
||||||
|
this.isCachedMetricComparisonArray(record.strongerMetrics, 'lead') &&
|
||||||
|
this.isCachedMetricComparisonArray(record.weakerMetrics, 'lead')
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private isCachedMetricComparisonArray(
|
||||||
|
value: unknown,
|
||||||
|
scoreFieldName: 'absoluteGap' | 'lead',
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
Array.isArray(value) &&
|
||||||
|
value.every((entry) => {
|
||||||
|
const record = this.asRecord(entry);
|
||||||
|
return (
|
||||||
|
record !== null &&
|
||||||
|
typeof record.metricId === 'string' &&
|
||||||
|
this.isFiniteNumber(record.currentValue) &&
|
||||||
|
this.isFiniteNumber(record.otherValue) &&
|
||||||
|
this.isFiniteNumber(record[scoreFieldName])
|
||||||
|
);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private asRecord(value: unknown): Record<string, unknown> | null {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||||
|
? (value as Record<string, unknown>)
|
||||||
|
: null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private isFiniteNumber(value: unknown): value is number {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,676 @@
|
|||||||
|
import { TimelineDerivedService } from './timeline-derived.service';
|
||||||
|
|
||||||
|
function createTimelinePayload(
|
||||||
|
eventsByFrame: Array<Record<string, unknown>[]>,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
info: {
|
||||||
|
frames: eventsByFrame.map((events, index) => ({
|
||||||
|
timestamp: index * 60_000,
|
||||||
|
events,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTimelinePayloadWithFrames(
|
||||||
|
frames: Array<{
|
||||||
|
timestamp?: number;
|
||||||
|
events?: Record<string, unknown>[];
|
||||||
|
participantFrames?: Record<string, unknown>;
|
||||||
|
}>,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
info: {
|
||||||
|
frames: frames.map((frame, index) => ({
|
||||||
|
timestamp: frame.timestamp ?? index * 60_000,
|
||||||
|
events: frame.events ?? [],
|
||||||
|
participantFrames: frame.participantFrames ?? {},
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('TimelineDerivedService', () => {
|
||||||
|
const service = new TimelineDerivedService();
|
||||||
|
|
||||||
|
it('clusters champion kills transitively by time and distance', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 10_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
assistingParticipantIds: [2],
|
||||||
|
position: { x: 1_000, y: 1_000 },
|
||||||
|
victimDamageReceived: [
|
||||||
|
{
|
||||||
|
participantId: 3,
|
||||||
|
magicDamageDone: 100,
|
||||||
|
physicalDamageDone: 50,
|
||||||
|
trueDamageDone: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
participantId: 1,
|
||||||
|
magicDamageDone: 20,
|
||||||
|
physicalDamageDone: 30,
|
||||||
|
trueDamageDone: 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 24_000,
|
||||||
|
killerId: 2,
|
||||||
|
victimId: 7,
|
||||||
|
assistingParticipantIds: null,
|
||||||
|
victimDamageReceived: null,
|
||||||
|
position: { x: 3_400, y: 1_000 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 38_000,
|
||||||
|
killerId: 4,
|
||||||
|
victimId: 8,
|
||||||
|
assistingParticipantIds: [5],
|
||||||
|
position: { x: 5_800, y: 1_000 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.fightClusters).toEqual([
|
||||||
|
{
|
||||||
|
startTimeMs: 10_000,
|
||||||
|
endTimeMs: 38_000,
|
||||||
|
killCount: 3,
|
||||||
|
participantIds: [1, 2, 3, 4, 5, 6, 7, 8],
|
||||||
|
openerParticipantIds: [1, 2, 3],
|
||||||
|
cleanupParticipantIds: [4, 5, 8],
|
||||||
|
isTeamfight: true,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('separates champion kills that are not connected by both time and distance', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 10_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
position: { x: 1_000, y: 1_000 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 20_000,
|
||||||
|
killerId: 2,
|
||||||
|
victimId: 7,
|
||||||
|
position: { x: 7_000, y: 1_000 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 40_000,
|
||||||
|
killerId: 3,
|
||||||
|
victimId: 8,
|
||||||
|
position: { x: 7_500, y: 1_000 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.fightClusters).toHaveLength(3);
|
||||||
|
expect(derived.fightClusters.map((cluster) => cluster.killCount)).toEqual([
|
||||||
|
1, 1, 1,
|
||||||
|
]);
|
||||||
|
expect(
|
||||||
|
derived.fightClusters.every((cluster) => cluster.isTeamfight === false),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes every kill within five seconds of the last kill as cleanup', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 10_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
position: { x: 1_000, y: 1_000 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 20_000,
|
||||||
|
killerId: 2,
|
||||||
|
victimId: 7,
|
||||||
|
position: { x: 2_000, y: 1_000 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 24_000,
|
||||||
|
killerId: 3,
|
||||||
|
victimId: 8,
|
||||||
|
position: { x: 2_500, y: 1_000 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.fightClusters[0].cleanupParticipantIds).toEqual([
|
||||||
|
2, 3, 7, 8,
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses explicit victim damage totals without adding component damage twice', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 10_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
position: { x: 1_000, y: 1_000 },
|
||||||
|
victimDamageReceived: [
|
||||||
|
{
|
||||||
|
participantId: 3,
|
||||||
|
totalDamageDone: 100,
|
||||||
|
magicDamageDone: 1_000,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
participantId: 4,
|
||||||
|
magicDamageDone: 150,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.fightClusters[0].openerParticipantIds).toEqual([1, 4]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aggregates duplicate victim damage rows before selecting the opener contributor', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 10_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
position: { x: 1_000, y: 1_000 },
|
||||||
|
victimDamageReceived: [
|
||||||
|
{
|
||||||
|
participantId: 3,
|
||||||
|
magicDamageDone: 80,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
participantId: 3,
|
||||||
|
physicalDamageDone: 80,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
participantId: 4,
|
||||||
|
magicDamageDone: 150,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.fightClusters[0].openerParticipantIds).toEqual([1, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds objective windows around elite monster kill timestamps', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'ELITE_MONSTER_KILL',
|
||||||
|
timestamp: 900_000,
|
||||||
|
killerId: 4,
|
||||||
|
killerTeamId: 100,
|
||||||
|
monsterType: 'DRAGON',
|
||||||
|
monsterSubType: 'HEXTECH_DRAGON',
|
||||||
|
position: { x: 9_800, y: 4_400 },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'WARD_PLACED',
|
||||||
|
timestamp: 905_000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.objectiveWindows).toEqual([
|
||||||
|
{
|
||||||
|
objectiveTimeMs: 900_000,
|
||||||
|
startTimeMs: 780_000,
|
||||||
|
endTimeMs: 930_000,
|
||||||
|
killerParticipantId: 4,
|
||||||
|
killerTeamId: 100,
|
||||||
|
monsterType: 'DRAGON',
|
||||||
|
monsterSubType: 'HEXTECH_DRAGON',
|
||||||
|
position: { x: 9_800, y: 4_400 },
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('ignores elite monster kills outside dragon, rift herald, and baron', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'ELITE_MONSTER_KILL',
|
||||||
|
timestamp: 900_000,
|
||||||
|
killerId: 4,
|
||||||
|
killerTeamId: 100,
|
||||||
|
monsterType: 'HORDE',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'ELITE_MONSTER_KILL',
|
||||||
|
timestamp: 1_200_000,
|
||||||
|
killerId: 5,
|
||||||
|
killerTeamId: 200,
|
||||||
|
monsterType: 'BARON_NASHOR',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.objectiveWindows).toHaveLength(1);
|
||||||
|
expect(derived.objectiveWindows[0].monsterType).toBe('BARON_NASHOR');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds death events with shutdown bounty, zone, and nearest ally approximation', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayloadWithFrames([
|
||||||
|
{
|
||||||
|
timestamp: 0,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 9_870, y: 4_414 } },
|
||||||
|
'7': { position: { x: 9_000, y: 4_000 } },
|
||||||
|
'8': { position: { x: 12_000, y: 4_000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 30_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 30_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
shutdownBounty: 277,
|
||||||
|
position: { x: 9_866, y: 4_414 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 9_870, y: 4_414 } },
|
||||||
|
'7': { position: { x: 10_000, y: 4_000 } },
|
||||||
|
'8': { position: { x: 12_000, y: 4_000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.deathEvents).toEqual([
|
||||||
|
{
|
||||||
|
t: 30_000,
|
||||||
|
victimParticipantId: 6,
|
||||||
|
x: 9_866,
|
||||||
|
y: 4_414,
|
||||||
|
zone: 'dragonPit',
|
||||||
|
shutdownBountyGiven: 277,
|
||||||
|
nearestAllyDistanceApprox: 553,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('interpolates missing death positions from victim frames', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayloadWithFrames([
|
||||||
|
{
|
||||||
|
timestamp: 0,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 4_020, y: 6_000 } },
|
||||||
|
'6': { position: { x: 3_000, y: 6_000 } },
|
||||||
|
'7': { position: { x: 8_000, y: 6_000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 30_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 30_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 4_020, y: 6_000 } },
|
||||||
|
'6': { position: { x: 5_000, y: 6_000 } },
|
||||||
|
'7': { position: { x: 10_000, y: 6_000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.deathEvents).toEqual([
|
||||||
|
{
|
||||||
|
t: 30_000,
|
||||||
|
victimParticipantId: 6,
|
||||||
|
x: 4_000,
|
||||||
|
y: 6_000,
|
||||||
|
zone: 'southWestJungle',
|
||||||
|
shutdownBountyGiven: 0,
|
||||||
|
nearestAllyDistanceApprox: 5_000,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('classifies representative Summoner Rift death zones', () => {
|
||||||
|
const positions = [
|
||||||
|
{ x: 600, y: 600, zone: 'blueBase' },
|
||||||
|
{ x: 14_200, y: 14_200, zone: 'redBase' },
|
||||||
|
{ x: 1_000, y: 9_000, zone: 'topLane' },
|
||||||
|
{ x: 6_500, y: 6_500, zone: 'middleLane' },
|
||||||
|
{ x: 9_000, y: 1_000, zone: 'bottomLane' },
|
||||||
|
{ x: 8_000, y: 7_000, zone: 'river' },
|
||||||
|
{ x: 2_500, y: 8_500, zone: 'northWestJungle' },
|
||||||
|
{ x: 12_000, y: 9_000, zone: 'northEastJungle' },
|
||||||
|
{ x: 4_000, y: 6_000, zone: 'southWestJungle' },
|
||||||
|
{ x: 13_000, y: 5_000, zone: 'southEastJungle' },
|
||||||
|
{ x: 9_866, y: 4_414, zone: 'dragonPit' },
|
||||||
|
{ x: 5_007, y: 10_471, zone: 'baronPit' },
|
||||||
|
{ x: -1, y: 7_500, zone: 'unknown' },
|
||||||
|
];
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
positions.map((position, index) => ({
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: (index + 1) * 1_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
position: { x: position.x, y: position.y },
|
||||||
|
})),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.deathEvents.map((deathEvent) => deathEvent.zone)).toEqual(
|
||||||
|
positions.map((position) => position.zone),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds roam frames for non-jungle laners between 8 and 14 minutes', () => {
|
||||||
|
const rawMatch = {
|
||||||
|
info: {
|
||||||
|
participants: [
|
||||||
|
{ participantId: 1, teamId: 100, teamPosition: 'TOP' },
|
||||||
|
{ participantId: 2, teamId: 100, teamPosition: 'JUNGLE' },
|
||||||
|
{ participantId: 6, teamId: 200, teamPosition: 'MIDDLE' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayloadWithFrames([
|
||||||
|
{
|
||||||
|
timestamp: 7 * 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 8_000, y: 7_000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 8 * 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 8_000, y: 7_000 } },
|
||||||
|
'2': { position: { x: 8_000, y: 7_000 } },
|
||||||
|
'6': { position: { x: 14_200, y: 14_200 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 9 * 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 1_000, y: 9_000 } },
|
||||||
|
'6': { position: { x: 8_000, y: 7_000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 14 * 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 9_000, y: 1_000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 15 * 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 8_000, y: 7_000 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
rawMatch,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.roamFrames).toEqual([
|
||||||
|
{
|
||||||
|
t: 8 * 60_000,
|
||||||
|
participantId: 1,
|
||||||
|
teamId: 100,
|
||||||
|
x: 8_000,
|
||||||
|
y: 7_000,
|
||||||
|
zone: 'river',
|
||||||
|
assignedLaneZone: 'topLane',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
t: 9 * 60_000,
|
||||||
|
participantId: 6,
|
||||||
|
teamId: 200,
|
||||||
|
x: 8_000,
|
||||||
|
y: 7_000,
|
||||||
|
zone: 'river',
|
||||||
|
assignedLaneZone: 'middleLane',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
t: 14 * 60_000,
|
||||||
|
participantId: 1,
|
||||||
|
teamId: 100,
|
||||||
|
x: 9_000,
|
||||||
|
y: 1_000,
|
||||||
|
zone: 'bottomLane',
|
||||||
|
assignedLaneZone: 'topLane',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses the participant own base only when filtering roam frames', () => {
|
||||||
|
const rawMatch = {
|
||||||
|
info: {
|
||||||
|
participants: [{ participantId: 1, teamId: 100, teamPosition: 'TOP' }],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayloadWithFrames([
|
||||||
|
{
|
||||||
|
timestamp: 8 * 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 600, y: 600 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 9 * 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 14_200, y: 14_200 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
rawMatch,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.roamFrames).toEqual([
|
||||||
|
{
|
||||||
|
t: 9 * 60_000,
|
||||||
|
participantId: 1,
|
||||||
|
teamId: 100,
|
||||||
|
x: 14_200,
|
||||||
|
y: 14_200,
|
||||||
|
zone: 'redBase',
|
||||||
|
assignedLaneZone: 'topLane',
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits roam frames when participant id or map zone is unknown', () => {
|
||||||
|
const rawMatch = {
|
||||||
|
info: {
|
||||||
|
participants: [
|
||||||
|
{ teamId: 100, teamPosition: 'TOP' },
|
||||||
|
{ participantId: 2, teamId: 100, teamPosition: 'MIDDLE' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayloadWithFrames([
|
||||||
|
{
|
||||||
|
timestamp: 8 * 60_000,
|
||||||
|
participantFrames: {
|
||||||
|
'1': { position: { x: 8_000, y: 7_000 } },
|
||||||
|
'2': { position: { x: -1, y: 7_500 } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
rawMatch,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.roamFrames).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('builds weighted advantage events for kills, plates, towers, and objectives', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 10_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
assistingParticipantIds: [2],
|
||||||
|
victimDamageReceived: [{ participantId: 3, magicDamageDone: 80 }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'TURRET_PLATE_DESTROYED',
|
||||||
|
timestamp: 20_000,
|
||||||
|
killerId: 0,
|
||||||
|
teamId: 200,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'BUILDING_KILL',
|
||||||
|
timestamp: 30_000,
|
||||||
|
killerId: 2,
|
||||||
|
assistingParticipantIds: [3, 4],
|
||||||
|
buildingType: 'TOWER_BUILDING',
|
||||||
|
teamId: 200,
|
||||||
|
towerType: 'OUTER_TURRET',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'ELITE_MONSTER_KILL',
|
||||||
|
timestamp: 40_000,
|
||||||
|
killerId: 3,
|
||||||
|
killerTeamId: 100,
|
||||||
|
monsterType: 'RIFTHERALD',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'ELITE_MONSTER_KILL',
|
||||||
|
timestamp: 50_000,
|
||||||
|
killerId: 8,
|
||||||
|
killerTeamId: 200,
|
||||||
|
monsterType: 'BARON_NASHOR',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.advantageEvents).toEqual([
|
||||||
|
{
|
||||||
|
timestampMs: 10_000,
|
||||||
|
teamId: 100,
|
||||||
|
type: 'championKill',
|
||||||
|
score: 1,
|
||||||
|
participantIds: [1, 2, 3],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestampMs: 20_000,
|
||||||
|
teamId: 100,
|
||||||
|
type: 'turretPlate',
|
||||||
|
score: 0.5,
|
||||||
|
participantIds: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestampMs: 30_000,
|
||||||
|
teamId: 100,
|
||||||
|
type: 'tower',
|
||||||
|
score: 1.5,
|
||||||
|
participantIds: [2, 3, 4],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestampMs: 40_000,
|
||||||
|
teamId: 100,
|
||||||
|
type: 'riftHerald',
|
||||||
|
score: 1.5,
|
||||||
|
participantIds: [3],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestampMs: 50_000,
|
||||||
|
teamId: 200,
|
||||||
|
type: 'baron',
|
||||||
|
score: 3,
|
||||||
|
participantIds: [8],
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits advantage events when the scoring team cannot be inferred', () => {
|
||||||
|
const derived = service.buildDerivedData(
|
||||||
|
createTimelinePayload([
|
||||||
|
[
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 10_000,
|
||||||
|
killerId: 0,
|
||||||
|
victimId: 6,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'TURRET_PLATE_DESTROYED',
|
||||||
|
timestamp: 20_000,
|
||||||
|
killerId: 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'BUILDING_KILL',
|
||||||
|
timestamp: 30_000,
|
||||||
|
buildingType: 'TOWER_BUILDING',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'ELITE_MONSTER_KILL',
|
||||||
|
timestamp: 40_000,
|
||||||
|
killerId: 0,
|
||||||
|
monsterType: 'DRAGON',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(derived.advantageEvents).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,957 @@
|
|||||||
|
import {
|
||||||
|
ADVANTAGE_EVENT_WEIGHTS,
|
||||||
|
SUMMONERS_RIFT_MAP,
|
||||||
|
type AdvantageEventType,
|
||||||
|
type SummonersRiftMapZone,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
|
import { Injectable } from '@nestjs/common';
|
||||||
|
|
||||||
|
interface TimelinePosition {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimelineChampionKillEvent {
|
||||||
|
timestamp: number;
|
||||||
|
killerId?: number;
|
||||||
|
victimId?: number;
|
||||||
|
shutdownBounty?: number;
|
||||||
|
assistingParticipantIds: number[];
|
||||||
|
position?: TimelinePosition;
|
||||||
|
victimDamageReceived: Array<{
|
||||||
|
participantId: number;
|
||||||
|
damage: number;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimelineEliteMonsterKillEvent {
|
||||||
|
timestamp: number;
|
||||||
|
killerParticipantId?: number;
|
||||||
|
killerTeamId?: number;
|
||||||
|
monsterType?: string;
|
||||||
|
monsterSubType?: string;
|
||||||
|
position?: TimelinePosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimelineFrameSnapshot {
|
||||||
|
timestamp: number;
|
||||||
|
participantPositions: Map<number, TimelinePosition>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TimelineRoamParticipant {
|
||||||
|
participantId: number;
|
||||||
|
teamId: 100 | 200;
|
||||||
|
assignedLaneZone: SummonersRiftMapZone;
|
||||||
|
baseZone: SummonersRiftMapZone;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TimelineFightCluster {
|
||||||
|
startTimeMs: number;
|
||||||
|
endTimeMs: number;
|
||||||
|
killCount: number;
|
||||||
|
participantIds: number[];
|
||||||
|
openerParticipantIds: number[];
|
||||||
|
cleanupParticipantIds: number[];
|
||||||
|
isTeamfight: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TimelineObjectiveWindow {
|
||||||
|
objectiveTimeMs: number;
|
||||||
|
startTimeMs: number;
|
||||||
|
endTimeMs: number;
|
||||||
|
killerParticipantId?: number;
|
||||||
|
killerTeamId?: number;
|
||||||
|
monsterType?: string;
|
||||||
|
monsterSubType?: string;
|
||||||
|
position?: TimelinePosition;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TimelineAdvantageEvent {
|
||||||
|
timestampMs: number;
|
||||||
|
teamId: number;
|
||||||
|
type: AdvantageEventType;
|
||||||
|
score: number;
|
||||||
|
participantIds: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TimelineDeathEvent {
|
||||||
|
t: number;
|
||||||
|
victimParticipantId: number;
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
zone: SummonersRiftMapZone;
|
||||||
|
shutdownBountyGiven: number;
|
||||||
|
nearestAllyDistanceApprox: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TimelineRoamFrame {
|
||||||
|
t: number;
|
||||||
|
participantId: number;
|
||||||
|
teamId: number;
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
zone: SummonersRiftMapZone;
|
||||||
|
assignedLaneZone: SummonersRiftMapZone;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TimelineDerivedData {
|
||||||
|
fightClusters: TimelineFightCluster[];
|
||||||
|
advantageEvents: TimelineAdvantageEvent[];
|
||||||
|
deathEvents: TimelineDeathEvent[];
|
||||||
|
objectiveWindows: TimelineObjectiveWindow[];
|
||||||
|
roamFrames: TimelineRoamFrame[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const FIGHT_CLUSTER_MAX_GAP_MS = 15_000;
|
||||||
|
const FIGHT_CLUSTER_MAX_DISTANCE = 3_000;
|
||||||
|
const CLEANUP_WINDOW_MS = 5_000;
|
||||||
|
const OBJECTIVE_WINDOW_BEFORE_MS = 120_000;
|
||||||
|
const OBJECTIVE_WINDOW_AFTER_MS = 30_000;
|
||||||
|
const ROAM_FRAME_START_MS = 8 * 60_000;
|
||||||
|
const ROAM_FRAME_END_MS = 14 * 60_000;
|
||||||
|
const OBJECTIVE_MONSTER_TYPES = new Set([
|
||||||
|
'DRAGON',
|
||||||
|
'RIFTHERALD',
|
||||||
|
'BARON_NASHOR',
|
||||||
|
]);
|
||||||
|
|
||||||
|
function asRecord(value: unknown): Record<string, unknown> {
|
||||||
|
if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
|
||||||
|
return value as Record<string, unknown>;
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function asArray(value: unknown): unknown[] {
|
||||||
|
return Array.isArray(value) ? value : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
function asNumber(value: unknown): number | undefined {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value)
|
||||||
|
? value
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asString(value: unknown): string | undefined {
|
||||||
|
return typeof value === 'string' ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function asParticipantId(value: unknown): number | undefined {
|
||||||
|
const participantId = asNumber(value);
|
||||||
|
return participantId !== undefined && participantId > 0
|
||||||
|
? participantId
|
||||||
|
: undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toSortedIds(values: Iterable<number>): number[] {
|
||||||
|
return [...new Set(values)].sort((left, right) => left - right);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parsePosition(value: unknown): TimelinePosition | undefined {
|
||||||
|
const position = asRecord(value);
|
||||||
|
const x = asNumber(position.x);
|
||||||
|
const y = asNumber(position.y);
|
||||||
|
if (x === undefined || y === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return { x, y };
|
||||||
|
}
|
||||||
|
|
||||||
|
function distance(
|
||||||
|
left: TimelinePosition | undefined,
|
||||||
|
right: TimelinePosition | undefined,
|
||||||
|
): number {
|
||||||
|
if (!left || !right) {
|
||||||
|
return Number.POSITIVE_INFINITY;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.hypot(left.x - right.x, left.y - right.y);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isWithinRadius(
|
||||||
|
position: TimelinePosition,
|
||||||
|
center: TimelinePosition,
|
||||||
|
radius: number,
|
||||||
|
): boolean {
|
||||||
|
return distance(position, center) <= radius;
|
||||||
|
}
|
||||||
|
|
||||||
|
function classifySummonersRiftPosition(
|
||||||
|
position: TimelinePosition | undefined,
|
||||||
|
): SummonersRiftMapZone {
|
||||||
|
if (!position) {
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
baronPit,
|
||||||
|
baseRadius,
|
||||||
|
coordinateMax,
|
||||||
|
coordinateMin,
|
||||||
|
dragonPit,
|
||||||
|
jungleMidline,
|
||||||
|
laneAxisHalfWidth,
|
||||||
|
objectivePitRadius,
|
||||||
|
riverBandHalfWidth,
|
||||||
|
} = SUMMONERS_RIFT_MAP;
|
||||||
|
const { x, y } = position;
|
||||||
|
|
||||||
|
if (
|
||||||
|
x < coordinateMin ||
|
||||||
|
y < coordinateMin ||
|
||||||
|
x > coordinateMax ||
|
||||||
|
y > coordinateMax
|
||||||
|
) {
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
if (isWithinRadius(position, dragonPit, objectivePitRadius)) {
|
||||||
|
return 'dragonPit';
|
||||||
|
}
|
||||||
|
if (isWithinRadius(position, baronPit, objectivePitRadius)) {
|
||||||
|
return 'baronPit';
|
||||||
|
}
|
||||||
|
if (x <= baseRadius && y <= baseRadius) {
|
||||||
|
return 'blueBase';
|
||||||
|
}
|
||||||
|
if (x >= coordinateMax - baseRadius && y >= coordinateMax - baseRadius) {
|
||||||
|
return 'redBase';
|
||||||
|
}
|
||||||
|
if (Math.abs(x + y - coordinateMax) <= riverBandHalfWidth) {
|
||||||
|
return 'river';
|
||||||
|
}
|
||||||
|
if (x <= laneAxisHalfWidth || y >= coordinateMax - laneAxisHalfWidth) {
|
||||||
|
return 'topLane';
|
||||||
|
}
|
||||||
|
if (Math.abs(x - y) <= laneAxisHalfWidth) {
|
||||||
|
return 'middleLane';
|
||||||
|
}
|
||||||
|
if (y <= laneAxisHalfWidth || x >= coordinateMax - laneAxisHalfWidth) {
|
||||||
|
return 'bottomLane';
|
||||||
|
}
|
||||||
|
if (x < jungleMidline && y >= jungleMidline) {
|
||||||
|
return 'northWestJungle';
|
||||||
|
}
|
||||||
|
if (x >= jungleMidline && y >= jungleMidline) {
|
||||||
|
return 'northEastJungle';
|
||||||
|
}
|
||||||
|
if (x < jungleMidline && y < jungleMidline) {
|
||||||
|
return 'southWestJungle';
|
||||||
|
}
|
||||||
|
if (x >= jungleMidline && y < jungleMidline) {
|
||||||
|
return 'southEastJungle';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'unknown';
|
||||||
|
}
|
||||||
|
|
||||||
|
function isConnectedKill(
|
||||||
|
left: TimelineChampionKillEvent,
|
||||||
|
right: TimelineChampionKillEvent,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
Math.abs(left.timestamp - right.timestamp) <= FIGHT_CLUSTER_MAX_GAP_MS &&
|
||||||
|
distance(left.position, right.position) <= FIGHT_CLUSTER_MAX_DISTANCE
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function eventParticipantIds(event: TimelineChampionKillEvent): number[] {
|
||||||
|
return toSortedIds(
|
||||||
|
[
|
||||||
|
event.killerId,
|
||||||
|
event.victimId,
|
||||||
|
...event.assistingParticipantIds,
|
||||||
|
...event.victimDamageReceived.map((damage) => damage.participantId),
|
||||||
|
].filter((id): id is number => id !== undefined),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function eventOpenerParticipantIds(event: TimelineChampionKillEvent): number[] {
|
||||||
|
const damageByParticipantId = new Map<number, number>();
|
||||||
|
for (const damage of event.victimDamageReceived) {
|
||||||
|
damageByParticipantId.set(
|
||||||
|
damage.participantId,
|
||||||
|
(damageByParticipantId.get(damage.participantId) ?? 0) + damage.damage,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const highestDamageContributor = [...damageByParticipantId.entries()].reduce<
|
||||||
|
{ participantId: number; damage: number } | undefined
|
||||||
|
>((selected, [participantId, damage]) => {
|
||||||
|
if (!selected || damage > selected.damage) {
|
||||||
|
return { participantId, damage };
|
||||||
|
}
|
||||||
|
return selected;
|
||||||
|
}, undefined);
|
||||||
|
|
||||||
|
return toSortedIds(
|
||||||
|
[
|
||||||
|
event.killerId,
|
||||||
|
...event.assistingParticipantIds,
|
||||||
|
highestDamageContributor?.participantId,
|
||||||
|
].filter((id): id is number => id !== undefined),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isObjectiveMonsterType(monsterType: string | undefined): boolean {
|
||||||
|
return monsterType !== undefined && OBJECTIVE_MONSTER_TYPES.has(monsterType);
|
||||||
|
}
|
||||||
|
|
||||||
|
function objectiveAdvantageEventType(
|
||||||
|
monsterType: string | undefined,
|
||||||
|
): AdvantageEventType | undefined {
|
||||||
|
switch (monsterType) {
|
||||||
|
case 'DRAGON':
|
||||||
|
return 'dragon';
|
||||||
|
case 'RIFTHERALD':
|
||||||
|
return 'riftHerald';
|
||||||
|
case 'BARON_NASHOR':
|
||||||
|
return 'baron';
|
||||||
|
default:
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function teamIdFromParticipantId(
|
||||||
|
participantId: number | undefined,
|
||||||
|
): 100 | 200 | undefined {
|
||||||
|
if (participantId === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
if (participantId >= 1 && participantId <= 5) {
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
if (participantId >= 6 && participantId <= 10) {
|
||||||
|
return 200;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function toTeamId(value: unknown): 100 | 200 | undefined {
|
||||||
|
const teamId = asNumber(value);
|
||||||
|
return teamId === 100 || teamId === 200 ? teamId : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function opposingTeamId(teamId: 100 | 200 | undefined): 100 | 200 | undefined {
|
||||||
|
if (teamId === 100) {
|
||||||
|
return 200;
|
||||||
|
}
|
||||||
|
if (teamId === 200) {
|
||||||
|
return 100;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function assignedLaneZoneForRole(
|
||||||
|
teamPosition: string | undefined,
|
||||||
|
): SummonersRiftMapZone | undefined {
|
||||||
|
switch (teamPosition) {
|
||||||
|
case 'TOP':
|
||||||
|
return 'topLane';
|
||||||
|
case 'MIDDLE':
|
||||||
|
return 'middleLane';
|
||||||
|
case 'BOTTOM':
|
||||||
|
case 'UTILITY':
|
||||||
|
return 'bottomLane';
|
||||||
|
default:
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function baseZoneForTeamId(
|
||||||
|
teamId: 100 | 200 | undefined,
|
||||||
|
): SummonersRiftMapZone | undefined {
|
||||||
|
switch (teamId) {
|
||||||
|
case 100:
|
||||||
|
return 'blueBase';
|
||||||
|
case 200:
|
||||||
|
return 'redBase';
|
||||||
|
default:
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseRoamParticipants(
|
||||||
|
rawMatch: Record<string, unknown> | undefined,
|
||||||
|
): TimelineRoamParticipant[] {
|
||||||
|
const info = asRecord(rawMatch?.info);
|
||||||
|
return asArray(info.participants)
|
||||||
|
.map(asRecord)
|
||||||
|
.flatMap((participant) => {
|
||||||
|
const participantId = asParticipantId(participant.participantId);
|
||||||
|
const teamId = toTeamId(participant.teamId);
|
||||||
|
const assignedLaneZone = assignedLaneZoneForRole(
|
||||||
|
asString(participant.teamPosition),
|
||||||
|
);
|
||||||
|
const baseZone = baseZoneForTeamId(teamId);
|
||||||
|
if (
|
||||||
|
participantId === undefined ||
|
||||||
|
teamId === undefined ||
|
||||||
|
assignedLaneZone === undefined ||
|
||||||
|
baseZone === undefined
|
||||||
|
) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
participantId,
|
||||||
|
teamId,
|
||||||
|
assignedLaneZone,
|
||||||
|
baseZone,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function scoringParticipantIds(event: TimelineChampionKillEvent): number[] {
|
||||||
|
return toSortedIds(
|
||||||
|
[
|
||||||
|
event.killerId,
|
||||||
|
...event.assistingParticipantIds,
|
||||||
|
...event.victimDamageReceived.map((damage) => damage.participantId),
|
||||||
|
].filter((id): id is number => id !== undefined),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseAssistingParticipantIds(value: unknown): number[] {
|
||||||
|
return toSortedIds(
|
||||||
|
asArray(value).flatMap((item) => {
|
||||||
|
const participantId = asParticipantId(item);
|
||||||
|
return participantId === undefined ? [] : [participantId];
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseVictimDamageReceived(
|
||||||
|
value: unknown,
|
||||||
|
): TimelineChampionKillEvent['victimDamageReceived'] {
|
||||||
|
return asArray(value).flatMap((item) => {
|
||||||
|
const damageRecord = asRecord(item);
|
||||||
|
const participantId = asParticipantId(damageRecord.participantId);
|
||||||
|
if (participantId === undefined) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
const explicitDamage =
|
||||||
|
asNumber(damageRecord.totalDamageDone) ?? asNumber(damageRecord.damage);
|
||||||
|
const componentDamage =
|
||||||
|
(asNumber(damageRecord.magicDamageDone) ?? 0) +
|
||||||
|
(asNumber(damageRecord.physicalDamageDone) ?? 0) +
|
||||||
|
(asNumber(damageRecord.trueDamageDone) ?? 0);
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
participantId,
|
||||||
|
damage: explicitDamage ?? componentDamage,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseChampionKillEvent(
|
||||||
|
event: Record<string, unknown>,
|
||||||
|
): TimelineChampionKillEvent | undefined {
|
||||||
|
const timestamp = asNumber(event.timestamp);
|
||||||
|
if (timestamp === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
timestamp,
|
||||||
|
killerId: asParticipantId(event.killerId),
|
||||||
|
victimId: asParticipantId(event.victimId),
|
||||||
|
shutdownBounty: asNumber(event.shutdownBounty),
|
||||||
|
assistingParticipantIds: parseAssistingParticipantIds(
|
||||||
|
event.assistingParticipantIds,
|
||||||
|
),
|
||||||
|
position: parsePosition(event.position),
|
||||||
|
victimDamageReceived: parseVictimDamageReceived(event.victimDamageReceived),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTimelineFrame(
|
||||||
|
frame: Record<string, unknown>,
|
||||||
|
): TimelineFrameSnapshot | undefined {
|
||||||
|
const timestamp = asNumber(frame.timestamp);
|
||||||
|
if (timestamp === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const participantFrames = asRecord(frame.participantFrames);
|
||||||
|
const participantPositions = new Map<number, TimelinePosition>();
|
||||||
|
for (const [participantIdValue, participantFrameValue] of Object.entries(
|
||||||
|
participantFrames,
|
||||||
|
)) {
|
||||||
|
const participantId = asParticipantId(Number(participantIdValue));
|
||||||
|
const participantFrame = asRecord(participantFrameValue);
|
||||||
|
const position = parsePosition(participantFrame.position);
|
||||||
|
if (participantId !== undefined && position) {
|
||||||
|
participantPositions.set(participantId, position);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
timestamp,
|
||||||
|
participantPositions,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseEliteMonsterKillEvent(
|
||||||
|
event: Record<string, unknown>,
|
||||||
|
): TimelineEliteMonsterKillEvent | undefined {
|
||||||
|
const timestamp = asNumber(event.timestamp);
|
||||||
|
if (timestamp === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
timestamp,
|
||||||
|
killerParticipantId: asParticipantId(event.killerId),
|
||||||
|
killerTeamId: asNumber(event.killerTeamId),
|
||||||
|
monsterType: asString(event.monsterType),
|
||||||
|
monsterSubType: asString(event.monsterSubType),
|
||||||
|
position: parsePosition(event.position),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function structureParticipantIds(event: Record<string, unknown>): number[] {
|
||||||
|
return toSortedIds(
|
||||||
|
[
|
||||||
|
asParticipantId(event.killerId),
|
||||||
|
...parseAssistingParticipantIds(event.assistingParticipantIds),
|
||||||
|
].filter((id): id is number => id !== undefined),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function createStructureAdvantageEvent(
|
||||||
|
event: Record<string, unknown>,
|
||||||
|
type: AdvantageEventType,
|
||||||
|
): TimelineAdvantageEvent | undefined {
|
||||||
|
const timestamp = asNumber(event.timestamp);
|
||||||
|
const participantIds = structureParticipantIds(event);
|
||||||
|
const teamId =
|
||||||
|
teamIdFromParticipantId(participantIds[0]) ??
|
||||||
|
opposingTeamId(toTeamId(event.teamId));
|
||||||
|
if (timestamp === undefined || !teamId) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
timestampMs: timestamp,
|
||||||
|
teamId,
|
||||||
|
type,
|
||||||
|
score: ADVANTAGE_EVENT_WEIGHTS[type],
|
||||||
|
participantIds,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createChampionKillAdvantageEvent(
|
||||||
|
event: TimelineChampionKillEvent,
|
||||||
|
): TimelineAdvantageEvent | undefined {
|
||||||
|
const teamId = teamIdFromParticipantId(event.killerId);
|
||||||
|
if (event.killerId === undefined || !teamId) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
timestampMs: event.timestamp,
|
||||||
|
teamId,
|
||||||
|
type: 'championKill',
|
||||||
|
score: ADVANTAGE_EVENT_WEIGHTS.championKill,
|
||||||
|
participantIds: scoringParticipantIds(event),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createEliteMonsterAdvantageEvent(
|
||||||
|
event: TimelineEliteMonsterKillEvent,
|
||||||
|
): TimelineAdvantageEvent | undefined {
|
||||||
|
const type = objectiveAdvantageEventType(event.monsterType);
|
||||||
|
if (!type) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const teamId =
|
||||||
|
toTeamId(event.killerTeamId) ??
|
||||||
|
teamIdFromParticipantId(event.killerParticipantId);
|
||||||
|
if (!teamId) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
timestampMs: event.timestamp,
|
||||||
|
teamId,
|
||||||
|
type,
|
||||||
|
score: ADVANTAGE_EVENT_WEIGHTS[type],
|
||||||
|
participantIds:
|
||||||
|
event.killerParticipantId === undefined
|
||||||
|
? []
|
||||||
|
: [event.killerParticipantId],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createBuildingAdvantageEvent(
|
||||||
|
event: Record<string, unknown>,
|
||||||
|
): TimelineAdvantageEvent | undefined {
|
||||||
|
const buildingType = asString(event.buildingType);
|
||||||
|
const towerType = asString(event.towerType);
|
||||||
|
if (buildingType !== 'TOWER_BUILDING' && towerType === undefined) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
return createStructureAdvantageEvent(event, 'tower');
|
||||||
|
}
|
||||||
|
|
||||||
|
function extractTimelineEvents(timeline: Record<string, unknown>) {
|
||||||
|
const info = asRecord(timeline.info);
|
||||||
|
const frames = asArray(info.frames).map(asRecord);
|
||||||
|
const championKills: TimelineChampionKillEvent[] = [];
|
||||||
|
const eliteMonsterKills: TimelineEliteMonsterKillEvent[] = [];
|
||||||
|
const advantageEvents: TimelineAdvantageEvent[] = [];
|
||||||
|
const frameSnapshots: TimelineFrameSnapshot[] = [];
|
||||||
|
|
||||||
|
for (const frame of frames) {
|
||||||
|
const frameSnapshot = parseTimelineFrame(frame);
|
||||||
|
if (frameSnapshot) {
|
||||||
|
frameSnapshots.push(frameSnapshot);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const rawEvent of asArray(frame.events)) {
|
||||||
|
const event = asRecord(rawEvent);
|
||||||
|
switch (asString(event.type)) {
|
||||||
|
case 'CHAMPION_KILL': {
|
||||||
|
const championKill = parseChampionKillEvent(event);
|
||||||
|
if (championKill) {
|
||||||
|
championKills.push(championKill);
|
||||||
|
const advantageEvent =
|
||||||
|
createChampionKillAdvantageEvent(championKill);
|
||||||
|
if (advantageEvent) {
|
||||||
|
advantageEvents.push(advantageEvent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'ELITE_MONSTER_KILL': {
|
||||||
|
const eliteMonsterKill = parseEliteMonsterKillEvent(event);
|
||||||
|
if (eliteMonsterKill) {
|
||||||
|
eliteMonsterKills.push(eliteMonsterKill);
|
||||||
|
const advantageEvent =
|
||||||
|
createEliteMonsterAdvantageEvent(eliteMonsterKill);
|
||||||
|
if (advantageEvent) {
|
||||||
|
advantageEvents.push(advantageEvent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'TURRET_PLATE_DESTROYED': {
|
||||||
|
const advantageEvent = createStructureAdvantageEvent(
|
||||||
|
event,
|
||||||
|
'turretPlate',
|
||||||
|
);
|
||||||
|
if (advantageEvent) {
|
||||||
|
advantageEvents.push(advantageEvent);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case 'BUILDING_KILL': {
|
||||||
|
const advantageEvent = createBuildingAdvantageEvent(event);
|
||||||
|
if (advantageEvent) {
|
||||||
|
advantageEvents.push(advantageEvent);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
championKills: championKills.sort(
|
||||||
|
(left, right) => left.timestamp - right.timestamp,
|
||||||
|
),
|
||||||
|
eliteMonsterKills: eliteMonsterKills.sort(
|
||||||
|
(left, right) => left.timestamp - right.timestamp,
|
||||||
|
),
|
||||||
|
advantageEvents: advantageEvents.sort(
|
||||||
|
(left, right) => left.timestampMs - right.timestampMs,
|
||||||
|
),
|
||||||
|
frameSnapshots: frameSnapshots.sort(
|
||||||
|
(left, right) => left.timestamp - right.timestamp,
|
||||||
|
),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function findRoot(parents: number[], index: number): number {
|
||||||
|
let root = index;
|
||||||
|
while (parents[root] !== root) {
|
||||||
|
root = parents[root];
|
||||||
|
}
|
||||||
|
|
||||||
|
while (parents[index] !== index) {
|
||||||
|
const parent = parents[index];
|
||||||
|
parents[index] = root;
|
||||||
|
index = parent;
|
||||||
|
}
|
||||||
|
|
||||||
|
return root;
|
||||||
|
}
|
||||||
|
|
||||||
|
function union(parents: number[], left: number, right: number): void {
|
||||||
|
const leftRoot = findRoot(parents, left);
|
||||||
|
const rightRoot = findRoot(parents, right);
|
||||||
|
if (leftRoot !== rightRoot) {
|
||||||
|
parents[rightRoot] = leftRoot;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFightClusters(
|
||||||
|
kills: TimelineChampionKillEvent[],
|
||||||
|
): TimelineFightCluster[] {
|
||||||
|
const parents = kills.map((_, index) => index);
|
||||||
|
|
||||||
|
for (let leftIndex = 0; leftIndex < kills.length; leftIndex += 1) {
|
||||||
|
for (
|
||||||
|
let rightIndex = leftIndex + 1;
|
||||||
|
rightIndex < kills.length;
|
||||||
|
rightIndex += 1
|
||||||
|
) {
|
||||||
|
if (isConnectedKill(kills[leftIndex], kills[rightIndex])) {
|
||||||
|
union(parents, leftIndex, rightIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const clusterGroups = new Map<number, TimelineChampionKillEvent[]>();
|
||||||
|
for (const [index, kill] of kills.entries()) {
|
||||||
|
const root = findRoot(parents, index);
|
||||||
|
clusterGroups.set(root, [...(clusterGroups.get(root) ?? []), kill]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...clusterGroups.values()]
|
||||||
|
.map((clusterKills) => {
|
||||||
|
const sortedKills = [...clusterKills].sort(
|
||||||
|
(left, right) => left.timestamp - right.timestamp,
|
||||||
|
);
|
||||||
|
const firstKill = sortedKills[0];
|
||||||
|
const lastKill = sortedKills[sortedKills.length - 1];
|
||||||
|
const cleanupStartTimeMs = lastKill.timestamp - CLEANUP_WINDOW_MS;
|
||||||
|
const cleanupEndTimeMs = lastKill.timestamp + CLEANUP_WINDOW_MS;
|
||||||
|
const cleanupParticipantIds = sortedKills
|
||||||
|
.filter(
|
||||||
|
(kill) =>
|
||||||
|
kill.timestamp >= cleanupStartTimeMs &&
|
||||||
|
kill.timestamp <= cleanupEndTimeMs,
|
||||||
|
)
|
||||||
|
.flatMap(eventParticipantIds);
|
||||||
|
|
||||||
|
return {
|
||||||
|
startTimeMs: firstKill.timestamp,
|
||||||
|
endTimeMs: lastKill.timestamp,
|
||||||
|
killCount: sortedKills.length,
|
||||||
|
participantIds: toSortedIds(sortedKills.flatMap(eventParticipantIds)),
|
||||||
|
openerParticipantIds: eventOpenerParticipantIds(firstKill),
|
||||||
|
cleanupParticipantIds: toSortedIds(cleanupParticipantIds),
|
||||||
|
isTeamfight: sortedKills.length >= 3,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((left, right) => left.startTimeMs - right.startTimeMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildObjectiveWindows(
|
||||||
|
eliteMonsterKills: TimelineEliteMonsterKillEvent[],
|
||||||
|
): TimelineObjectiveWindow[] {
|
||||||
|
return eliteMonsterKills
|
||||||
|
.filter((event) => isObjectiveMonsterType(event.monsterType))
|
||||||
|
.map((event) => ({
|
||||||
|
objectiveTimeMs: event.timestamp,
|
||||||
|
startTimeMs: event.timestamp - OBJECTIVE_WINDOW_BEFORE_MS,
|
||||||
|
endTimeMs: event.timestamp + OBJECTIVE_WINDOW_AFTER_MS,
|
||||||
|
...(event.killerParticipantId !== undefined
|
||||||
|
? { killerParticipantId: event.killerParticipantId }
|
||||||
|
: {}),
|
||||||
|
...(event.killerTeamId !== undefined
|
||||||
|
? { killerTeamId: event.killerTeamId }
|
||||||
|
: {}),
|
||||||
|
...(event.monsterType ? { monsterType: event.monsterType } : {}),
|
||||||
|
...(event.monsterSubType ? { monsterSubType: event.monsterSubType } : {}),
|
||||||
|
...(event.position ? { position: event.position } : {}),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
function interpolatePosition(
|
||||||
|
frameSnapshots: TimelineFrameSnapshot[],
|
||||||
|
participantId: number,
|
||||||
|
timestampMs: number,
|
||||||
|
): TimelinePosition | undefined {
|
||||||
|
let previous: { timestamp: number; position: TimelinePosition } | undefined;
|
||||||
|
let next: { timestamp: number; position: TimelinePosition } | undefined;
|
||||||
|
|
||||||
|
for (const frame of frameSnapshots) {
|
||||||
|
const position = frame.participantPositions.get(participantId);
|
||||||
|
if (!position) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (frame.timestamp <= timestampMs) {
|
||||||
|
previous = { timestamp: frame.timestamp, position };
|
||||||
|
}
|
||||||
|
if (frame.timestamp >= timestampMs) {
|
||||||
|
next = { timestamp: frame.timestamp, position };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (previous && next) {
|
||||||
|
if (previous.timestamp === next.timestamp) {
|
||||||
|
return previous.position;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ratio =
|
||||||
|
(timestampMs - previous.timestamp) /
|
||||||
|
(next.timestamp - previous.timestamp);
|
||||||
|
return {
|
||||||
|
x: previous.position.x + (next.position.x - previous.position.x) * ratio,
|
||||||
|
y: previous.position.y + (next.position.y - previous.position.y) * ratio,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return previous?.position ?? next?.position;
|
||||||
|
}
|
||||||
|
|
||||||
|
function nearestAllyDistanceApprox(
|
||||||
|
frameSnapshots: TimelineFrameSnapshot[],
|
||||||
|
victimParticipantId: number,
|
||||||
|
deathPosition: TimelinePosition,
|
||||||
|
timestampMs: number,
|
||||||
|
): number | null {
|
||||||
|
const victimTeamId = teamIdFromParticipantId(victimParticipantId);
|
||||||
|
if (!victimTeamId) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
let nearestDistance = Number.POSITIVE_INFINITY;
|
||||||
|
for (let participantId = 1; participantId <= 10; participantId += 1) {
|
||||||
|
if (
|
||||||
|
participantId === victimParticipantId ||
|
||||||
|
teamIdFromParticipantId(participantId) !== victimTeamId
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const allyPosition = interpolatePosition(
|
||||||
|
frameSnapshots,
|
||||||
|
participantId,
|
||||||
|
timestampMs,
|
||||||
|
);
|
||||||
|
if (!allyPosition) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
nearestDistance = Math.min(
|
||||||
|
nearestDistance,
|
||||||
|
distance(deathPosition, allyPosition),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Number.isFinite(nearestDistance) ? Math.round(nearestDistance) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildDeathEvents(
|
||||||
|
championKills: TimelineChampionKillEvent[],
|
||||||
|
frameSnapshots: TimelineFrameSnapshot[],
|
||||||
|
): TimelineDeathEvent[] {
|
||||||
|
return championKills.flatMap((event) => {
|
||||||
|
if (event.victimId === undefined) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const position =
|
||||||
|
event.position ??
|
||||||
|
interpolatePosition(frameSnapshots, event.victimId, event.timestamp);
|
||||||
|
if (!position) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
t: event.timestamp,
|
||||||
|
victimParticipantId: event.victimId,
|
||||||
|
x: position.x,
|
||||||
|
y: position.y,
|
||||||
|
zone: classifySummonersRiftPosition(position),
|
||||||
|
shutdownBountyGiven: event.shutdownBounty ?? 0,
|
||||||
|
nearestAllyDistanceApprox: nearestAllyDistanceApprox(
|
||||||
|
frameSnapshots,
|
||||||
|
event.victimId,
|
||||||
|
position,
|
||||||
|
event.timestamp,
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildRoamFrames(
|
||||||
|
frameSnapshots: TimelineFrameSnapshot[],
|
||||||
|
rawMatch: Record<string, unknown> | undefined,
|
||||||
|
): TimelineRoamFrame[] {
|
||||||
|
const roamParticipants = parseRoamParticipants(rawMatch);
|
||||||
|
if (roamParticipants.length === 0) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return frameSnapshots.flatMap((frame) => {
|
||||||
|
if (
|
||||||
|
frame.timestamp < ROAM_FRAME_START_MS ||
|
||||||
|
frame.timestamp > ROAM_FRAME_END_MS
|
||||||
|
) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return roamParticipants.flatMap((participant) => {
|
||||||
|
const position = frame.participantPositions.get(
|
||||||
|
participant.participantId,
|
||||||
|
);
|
||||||
|
if (!position) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const zone = classifySummonersRiftPosition(position);
|
||||||
|
if (
|
||||||
|
zone === 'unknown' ||
|
||||||
|
zone === participant.assignedLaneZone ||
|
||||||
|
zone === participant.baseZone
|
||||||
|
) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
t: frame.timestamp,
|
||||||
|
participantId: participant.participantId,
|
||||||
|
teamId: participant.teamId,
|
||||||
|
x: position.x,
|
||||||
|
y: position.y,
|
||||||
|
zone,
|
||||||
|
assignedLaneZone: participant.assignedLaneZone,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class TimelineDerivedService {
|
||||||
|
public buildDerivedData(
|
||||||
|
timeline: Record<string, unknown>,
|
||||||
|
rawMatch?: Record<string, unknown>,
|
||||||
|
): TimelineDerivedData {
|
||||||
|
const {
|
||||||
|
advantageEvents,
|
||||||
|
championKills,
|
||||||
|
eliteMonsterKills,
|
||||||
|
frameSnapshots,
|
||||||
|
} = extractTimelineEvents(timeline);
|
||||||
|
|
||||||
|
return {
|
||||||
|
fightClusters: buildFightClusters(championKills),
|
||||||
|
advantageEvents,
|
||||||
|
deathEvents: buildDeathEvents(championKills, frameSnapshots),
|
||||||
|
objectiveWindows: buildObjectiveWindows(eliteMonsterKills),
|
||||||
|
roamFrames: buildRoamFrames(frameSnapshots, rawMatch),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,718 @@
|
|||||||
|
import { VECTOR_METRICS } from '@persona-lenz/shared';
|
||||||
|
import type { ExtractedPlayerMatchFeature } from './analysis.types';
|
||||||
|
import { TimelineMetricService } from './timeline-metric.service';
|
||||||
|
|
||||||
|
function createBaseFeature(): ExtractedPlayerMatchFeature {
|
||||||
|
return {
|
||||||
|
matchId: 'KR_1',
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
role: 'MIDDLE',
|
||||||
|
championId: 103,
|
||||||
|
gameCreation: 1_700_000_000_000,
|
||||||
|
gameDurationSec: 1_800,
|
||||||
|
win: true,
|
||||||
|
patch: '26.13',
|
||||||
|
features: {
|
||||||
|
kda: 3,
|
||||||
|
},
|
||||||
|
normalized: {
|
||||||
|
kda: 0.5,
|
||||||
|
},
|
||||||
|
vector: [],
|
||||||
|
featureSchemaVersion: 2,
|
||||||
|
normalizationMethod: 'registry-baseline',
|
||||||
|
confidence: 1,
|
||||||
|
timelineProcessed: false,
|
||||||
|
laneOpponent: {
|
||||||
|
puuid: 'enemy-mid-puuid',
|
||||||
|
championId: 134,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createRawMatch() {
|
||||||
|
return {
|
||||||
|
metadata: {
|
||||||
|
matchId: 'KR_1',
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
participants: [
|
||||||
|
{
|
||||||
|
participantId: 1,
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: 'MIDDLE',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
participantId: 2,
|
||||||
|
puuid: 'ally-jungle-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: 'JUNGLE',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
participantId: 3,
|
||||||
|
puuid: 'ally-top-puuid',
|
||||||
|
teamId: 100,
|
||||||
|
teamPosition: 'TOP',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
participantId: 6,
|
||||||
|
puuid: 'enemy-mid-puuid',
|
||||||
|
teamId: 200,
|
||||||
|
teamPosition: 'MIDDLE',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
participantId: 7,
|
||||||
|
puuid: 'enemy-jungle-puuid',
|
||||||
|
teamId: 200,
|
||||||
|
teamPosition: 'JUNGLE',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function participantFrame(overrides: Record<string, unknown>) {
|
||||||
|
return {
|
||||||
|
jungleMinionsKilled: 0,
|
||||||
|
minionsKilled: 0,
|
||||||
|
position: { x: 0, y: 0 },
|
||||||
|
timeEnemySpentControlled: 0,
|
||||||
|
totalGold: 0,
|
||||||
|
xp: 0,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createTimeline() {
|
||||||
|
return {
|
||||||
|
info: {
|
||||||
|
frames: [
|
||||||
|
{
|
||||||
|
timestamp: 8 * 60_000,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({ position: { x: 4_000, y: 4_000 } }),
|
||||||
|
'2': participantFrame({ position: { x: 5_000, y: 4_000 } }),
|
||||||
|
'3': participantFrame({ position: { x: 10_000, y: 4_000 } }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 10 * 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 100_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
assistingParticipantIds: [2],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 200_000,
|
||||||
|
killerId: 2,
|
||||||
|
victimId: 7,
|
||||||
|
assistingParticipantIds: [1],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 300_000,
|
||||||
|
killerId: 2,
|
||||||
|
victimId: 7,
|
||||||
|
assistingParticipantIds: null,
|
||||||
|
victimDamageReceived: [{ participantId: 1 }],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 400_000,
|
||||||
|
killerId: 6,
|
||||||
|
victimId: 1,
|
||||||
|
assistingParticipantIds: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'WARD_PLACED',
|
||||||
|
timestamp: 500_000,
|
||||||
|
creatorId: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({
|
||||||
|
jungleMinionsKilled: 5,
|
||||||
|
minionsKilled: 75,
|
||||||
|
position: { x: 4_000, y: 4_000 },
|
||||||
|
timeEnemySpentControlled: 10_000,
|
||||||
|
totalGold: 4_000,
|
||||||
|
xp: 5_000,
|
||||||
|
}),
|
||||||
|
'2': participantFrame({ position: { x: 4_800, y: 4_000 } }),
|
||||||
|
'3': participantFrame({ position: { x: 9_000, y: 4_000 } }),
|
||||||
|
'6': participantFrame({
|
||||||
|
jungleMinionsKilled: 0,
|
||||||
|
minionsKilled: 70,
|
||||||
|
totalGold: 3_500,
|
||||||
|
xp: 4_500,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 14 * 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'WARD_PLACED',
|
||||||
|
timestamp: 830_000,
|
||||||
|
creatorId: 1,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({
|
||||||
|
position: { x: 4_000, y: 4_000 },
|
||||||
|
timeEnemySpentControlled: 30_000,
|
||||||
|
totalGold: 6_000,
|
||||||
|
}),
|
||||||
|
'2': participantFrame({ position: { x: 5_500, y: 4_000 } }),
|
||||||
|
'3': participantFrame({ position: { x: 11_000, y: 4_000 } }),
|
||||||
|
'6': participantFrame({
|
||||||
|
totalGold: 6_200,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 15 * 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'WARD_PLACED',
|
||||||
|
timestamp: 850_000,
|
||||||
|
creatorId: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'ELITE_MONSTER_KILL',
|
||||||
|
timestamp: 900_000,
|
||||||
|
killerId: 2,
|
||||||
|
killerTeamId: 100,
|
||||||
|
monsterType: 'DRAGON',
|
||||||
|
assistingParticipantIds: [1],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 20 * 60_000,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({
|
||||||
|
position: { x: 4_000, y: 4_000 },
|
||||||
|
timeEnemySpentControlled: 60_000,
|
||||||
|
}),
|
||||||
|
'2': participantFrame({ position: { x: 7_000, y: 4_000 } }),
|
||||||
|
'3': participantFrame({ position: { x: 12_000, y: 4_000 } }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 30 * 60_000,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({
|
||||||
|
timeEnemySpentControlled: 90_000,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createInsightTimeline() {
|
||||||
|
return {
|
||||||
|
info: {
|
||||||
|
frames: [
|
||||||
|
{
|
||||||
|
timestamp: 10 * 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
actualStartTime: 640_000,
|
||||||
|
type: 'OBJECTIVE_BOUNTY_PRESTART',
|
||||||
|
timestamp: 590_000,
|
||||||
|
teamId: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({
|
||||||
|
minionsKilled: 80,
|
||||||
|
position: { x: 7_500, y: 7_500 },
|
||||||
|
totalGold: 4_000,
|
||||||
|
xp: 5_000,
|
||||||
|
}),
|
||||||
|
'6': participantFrame({
|
||||||
|
minionsKilled: 72,
|
||||||
|
totalGold: 3_400,
|
||||||
|
xp: 4_700,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 11 * 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 650_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 6,
|
||||||
|
shutdownBounty: 450,
|
||||||
|
assistingParticipantIds: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({ position: { x: 7_800, y: 9_000 } }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 12 * 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'TURRET_PLATE_DESTROYED',
|
||||||
|
timestamp: 700_000,
|
||||||
|
teamId: 200,
|
||||||
|
laneType: 'MID_LANE',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'OBJECTIVE_BOUNTY_FINISH',
|
||||||
|
timestamp: 700_000,
|
||||||
|
teamId: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({ position: { x: 7_800, y: 7_800 } }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 800_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 800_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 7,
|
||||||
|
assistingParticipantIds: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({ position: { x: 9_866, y: 4_414 } }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 14 * 60_000,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({
|
||||||
|
position: { x: 9_866, y: 4_414 },
|
||||||
|
totalGold: 5_800,
|
||||||
|
}),
|
||||||
|
'2': participantFrame({ position: { x: 8_800, y: 4_600 } }),
|
||||||
|
'3': participantFrame({ position: { x: 1_000, y: 13_000 } }),
|
||||||
|
'6': participantFrame({ totalGold: 5_500 }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 15 * 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'ELITE_MONSTER_KILL',
|
||||||
|
timestamp: 900_000,
|
||||||
|
killerId: 2,
|
||||||
|
killerTeamId: 100,
|
||||||
|
monsterType: 'DRAGON',
|
||||||
|
assistingParticipantIds: [1],
|
||||||
|
position: { x: 9_866, y: 4_414 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({ position: { x: 9_866, y: 4_414 } }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 20 * 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 1_030_000,
|
||||||
|
killerId: 6,
|
||||||
|
victimId: 1,
|
||||||
|
assistingParticipantIds: [],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 1_215_000,
|
||||||
|
killerId: 2,
|
||||||
|
victimId: 7,
|
||||||
|
assistingParticipantIds: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({
|
||||||
|
position: { x: 7_500, y: 7_500 },
|
||||||
|
totalGold: 8_000,
|
||||||
|
}),
|
||||||
|
'6': participantFrame({ totalGold: 7_700 }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createDeficitRecoveryTimeline() {
|
||||||
|
return {
|
||||||
|
info: {
|
||||||
|
frames: [
|
||||||
|
{
|
||||||
|
timestamp: 10 * 60_000,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({
|
||||||
|
minionsKilled: 65,
|
||||||
|
totalGold: 3_200,
|
||||||
|
xp: 4_200,
|
||||||
|
}),
|
||||||
|
'6': participantFrame({
|
||||||
|
minionsKilled: 75,
|
||||||
|
totalGold: 3_900,
|
||||||
|
xp: 4_600,
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 20 * 60_000,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': participantFrame({ totalGold: 7_500 }),
|
||||||
|
'6': participantFrame({ totalGold: 7_300 }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('TimelineMetricService', () => {
|
||||||
|
const service = new TimelineMetricService();
|
||||||
|
|
||||||
|
it('extracts timeline vector metrics and ratio counts', () => {
|
||||||
|
const feature = createBaseFeature();
|
||||||
|
const result = service.extractTimelineMetrics(
|
||||||
|
feature,
|
||||||
|
createRawMatch(),
|
||||||
|
createTimeline(),
|
||||||
|
{
|
||||||
|
advantageEvents: [],
|
||||||
|
deathEvents: [
|
||||||
|
{
|
||||||
|
t: 400_000,
|
||||||
|
victimParticipantId: 1,
|
||||||
|
x: 4_000,
|
||||||
|
y: 4_000,
|
||||||
|
zone: 'middleLane',
|
||||||
|
shutdownBountyGiven: 300,
|
||||||
|
nearestAllyDistanceApprox: 1_500,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
t: 1_000_000,
|
||||||
|
victimParticipantId: 1,
|
||||||
|
x: 4_000,
|
||||||
|
y: 4_000,
|
||||||
|
zone: 'middleLane',
|
||||||
|
shutdownBountyGiven: 0,
|
||||||
|
nearestAllyDistanceApprox: 1_500,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
fightClusters: [
|
||||||
|
{
|
||||||
|
startTimeMs: 100_000,
|
||||||
|
endTimeMs: 130_000,
|
||||||
|
killCount: 3,
|
||||||
|
participantIds: [1, 2, 6, 7],
|
||||||
|
openerParticipantIds: [1],
|
||||||
|
cleanupParticipantIds: [2],
|
||||||
|
isTeamfight: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
startTimeMs: 600_000,
|
||||||
|
endTimeMs: 640_000,
|
||||||
|
killCount: 3,
|
||||||
|
participantIds: [1, 2, 6, 7],
|
||||||
|
openerParticipantIds: [2],
|
||||||
|
cleanupParticipantIds: [1],
|
||||||
|
isTeamfight: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
objectiveWindows: [
|
||||||
|
{
|
||||||
|
objectiveTimeMs: 900_000,
|
||||||
|
startTimeMs: 780_000,
|
||||||
|
endTimeMs: 930_000,
|
||||||
|
killerParticipantId: 2,
|
||||||
|
killerTeamId: 100,
|
||||||
|
monsterType: 'DRAGON',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
roamFrames: [],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.features).toMatchObject({
|
||||||
|
goldDiffAt10: 500,
|
||||||
|
goldDiffAt14: -200,
|
||||||
|
csDiffAt10: 10,
|
||||||
|
xpDiffAt10: 500,
|
||||||
|
deathsBefore14: 1,
|
||||||
|
killParticipationBefore14: 1,
|
||||||
|
earlyWardsPerMin: 2 / 14,
|
||||||
|
objectivePreWardRateNumerator: 1,
|
||||||
|
objectivePreWardRateDenominator: 1,
|
||||||
|
eliteObjectiveParticipationRateNumerator: 1,
|
||||||
|
eliteObjectiveParticipationRateDenominator: 1,
|
||||||
|
teamfightFirstEngagementParticipationRateNumerator: 1,
|
||||||
|
teamfightFirstEngagementParticipationRateDenominator: 2,
|
||||||
|
teamfightCleanupKillParticipationRateNumerator: 1,
|
||||||
|
teamfightCleanupKillParticipationRateDenominator: 2,
|
||||||
|
deathWithShutdownBountyGivenRateNumerator: 1,
|
||||||
|
deathWithShutdownBountyGivenRateDenominator: 2,
|
||||||
|
ccTimePerMinute: 3,
|
||||||
|
});
|
||||||
|
expect(result.features.isolationTendency).toBeCloseTo(
|
||||||
|
(1_000 + 800 + 1_500 + 3_000) / 4,
|
||||||
|
);
|
||||||
|
expect(result.normalized.objectivePreWardRate).toBe(1);
|
||||||
|
expect(result.normalized.eliteObjectiveParticipationRate).toBe(1);
|
||||||
|
expect(result.normalized.teamfightFirstEngagementParticipationRate).toBe(
|
||||||
|
0.5,
|
||||||
|
);
|
||||||
|
expect(result.vector).toHaveLength(VECTOR_METRICS.length);
|
||||||
|
expect(
|
||||||
|
result.vector[
|
||||||
|
VECTOR_METRICS.findIndex((metric) => metric.id === 'goldDiffAt10')
|
||||||
|
],
|
||||||
|
).toBeCloseTo(result.normalized.goldDiffAt10);
|
||||||
|
expect(
|
||||||
|
result.vector[
|
||||||
|
VECTOR_METRICS.findIndex(
|
||||||
|
(metric) => metric.id === 'objectivePreWardRate',
|
||||||
|
)
|
||||||
|
],
|
||||||
|
).toBe(1);
|
||||||
|
expect(
|
||||||
|
result.vector[
|
||||||
|
VECTOR_METRICS.findIndex(
|
||||||
|
(metric) => metric.id === 'deathWithShutdownBountyGivenRate',
|
||||||
|
)
|
||||||
|
],
|
||||||
|
).toBe(0.5);
|
||||||
|
expect(result.vector[VECTOR_METRICS.length - 1]).toBe(
|
||||||
|
result.normalized.ccTimePerMinute,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extracts timeline insight metrics outside the vector', () => {
|
||||||
|
const feature = createBaseFeature();
|
||||||
|
const result = service.extractTimelineMetrics(
|
||||||
|
feature,
|
||||||
|
createRawMatch(),
|
||||||
|
createInsightTimeline(),
|
||||||
|
{
|
||||||
|
advantageEvents: [
|
||||||
|
{
|
||||||
|
timestampMs: 600_000,
|
||||||
|
teamId: 100,
|
||||||
|
type: 'championKill',
|
||||||
|
score: 1,
|
||||||
|
participantIds: [1],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestampMs: 650_000,
|
||||||
|
teamId: 100,
|
||||||
|
type: 'championKill',
|
||||||
|
score: 1,
|
||||||
|
participantIds: [1],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestampMs: 1_030_000,
|
||||||
|
teamId: 200,
|
||||||
|
type: 'championKill',
|
||||||
|
score: 1,
|
||||||
|
participantIds: [6],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestampMs: 1_215_000,
|
||||||
|
teamId: 100,
|
||||||
|
type: 'championKill',
|
||||||
|
score: 1,
|
||||||
|
participantIds: [2],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
deathEvents: [
|
||||||
|
{
|
||||||
|
t: 1_000_000,
|
||||||
|
victimParticipantId: 1,
|
||||||
|
x: 7_500,
|
||||||
|
y: 7_500,
|
||||||
|
zone: 'middleLane',
|
||||||
|
shutdownBountyGiven: 0,
|
||||||
|
nearestAllyDistanceApprox: 5_000,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
t: 1_200_000,
|
||||||
|
victimParticipantId: 1,
|
||||||
|
x: 7_500,
|
||||||
|
y: 7_500,
|
||||||
|
zone: 'middleLane',
|
||||||
|
shutdownBountyGiven: 0,
|
||||||
|
nearestAllyDistanceApprox: 1_000,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
fightClusters: [
|
||||||
|
{
|
||||||
|
startTimeMs: 850_000,
|
||||||
|
endTimeMs: 870_000,
|
||||||
|
killCount: 2,
|
||||||
|
participantIds: [1, 2, 6, 7],
|
||||||
|
openerParticipantIds: [1],
|
||||||
|
cleanupParticipantIds: [2],
|
||||||
|
isTeamfight: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
objectiveWindows: [
|
||||||
|
{
|
||||||
|
objectiveTimeMs: 900_000,
|
||||||
|
startTimeMs: 780_000,
|
||||||
|
endTimeMs: 930_000,
|
||||||
|
killerParticipantId: 2,
|
||||||
|
killerTeamId: 100,
|
||||||
|
monsterType: 'DRAGON',
|
||||||
|
position: { x: 9_866, y: 4_414 },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
roamFrames: [
|
||||||
|
{
|
||||||
|
t: 600_000,
|
||||||
|
participantId: 1,
|
||||||
|
teamId: 100,
|
||||||
|
x: 7_500,
|
||||||
|
y: 7_500,
|
||||||
|
zone: 'river',
|
||||||
|
assignedLaneZone: 'middleLane',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
t: 660_000,
|
||||||
|
participantId: 1,
|
||||||
|
teamId: 100,
|
||||||
|
x: 8_000,
|
||||||
|
y: 7_000,
|
||||||
|
zone: 'river',
|
||||||
|
assignedLaneZone: 'middleLane',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.features).toMatchObject({
|
||||||
|
objectiveFightOpeningParticipationRateNumerator: 1,
|
||||||
|
objectiveFightOpeningParticipationRateDenominator: 1,
|
||||||
|
objectiveFightOpeningConvertedToObjectiveRateNumerator: 1,
|
||||||
|
objectiveFightOpeningConvertedToObjectiveRateDenominator: 1,
|
||||||
|
preObjectivePitPresenceRateNumerator: 1,
|
||||||
|
preObjectivePitPresenceRateDenominator: 1,
|
||||||
|
preObjectivePickParticipationRateNumerator: 1,
|
||||||
|
preObjectivePickParticipationRateDenominator: 1,
|
||||||
|
deathFollowedByTeamLossRateNumerator: 1,
|
||||||
|
deathFollowedByTeamLossRateDenominator: 2,
|
||||||
|
deathTradedForTeamAdvantageRateNumerator: 1,
|
||||||
|
deathTradedForTeamAdvantageRateDenominator: 2,
|
||||||
|
deathWhileIsolatedFromNearestAllyRateNumerator: 1,
|
||||||
|
deathWhileIsolatedFromNearestAllyRateDenominator: 2,
|
||||||
|
laneLeadConversionRateNumerator: 1,
|
||||||
|
laneLeadConversionRateDenominator: 1,
|
||||||
|
roamConvertedToTeamAdvantageRateNumerator: 1,
|
||||||
|
roamConvertedToTeamAdvantageRateDenominator: 1,
|
||||||
|
shutdownGoldCollectedPerGame: 450,
|
||||||
|
platePresenceParticipationRateNumerator: 1,
|
||||||
|
platePresenceParticipationRateDenominator: 1,
|
||||||
|
objectiveBountyComebackParticipationRateNumerator: 1,
|
||||||
|
objectiveBountyComebackParticipationRateDenominator: 1,
|
||||||
|
});
|
||||||
|
expect(result.normalized.objectiveFightOpeningParticipationRate).toBe(1);
|
||||||
|
expect(result.normalized.deathFollowedByTeamLossRate).toBe(0.5);
|
||||||
|
expect(result.normalized.deathTradedForTeamAdvantageRate).toBe(0.5);
|
||||||
|
expect(result.normalized.deathWhileIsolatedFromNearestAllyRate).toBe(0.5);
|
||||||
|
expect(result.vector).toHaveLength(VECTOR_METRICS.length);
|
||||||
|
expect(
|
||||||
|
VECTOR_METRICS.some(
|
||||||
|
(metric) => metric.id === 'shutdownGoldCollectedPerGame',
|
||||||
|
),
|
||||||
|
).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extracts early deficit recovery as a sparse ratio metric', () => {
|
||||||
|
const feature = createBaseFeature();
|
||||||
|
const result = service.extractTimelineMetrics(
|
||||||
|
feature,
|
||||||
|
createRawMatch(),
|
||||||
|
createDeficitRecoveryTimeline(),
|
||||||
|
{
|
||||||
|
advantageEvents: [],
|
||||||
|
deathEvents: [],
|
||||||
|
fightClusters: [],
|
||||||
|
objectiveWindows: [],
|
||||||
|
roamFrames: [],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.features).toMatchObject({
|
||||||
|
goldDiffAt10: -700,
|
||||||
|
earlyDeficitRecoveryRateNumerator: 1,
|
||||||
|
earlyDeficitRecoveryRateDenominator: 1,
|
||||||
|
laneLeadConversionRateNumerator: 0,
|
||||||
|
laneLeadConversionRateDenominator: 0,
|
||||||
|
});
|
||||||
|
expect(result.normalized.earlyDeficitRecoveryRate).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not count the death kill event as a follow-up team loss', () => {
|
||||||
|
const feature = createBaseFeature();
|
||||||
|
const result = service.extractTimelineMetrics(
|
||||||
|
feature,
|
||||||
|
createRawMatch(),
|
||||||
|
createTimeline(),
|
||||||
|
{
|
||||||
|
advantageEvents: [
|
||||||
|
{
|
||||||
|
timestampMs: 400_000,
|
||||||
|
teamId: 200,
|
||||||
|
type: 'championKill',
|
||||||
|
score: 1,
|
||||||
|
participantIds: [6],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
deathEvents: [
|
||||||
|
{
|
||||||
|
t: 400_000,
|
||||||
|
victimParticipantId: 1,
|
||||||
|
x: 4_000,
|
||||||
|
y: 4_000,
|
||||||
|
zone: 'middleLane',
|
||||||
|
shutdownBountyGiven: 0,
|
||||||
|
nearestAllyDistanceApprox: 1_500,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
fightClusters: [],
|
||||||
|
objectiveWindows: [],
|
||||||
|
roamFrames: [],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result.features).toMatchObject({
|
||||||
|
deathFollowedByTeamLossRateNumerator: 0,
|
||||||
|
deathFollowedByTeamLossRateDenominator: 1,
|
||||||
|
});
|
||||||
|
expect(result.normalized.deathFollowedByTeamLossRate).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,10 @@
|
|||||||
import {
|
import {
|
||||||
|
ConnectionService,
|
||||||
resolveMongoAppName,
|
resolveMongoAppName,
|
||||||
resolveMongoConnectionOptions,
|
resolveMongoConnectionOptions,
|
||||||
resolveMongoDbName,
|
resolveMongoDbName,
|
||||||
} from './connection.service';
|
} from './connection.service';
|
||||||
|
import { modelDefinitions } from './schemas';
|
||||||
|
|
||||||
describe('resolveMongoDbName', () => {
|
describe('resolveMongoDbName', () => {
|
||||||
it('uses production database only for prod', () => {
|
it('uses production database only for prod', () => {
|
||||||
@@ -17,6 +19,57 @@ describe('resolveMongoDbName', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('ConnectionService.ensureCollections', () => {
|
||||||
|
function createConnectionService() {
|
||||||
|
return new ConnectionService({
|
||||||
|
get: jest.fn(),
|
||||||
|
ready: jest.fn(),
|
||||||
|
} as never);
|
||||||
|
}
|
||||||
|
|
||||||
|
it('creates every registered collection that does not exist yet', async () => {
|
||||||
|
const connectionService = createConnectionService();
|
||||||
|
const hasNext = jest.fn().mockResolvedValue(false);
|
||||||
|
const listCollections = jest.fn(() => ({ hasNext }));
|
||||||
|
const createCollection = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const getModel = jest.fn().mockResolvedValue({ createCollection });
|
||||||
|
|
||||||
|
connectionService.getConnection = jest.fn().mockResolvedValue({
|
||||||
|
db: { listCollections },
|
||||||
|
});
|
||||||
|
connectionService.getModel = getModel;
|
||||||
|
|
||||||
|
await connectionService.ensureCollections();
|
||||||
|
|
||||||
|
expect(listCollections).toHaveBeenCalledTimes(modelDefinitions.length);
|
||||||
|
expect(listCollections).toHaveBeenCalledWith(
|
||||||
|
{ name: 'account' },
|
||||||
|
{ nameOnly: true },
|
||||||
|
);
|
||||||
|
expect(getModel).toHaveBeenCalledTimes(modelDefinitions.length);
|
||||||
|
expect(createCollection).toHaveBeenCalledTimes(modelDefinitions.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips collections that already exist', async () => {
|
||||||
|
const connectionService = createConnectionService();
|
||||||
|
const hasNext = jest.fn().mockResolvedValue(true);
|
||||||
|
const listCollections = jest.fn(() => ({ hasNext }));
|
||||||
|
const createCollection = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const getModel = jest.fn().mockResolvedValue({ createCollection });
|
||||||
|
|
||||||
|
connectionService.getConnection = jest.fn().mockResolvedValue({
|
||||||
|
db: { listCollections },
|
||||||
|
});
|
||||||
|
connectionService.getModel = getModel;
|
||||||
|
|
||||||
|
await connectionService.ensureCollections();
|
||||||
|
|
||||||
|
expect(listCollections).toHaveBeenCalledTimes(modelDefinitions.length);
|
||||||
|
expect(getModel).not.toHaveBeenCalled();
|
||||||
|
expect(createCollection).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('resolveMongoAppName', () => {
|
describe('resolveMongoAppName', () => {
|
||||||
it('identifies api environment and process for MongoDB connection tracking', () => {
|
it('identifies api environment and process for MongoDB connection tracking', () => {
|
||||||
expect(resolveMongoAppName('staging', 1234)).toBe(
|
expect(resolveMongoAppName('staging', 1234)).toBe(
|
||||||
|
|||||||
@@ -118,9 +118,32 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async ensureCollections(): Promise<void> {
|
||||||
|
const connection = await this.getConnection();
|
||||||
|
let createdCollectionCount = 0;
|
||||||
|
|
||||||
|
for (const modelDefinition of modelDefinitions) {
|
||||||
|
const collectionExists = await this.collectionExists(
|
||||||
|
connection,
|
||||||
|
modelDefinition.collectionName,
|
||||||
|
);
|
||||||
|
if (collectionExists) continue;
|
||||||
|
|
||||||
|
const model = await this.getModel(
|
||||||
|
modelDefinition.name as keyof ModelTypes,
|
||||||
|
);
|
||||||
|
await model.createCollection();
|
||||||
|
createdCollectionCount += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`MongoDB collections ensured. registered=${modelDefinitions.length} created=${createdCollectionCount}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
public async onModuleInit() {
|
public async onModuleInit() {
|
||||||
await this.getConnection().catch((error: unknown) => {
|
await this.ensureCollections().catch((error: unknown) => {
|
||||||
this.logError('Failed to initialize MongoDB connection', error);
|
this.logError('Failed to initialize MongoDB collections', error);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -134,4 +157,18 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
error instanceof Error ? error.stack : undefined,
|
error instanceof Error ? error.stack : undefined,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async collectionExists(
|
||||||
|
connection: mongoose.Connection,
|
||||||
|
collectionName: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const database = connection.db;
|
||||||
|
if (!database) {
|
||||||
|
throw new Error('MongoDB database handle is unavailable.');
|
||||||
|
}
|
||||||
|
|
||||||
|
return database
|
||||||
|
.listCollections({ name: collectionName }, { nameOnly: true })
|
||||||
|
.hasNext();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -107,7 +107,7 @@ export const PlayerProfileSchema = new Schema<PlayerProfile>(
|
|||||||
);
|
);
|
||||||
|
|
||||||
PlayerProfileSchema.index({ puuid: 1, queueId: 1 }, { unique: true });
|
PlayerProfileSchema.index({ puuid: 1, queueId: 1 }, { unique: true });
|
||||||
// 운영 조회용 (멘토 검색 자체는 Atlas Vector Search 인덱스 사용)
|
// 운영 조회용 (유사 유저 검색 자체는 Atlas Vector Search 인덱스 사용)
|
||||||
PlayerProfileSchema.index({ isSeed: 1, mainRole: 1, tier: 1 });
|
PlayerProfileSchema.index({ isSeed: 1, mainRole: 1, tier: 1 });
|
||||||
|
|
||||||
export type PlayerProfileDocument = HydratedDocument<PlayerProfile>;
|
export type PlayerProfileDocument = HydratedDocument<PlayerProfile>;
|
||||||
@@ -2,14 +2,14 @@ import { HydratedDocument, Schema } from 'mongoose';
|
|||||||
import { MongooseTimestamps } from './common';
|
import { MongooseTimestamps } from './common';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* - mentor-match: 유사 고티어 유저 Top-K (MVP 3)
|
* - similar-player: 플레이스타일이 비슷한 유저 Top-K (MVP 3)
|
||||||
* - champion-recommendation: Fit/Growth/Stretch 챔피언 추천 (MVP 4)
|
* - champion-recommendation: Fit/Growth/Stretch 챔피언 추천 (MVP 4)
|
||||||
* - llm-feedback: LLM 생성 피드백 (MVP 5)
|
* - llm-feedback: LLM 생성 피드백 (MVP 5)
|
||||||
*/
|
*/
|
||||||
export type RecommendationType =
|
export type RecommendationType =
|
||||||
'mentor-match' | 'champion-recommendation' | 'llm-feedback';
|
'similar-player' | 'champion-recommendation' | 'llm-feedback';
|
||||||
export const RECOMMENDATION_TYPES: RecommendationType[] = [
|
export const RECOMMENDATION_TYPES: RecommendationType[] = [
|
||||||
'mentor-match',
|
'similar-player',
|
||||||
'champion-recommendation',
|
'champion-recommendation',
|
||||||
'llm-feedback',
|
'llm-feedback',
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -1,11 +1,12 @@
|
|||||||
import { Module, Global } from '@nestjs/common';
|
import { Module, Global } from '@nestjs/common';
|
||||||
import { DatabaseModule } from './database/database.module';
|
import { DatabaseModule } from './database/database.module';
|
||||||
|
import { RedisModule } from './redis/redis.module';
|
||||||
import { SecretModule } from './secret/secret.module';
|
import { SecretModule } from './secret/secret.module';
|
||||||
|
|
||||||
@Global()
|
@Global()
|
||||||
@Module({
|
@Module({
|
||||||
imports: [SecretModule, DatabaseModule],
|
imports: [SecretModule, DatabaseModule, RedisModule],
|
||||||
providers: [],
|
providers: [],
|
||||||
exports: [SecretModule, DatabaseModule],
|
exports: [SecretModule, DatabaseModule, RedisModule],
|
||||||
})
|
})
|
||||||
export class GlobalModule {}
|
export class GlobalModule {}
|
||||||
@@ -0,0 +1,386 @@
|
|||||||
|
import { SecretService } from '../global/secret/secret.service';
|
||||||
|
import {
|
||||||
|
RiotApiClient,
|
||||||
|
RiotApiKeyError,
|
||||||
|
RiotApiTimeoutError,
|
||||||
|
type RiotApiClientOptions,
|
||||||
|
RiotNotFoundError,
|
||||||
|
} from './riot-api.client';
|
||||||
|
import { RiotRateLimiter } from './riot-rate-limiter';
|
||||||
|
|
||||||
|
type FetchMock = jest.Mock<ReturnType<typeof fetch>, Parameters<typeof fetch>>;
|
||||||
|
type SleepMock = jest.Mock<Promise<void>, [number]>;
|
||||||
|
|
||||||
|
function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
|
||||||
|
return new Response(JSON.stringify(body), {
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
status: 200,
|
||||||
|
...init,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function createFetchMock(): FetchMock {
|
||||||
|
return jest.fn<ReturnType<typeof fetch>, Parameters<typeof fetch>>();
|
||||||
|
}
|
||||||
|
|
||||||
|
function createClient(
|
||||||
|
fetchMock: FetchMock,
|
||||||
|
options?: {
|
||||||
|
clientOptions?: Partial<RiotApiClientOptions>;
|
||||||
|
sleep?: SleepMock;
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const getSecret = jest
|
||||||
|
.fn<Promise<string>, [string]>()
|
||||||
|
.mockResolvedValue('RGAPI-test-key');
|
||||||
|
const waitForSlot = jest
|
||||||
|
.fn<Promise<void>, [string]>()
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
const sleep =
|
||||||
|
options?.sleep ??
|
||||||
|
jest.fn<Promise<void>, [number]>().mockResolvedValue(undefined);
|
||||||
|
const secretService = {
|
||||||
|
get: getSecret,
|
||||||
|
} as unknown as SecretService;
|
||||||
|
const rateLimiter = {
|
||||||
|
waitForSlot,
|
||||||
|
} as unknown as RiotRateLimiter;
|
||||||
|
const clientOptions: RiotApiClientOptions = {
|
||||||
|
fetchFn: fetchMock,
|
||||||
|
sleep,
|
||||||
|
...options?.clientOptions,
|
||||||
|
};
|
||||||
|
const client = new RiotApiClient(secretService, rateLimiter, clientOptions);
|
||||||
|
|
||||||
|
return { client, getSecret, sleep, waitForSlot };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('RiotApiClient', () => {
|
||||||
|
it('fetches account data through the regional Riot ID endpoint with an API key header', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(
|
||||||
|
jsonResponse({
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { client, getSecret, waitForSlot } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
client.getAccountByRiotId('Hide on bush', 'KR1', 'asia'),
|
||||||
|
).resolves.toEqual({
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(getSecret).toHaveBeenCalledWith('RIOT_API_KEY');
|
||||||
|
expect(waitForSlot).toHaveBeenCalledWith('asia');
|
||||||
|
const [requestUrl, requestInit] = fetchMock.mock.calls[0];
|
||||||
|
expect(requestUrl).toBe(
|
||||||
|
'https://asia.api.riotgames.com/riot/account/v1/accounts/by-riot-id/Hide%20on%20bush/KR1',
|
||||||
|
);
|
||||||
|
expect(requestInit?.headers).toEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
'X-Riot-Token': 'RGAPI-test-key',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches account data through the regional PUUID endpoint', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(
|
||||||
|
jsonResponse({
|
||||||
|
puuid: 'puuid/1',
|
||||||
|
gameName: 'Seed Player',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { client, waitForSlot } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(client.getAccountByPuuid('puuid/1', 'asia')).resolves.toEqual({
|
||||||
|
puuid: 'puuid/1',
|
||||||
|
gameName: 'Seed Player',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(waitForSlot).toHaveBeenCalledWith('asia');
|
||||||
|
expect(fetchMock).toHaveBeenCalledWith(
|
||||||
|
'https://asia.api.riotgames.com/riot/account/v1/accounts/by-puuid/puuid%2F1',
|
||||||
|
expect.any(Object),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches platform and regional League endpoints with encoded parameters and query filters', async () => {
|
||||||
|
const fetchMock = createFetchMock()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse({
|
||||||
|
profileIconId: 7,
|
||||||
|
puuid: 'puuid/1',
|
||||||
|
summonerLevel: 30,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(jsonResponse(['KR_1', 'KR_2']));
|
||||||
|
const { client } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await client.getSummonerByPuuid('puuid/1', 'kr');
|
||||||
|
await expect(
|
||||||
|
client.getMatchIds('puuid/1', {
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
queue: 420,
|
||||||
|
start: 0,
|
||||||
|
count: 20,
|
||||||
|
}),
|
||||||
|
).resolves.toEqual(['KR_1', 'KR_2']);
|
||||||
|
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
1,
|
||||||
|
'https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-puuid/puuid%2F1',
|
||||||
|
expect.any(Object),
|
||||||
|
);
|
||||||
|
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||||
|
2,
|
||||||
|
'https://asia.api.riotgames.com/lol/match/v5/matches/by-puuid/puuid%2F1/ids?queue=420&start=0&count=20',
|
||||||
|
expect.any(Object),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts current Summoner-V4 by-puuid responses', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(
|
||||||
|
jsonResponse({
|
||||||
|
profileIconId: 7,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
revisionDate: 1_783_056_144_000,
|
||||||
|
summonerLevel: 30,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { client } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(client.getSummonerByPuuid('puuid-1', 'kr')).resolves.toEqual({
|
||||||
|
profileIconId: 7,
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
revisionDate: 1_783_056_144_000,
|
||||||
|
summonerLevel: 30,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('accepts current League-V4 by-puuid entries without league ids', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(
|
||||||
|
jsonResponse([
|
||||||
|
{
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'DIAMOND',
|
||||||
|
rank: 'IV',
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
leaguePoints: 0,
|
||||||
|
wins: 164,
|
||||||
|
losses: 152,
|
||||||
|
veteran: false,
|
||||||
|
inactive: false,
|
||||||
|
freshBlood: false,
|
||||||
|
hotStreak: false,
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const { client } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
client.getLeagueEntriesByPuuid('puuid-1', 'kr'),
|
||||||
|
).resolves.toEqual([
|
||||||
|
{
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
tier: 'DIAMOND',
|
||||||
|
rank: 'IV',
|
||||||
|
leaguePoints: 0,
|
||||||
|
wins: 164,
|
||||||
|
losses: 152,
|
||||||
|
veteran: false,
|
||||||
|
inactive: false,
|
||||||
|
freshBlood: false,
|
||||||
|
hotStreak: false,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches apex League-V4 lists by queue without legacy summoner ids', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(
|
||||||
|
jsonResponse({
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
queue: 'RANKED_SOLO_5x5',
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
puuid: 'seed-puuid-1',
|
||||||
|
leaguePoints: 1200,
|
||||||
|
rank: 'I',
|
||||||
|
wins: 300,
|
||||||
|
losses: 210,
|
||||||
|
veteran: true,
|
||||||
|
inactive: false,
|
||||||
|
freshBlood: false,
|
||||||
|
hotStreak: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { client, waitForSlot } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
client.getChallengerLeagueByQueue('RANKED_SOLO_5x5', 'kr'),
|
||||||
|
).resolves.toEqual({
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
puuid: 'seed-puuid-1',
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
rank: 'I',
|
||||||
|
leaguePoints: 1200,
|
||||||
|
wins: 300,
|
||||||
|
losses: 210,
|
||||||
|
veteran: true,
|
||||||
|
inactive: false,
|
||||||
|
freshBlood: false,
|
||||||
|
hotStreak: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(waitForSlot).toHaveBeenCalledWith('kr');
|
||||||
|
expect(fetchMock).toHaveBeenCalledWith(
|
||||||
|
'https://kr.api.riotgames.com/lol/league/v4/challengerleagues/by-queue/RANKED_SOLO_5x5',
|
||||||
|
expect.any(Object),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects apex League-V4 list entries without puuid', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(
|
||||||
|
jsonResponse({
|
||||||
|
tier: 'MASTER',
|
||||||
|
queue: 'RANKED_SOLO_5x5',
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
leaguePoints: 200,
|
||||||
|
rank: 'I',
|
||||||
|
wins: 120,
|
||||||
|
losses: 100,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { client } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
client.getMasterLeagueByQueue('RANKED_SOLO_5x5', 'kr'),
|
||||||
|
).rejects.toThrow(
|
||||||
|
'Riot apex league entry response was missing string field "puuid".',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('honors Retry-After for 429 responses and retries', async () => {
|
||||||
|
const sleep = jest
|
||||||
|
.fn<Promise<void>, [number]>()
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
const fetchMock = createFetchMock()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(
|
||||||
|
{ status: { message: 'rate limited' } },
|
||||||
|
{
|
||||||
|
status: 429,
|
||||||
|
headers: { 'retry-after': '2' },
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(jsonResponse(['KR_1']));
|
||||||
|
const { client } = createClient(fetchMock, { sleep });
|
||||||
|
|
||||||
|
await expect(client.getMatchIds('puuid-1')).resolves.toEqual(['KR_1']);
|
||||||
|
|
||||||
|
expect(sleep).toHaveBeenCalledWith(2000);
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('caps oversized Retry-After waits before retrying', async () => {
|
||||||
|
const sleep = jest
|
||||||
|
.fn<Promise<void>, [number]>()
|
||||||
|
.mockResolvedValue(undefined);
|
||||||
|
const fetchMock = createFetchMock()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
jsonResponse(
|
||||||
|
{ status: { message: 'rate limited' } },
|
||||||
|
{
|
||||||
|
status: 429,
|
||||||
|
headers: { 'retry-after': '9999' },
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(jsonResponse(['KR_1']));
|
||||||
|
const { client } = createClient(fetchMock, { sleep });
|
||||||
|
|
||||||
|
await expect(client.getMatchIds('puuid-1')).resolves.toEqual(['KR_1']);
|
||||||
|
|
||||||
|
expect(sleep).toHaveBeenCalledWith(30_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fails 401 and 403 responses without retrying or leaking the API key', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(
|
||||||
|
jsonResponse({ status: { message: 'Forbidden' } }, { status: 403 }),
|
||||||
|
);
|
||||||
|
const { client } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(client.getMatch('KR_1')).rejects.toThrow(RiotApiKeyError);
|
||||||
|
await expect(client.getMatch('KR_1')).rejects.not.toThrow('RGAPI-test-key');
|
||||||
|
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('maps 404 responses to a domain not-found error', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(
|
||||||
|
jsonResponse({ status: { message: 'not found' } }, { status: 404 }),
|
||||||
|
);
|
||||||
|
const { client } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(client.getAccountByRiotId('Missing', 'KR1')).rejects.toThrow(
|
||||||
|
RiotNotFoundError,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('aborts a stalled Riot request with a domain timeout error', async () => {
|
||||||
|
const fetchMock: FetchMock = jest.fn(
|
||||||
|
(_input: RequestInfo | URL, init?: RequestInit) =>
|
||||||
|
new Promise<Response>((_resolve, reject) => {
|
||||||
|
init?.signal?.addEventListener('abort', () => {
|
||||||
|
reject(new DOMException('aborted', 'AbortError'));
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const { client } = createClient(fetchMock, {
|
||||||
|
clientOptions: { requestTimeoutMs: 1 },
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(client.getMatch('KR_1')).rejects.toThrow(RiotApiTimeoutError);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates minimal match and timeline response invariants', async () => {
|
||||||
|
const fetchMock = createFetchMock()
|
||||||
|
.mockResolvedValueOnce(jsonResponse({ metadata: {}, info: {} }))
|
||||||
|
.mockResolvedValueOnce(jsonResponse({ metadata: {}, info: {} }));
|
||||||
|
const { client } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(client.getMatch('KR_1')).resolves.toEqual({
|
||||||
|
metadata: {},
|
||||||
|
info: {},
|
||||||
|
});
|
||||||
|
await expect(client.getMatchTimeline('KR_1')).resolves.toEqual({
|
||||||
|
metadata: {},
|
||||||
|
info: {},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects malformed match payloads before analytics can consume them', async () => {
|
||||||
|
const fetchMock = createFetchMock().mockResolvedValue(jsonResponse({}));
|
||||||
|
const { client } = createClient(fetchMock);
|
||||||
|
|
||||||
|
await expect(client.getMatch('KR_1')).rejects.toThrow(
|
||||||
|
'Riot match response was missing object field "metadata".',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,548 @@
|
|||||||
|
import { Inject, Injectable, Optional } from '@nestjs/common';
|
||||||
|
import { SecretService } from '../global/secret/secret.service';
|
||||||
|
import {
|
||||||
|
RIOT_PLATFORM_ROUTES,
|
||||||
|
RIOT_REGIONAL_ROUTES,
|
||||||
|
type RiotPlatformRoute,
|
||||||
|
type RiotRegionalRoute,
|
||||||
|
} from './riot.types';
|
||||||
|
import { RiotRateLimiter } from './riot-rate-limiter';
|
||||||
|
|
||||||
|
export const RIOT_API_CLIENT_OPTIONS = Symbol('RIOT_API_CLIENT_OPTIONS');
|
||||||
|
|
||||||
|
type FetchFunction = typeof fetch;
|
||||||
|
|
||||||
|
export interface RiotApiClientOptions {
|
||||||
|
baseBackoffMs?: number;
|
||||||
|
maxRetryAfterMs?: number;
|
||||||
|
fetchFn?: FetchFunction;
|
||||||
|
requestTimeoutMs?: number;
|
||||||
|
maxRetries?: number;
|
||||||
|
sleep?: (durationMs: number) => Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiotAccountDto {
|
||||||
|
puuid: string;
|
||||||
|
gameName: string;
|
||||||
|
tagLine: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiotSummonerDto {
|
||||||
|
profileIconId: number;
|
||||||
|
puuid: string;
|
||||||
|
revisionDate?: number;
|
||||||
|
summonerLevel: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiotLeagueEntryDto {
|
||||||
|
freshBlood: boolean;
|
||||||
|
hotStreak: boolean;
|
||||||
|
inactive: boolean;
|
||||||
|
leaguePoints: number;
|
||||||
|
losses: number;
|
||||||
|
queueType: string;
|
||||||
|
rank: string;
|
||||||
|
tier: string;
|
||||||
|
veteran: boolean;
|
||||||
|
wins: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiotApexLeagueEntryDto extends RiotLeagueEntryDto {
|
||||||
|
puuid: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiotApexLeagueListDto {
|
||||||
|
entries: RiotApexLeagueEntryDto[];
|
||||||
|
queueType: string;
|
||||||
|
tier: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiotMatchIdsParams {
|
||||||
|
count?: number;
|
||||||
|
queue?: number;
|
||||||
|
regionalRoute?: RiotRegionalRoute;
|
||||||
|
start?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RiotApiError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
public readonly statusCode?: number,
|
||||||
|
public readonly code = 'RIOT_API_ERROR',
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.name = new.target.name;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RiotApiKeyError extends RiotApiError {
|
||||||
|
constructor(statusCode: number) {
|
||||||
|
super(
|
||||||
|
'Riot API key is missing, expired, or invalid. Regenerate the key in the Riot Developer Portal and update Infisical RIOT_API_KEY.',
|
||||||
|
statusCode,
|
||||||
|
'RIOT_API_KEY_INVALID',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RiotNotFoundError extends RiotApiError {
|
||||||
|
constructor(statusCode: number) {
|
||||||
|
super('Riot API resource was not found.', statusCode, 'RIOT_NOT_FOUND');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class RiotApiTimeoutError extends RiotApiError {
|
||||||
|
constructor() {
|
||||||
|
super('Riot API request timed out.', undefined, 'RIOT_API_TIMEOUT');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_MAX_RETRIES = 3;
|
||||||
|
const DEFAULT_BASE_BACKOFF_MS = 250;
|
||||||
|
const DEFAULT_MAX_RETRY_AFTER_MS = 30_000;
|
||||||
|
const DEFAULT_REQUEST_TIMEOUT_MS = 10_000;
|
||||||
|
|
||||||
|
function defaultSleep(durationMs: number): Promise<void> {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, durationMs));
|
||||||
|
}
|
||||||
|
|
||||||
|
function assertAllowedRoute(
|
||||||
|
route: RiotPlatformRoute | RiotRegionalRoute,
|
||||||
|
): void {
|
||||||
|
if (
|
||||||
|
!RIOT_PLATFORM_ROUTES.includes(route as RiotPlatformRoute) &&
|
||||||
|
!RIOT_REGIONAL_ROUTES.includes(route as RiotRegionalRoute)
|
||||||
|
) {
|
||||||
|
throw new RiotApiError('Unsupported Riot routing value.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function regionalBaseUrl(regionalRoute: RiotRegionalRoute): string {
|
||||||
|
assertAllowedRoute(regionalRoute);
|
||||||
|
return `https://${regionalRoute}.api.riotgames.com`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function platformBaseUrl(platformRoute: RiotPlatformRoute): string {
|
||||||
|
assertAllowedRoute(platformRoute);
|
||||||
|
return `https://${platformRoute}.api.riotgames.com`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function encodePathValue(value: string): string {
|
||||||
|
return encodeURIComponent(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseRetryAfterMs(
|
||||||
|
retryAfter: string | null,
|
||||||
|
now = Date.now(),
|
||||||
|
): number | undefined {
|
||||||
|
const trimmed = retryAfter?.trim();
|
||||||
|
if (!trimmed) return undefined;
|
||||||
|
|
||||||
|
const retryAfterSeconds = Number(trimmed);
|
||||||
|
if (Number.isFinite(retryAfterSeconds)) {
|
||||||
|
return Math.max(0, retryAfterSeconds * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
const retryAt = Date.parse(trimmed);
|
||||||
|
if (Number.isNaN(retryAt)) return undefined;
|
||||||
|
return Math.max(0, retryAt - now);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireRecord(value: unknown, endpointName: string) {
|
||||||
|
if (!isRecord(value)) {
|
||||||
|
throw new RiotApiError(
|
||||||
|
`Riot ${endpointName} response had an unexpected shape.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireRecordField(
|
||||||
|
record: Record<string, unknown>,
|
||||||
|
key: string,
|
||||||
|
endpointName: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const value = record[key];
|
||||||
|
if (!isRecord(value)) {
|
||||||
|
throw new RiotApiError(
|
||||||
|
`Riot ${endpointName} response was missing object field "${key}".`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function requireString(
|
||||||
|
record: Record<string, unknown>,
|
||||||
|
key: string,
|
||||||
|
endpointName: string,
|
||||||
|
): string {
|
||||||
|
const value = record[key];
|
||||||
|
if (typeof value !== 'string') {
|
||||||
|
throw new RiotApiError(
|
||||||
|
`Riot ${endpointName} response was missing string field "${key}".`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function numberOrFallback(
|
||||||
|
record: Record<string, unknown>,
|
||||||
|
key: string,
|
||||||
|
fallback: number,
|
||||||
|
): number {
|
||||||
|
const value = record[key];
|
||||||
|
return typeof value === 'number' ? value : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function optionalNumber(
|
||||||
|
record: Record<string, unknown>,
|
||||||
|
key: string,
|
||||||
|
): number | undefined {
|
||||||
|
const value = record[key];
|
||||||
|
return typeof value === 'number' ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function optionalBoolean(
|
||||||
|
record: Record<string, unknown>,
|
||||||
|
key: string,
|
||||||
|
fallback: boolean,
|
||||||
|
) {
|
||||||
|
const value = record[key];
|
||||||
|
return typeof value === 'boolean' ? value : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RiotApiClient {
|
||||||
|
private readonly baseBackoffMs: number;
|
||||||
|
private readonly fetchFn: FetchFunction;
|
||||||
|
private readonly maxRetryAfterMs: number;
|
||||||
|
private readonly maxRetries: number;
|
||||||
|
private readonly requestTimeoutMs: number;
|
||||||
|
private readonly sleep: (durationMs: number) => Promise<void>;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly secretService: SecretService,
|
||||||
|
private readonly rateLimiter: RiotRateLimiter,
|
||||||
|
@Optional()
|
||||||
|
@Inject(RIOT_API_CLIENT_OPTIONS)
|
||||||
|
options: RiotApiClientOptions = {},
|
||||||
|
) {
|
||||||
|
this.baseBackoffMs = options.baseBackoffMs ?? DEFAULT_BASE_BACKOFF_MS;
|
||||||
|
this.fetchFn = options.fetchFn ?? fetch;
|
||||||
|
this.maxRetryAfterMs =
|
||||||
|
options.maxRetryAfterMs ?? DEFAULT_MAX_RETRY_AFTER_MS;
|
||||||
|
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
|
||||||
|
this.requestTimeoutMs =
|
||||||
|
options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||||
|
this.sleep = options.sleep ?? defaultSleep;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getAccountByRiotId(
|
||||||
|
gameName: string,
|
||||||
|
tagLine: string,
|
||||||
|
regionalRoute: RiotRegionalRoute = 'asia',
|
||||||
|
): Promise<RiotAccountDto> {
|
||||||
|
const response = await this.requestJson(
|
||||||
|
regionalRoute,
|
||||||
|
`${regionalBaseUrl(regionalRoute)}/riot/account/v1/accounts/by-riot-id/${encodePathValue(gameName)}/${encodePathValue(tagLine)}`,
|
||||||
|
);
|
||||||
|
return this.parseAccount(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getAccountByPuuid(
|
||||||
|
puuid: string,
|
||||||
|
regionalRoute: RiotRegionalRoute = 'asia',
|
||||||
|
): Promise<RiotAccountDto> {
|
||||||
|
const response = await this.requestJson(
|
||||||
|
regionalRoute,
|
||||||
|
`${regionalBaseUrl(regionalRoute)}/riot/account/v1/accounts/by-puuid/${encodePathValue(puuid)}`,
|
||||||
|
);
|
||||||
|
return this.parseAccount(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getSummonerByPuuid(
|
||||||
|
puuid: string,
|
||||||
|
platformRoute: RiotPlatformRoute = 'kr',
|
||||||
|
): Promise<RiotSummonerDto> {
|
||||||
|
const response = await this.requestJson(
|
||||||
|
platformRoute,
|
||||||
|
`${platformBaseUrl(platformRoute)}/lol/summoner/v4/summoners/by-puuid/${encodePathValue(puuid)}`,
|
||||||
|
);
|
||||||
|
return this.parseSummoner(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getLeagueEntriesByPuuid(
|
||||||
|
puuid: string,
|
||||||
|
platformRoute: RiotPlatformRoute = 'kr',
|
||||||
|
): Promise<RiotLeagueEntryDto[]> {
|
||||||
|
const response = await this.requestJson(
|
||||||
|
platformRoute,
|
||||||
|
`${platformBaseUrl(platformRoute)}/lol/league/v4/entries/by-puuid/${encodePathValue(puuid)}`,
|
||||||
|
);
|
||||||
|
return this.parseLeagueEntries(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getChallengerLeagueByQueue(
|
||||||
|
queueType = 'RANKED_SOLO_5x5',
|
||||||
|
platformRoute: RiotPlatformRoute = 'kr',
|
||||||
|
): Promise<RiotApexLeagueListDto> {
|
||||||
|
return this.getApexLeagueByQueue(
|
||||||
|
'challengerleagues',
|
||||||
|
queueType,
|
||||||
|
platformRoute,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getGrandmasterLeagueByQueue(
|
||||||
|
queueType = 'RANKED_SOLO_5x5',
|
||||||
|
platformRoute: RiotPlatformRoute = 'kr',
|
||||||
|
): Promise<RiotApexLeagueListDto> {
|
||||||
|
return this.getApexLeagueByQueue(
|
||||||
|
'grandmasterleagues',
|
||||||
|
queueType,
|
||||||
|
platformRoute,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getMasterLeagueByQueue(
|
||||||
|
queueType = 'RANKED_SOLO_5x5',
|
||||||
|
platformRoute: RiotPlatformRoute = 'kr',
|
||||||
|
): Promise<RiotApexLeagueListDto> {
|
||||||
|
return this.getApexLeagueByQueue('masterleagues', queueType, platformRoute);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getMatchIds(
|
||||||
|
puuid: string,
|
||||||
|
params: RiotMatchIdsParams = {},
|
||||||
|
): Promise<string[]> {
|
||||||
|
const regionalRoute = params.regionalRoute ?? 'asia';
|
||||||
|
const searchParams = new URLSearchParams();
|
||||||
|
if (params.queue !== undefined)
|
||||||
|
searchParams.set('queue', String(params.queue));
|
||||||
|
if (params.start !== undefined)
|
||||||
|
searchParams.set('start', String(params.start));
|
||||||
|
if (params.count !== undefined)
|
||||||
|
searchParams.set('count', String(params.count));
|
||||||
|
|
||||||
|
const query = searchParams.size > 0 ? `?${searchParams.toString()}` : '';
|
||||||
|
const response = await this.requestJson(
|
||||||
|
regionalRoute,
|
||||||
|
`${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/by-puuid/${encodePathValue(puuid)}/ids${query}`,
|
||||||
|
);
|
||||||
|
return this.parseMatchIds(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getMatch(
|
||||||
|
matchId: string,
|
||||||
|
regionalRoute: RiotRegionalRoute = 'asia',
|
||||||
|
): Promise<Record<string, unknown>> {
|
||||||
|
const response = await this.requestJson(
|
||||||
|
regionalRoute,
|
||||||
|
`${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/${encodePathValue(matchId)}`,
|
||||||
|
);
|
||||||
|
return this.parseMatchPayload(response, 'match');
|
||||||
|
}
|
||||||
|
|
||||||
|
public async getMatchTimeline(
|
||||||
|
matchId: string,
|
||||||
|
regionalRoute: RiotRegionalRoute = 'asia',
|
||||||
|
): Promise<Record<string, unknown>> {
|
||||||
|
const response = await this.requestJson(
|
||||||
|
regionalRoute,
|
||||||
|
`${regionalBaseUrl(regionalRoute)}/lol/match/v5/matches/${encodePathValue(matchId)}/timeline`,
|
||||||
|
);
|
||||||
|
return this.parseMatchPayload(response, 'match timeline');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getApexLeagueByQueue(
|
||||||
|
endpointName: 'challengerleagues' | 'grandmasterleagues' | 'masterleagues',
|
||||||
|
queueType: string,
|
||||||
|
platformRoute: RiotPlatformRoute,
|
||||||
|
): Promise<RiotApexLeagueListDto> {
|
||||||
|
const response = await this.requestJson(
|
||||||
|
platformRoute,
|
||||||
|
`${platformBaseUrl(platformRoute)}/lol/league/v4/${endpointName}/by-queue/${encodePathValue(queueType)}`,
|
||||||
|
);
|
||||||
|
return this.parseApexLeagueList(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async requestJson(
|
||||||
|
routingValue: RiotPlatformRoute | RiotRegionalRoute,
|
||||||
|
url: string,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const apiKey = await this.secretService.get('RIOT_API_KEY');
|
||||||
|
|
||||||
|
for (let attemptIndex = 0; ; attemptIndex += 1) {
|
||||||
|
await this.rateLimiter.waitForSlot(routingValue);
|
||||||
|
|
||||||
|
const response = await this.fetchWithTimeout(url, apiKey);
|
||||||
|
|
||||||
|
if (response.status === 429 && attemptIndex < this.maxRetries) {
|
||||||
|
const rawRetryAfterMs =
|
||||||
|
parseRetryAfterMs(response.headers.get('retry-after')) ??
|
||||||
|
this.exponentialBackoffMs(attemptIndex);
|
||||||
|
const retryAfterMs = Math.min(rawRetryAfterMs, this.maxRetryAfterMs);
|
||||||
|
await this.sleep(retryAfterMs);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status >= 500 && attemptIndex < this.maxRetries) {
|
||||||
|
await this.sleep(this.exponentialBackoffMs(attemptIndex));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.status === 401 || response.status === 403) {
|
||||||
|
throw new RiotApiKeyError(response.status);
|
||||||
|
}
|
||||||
|
if (response.status === 404) {
|
||||||
|
throw new RiotNotFoundError(response.status);
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new RiotApiError(
|
||||||
|
`Riot API request failed with status ${response.status}.`,
|
||||||
|
response.status,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return response.json();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private exponentialBackoffMs(attemptIndex: number): number {
|
||||||
|
return this.baseBackoffMs * 2 ** attemptIndex;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchWithTimeout(
|
||||||
|
url: string,
|
||||||
|
apiKey: string,
|
||||||
|
): Promise<Response> {
|
||||||
|
const abortController = new AbortController();
|
||||||
|
const timeout = setTimeout(
|
||||||
|
() => abortController.abort(),
|
||||||
|
this.requestTimeoutMs,
|
||||||
|
);
|
||||||
|
try {
|
||||||
|
return await this.fetchFn(url, {
|
||||||
|
headers: {
|
||||||
|
Accept: 'application/json',
|
||||||
|
'X-Riot-Token': apiKey,
|
||||||
|
},
|
||||||
|
signal: abortController.signal,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (
|
||||||
|
error instanceof DOMException &&
|
||||||
|
error.name.toLowerCase() === 'aborterror'
|
||||||
|
) {
|
||||||
|
throw new RiotApiTimeoutError();
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseAccount(value: unknown): RiotAccountDto {
|
||||||
|
const record = requireRecord(value, 'account');
|
||||||
|
return {
|
||||||
|
puuid: requireString(record, 'puuid', 'account'),
|
||||||
|
gameName: requireString(record, 'gameName', 'account'),
|
||||||
|
tagLine: requireString(record, 'tagLine', 'account'),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseSummoner(value: unknown): RiotSummonerDto {
|
||||||
|
const record = requireRecord(value, 'summoner');
|
||||||
|
return {
|
||||||
|
puuid: requireString(record, 'puuid', 'summoner'),
|
||||||
|
profileIconId: numberOrFallback(record, 'profileIconId', 0),
|
||||||
|
revisionDate: optionalNumber(record, 'revisionDate'),
|
||||||
|
summonerLevel: numberOrFallback(record, 'summonerLevel', 0),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
throw new RiotApiError(
|
||||||
|
'Riot league entries response had an unexpected shape.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return value.map((entry) => {
|
||||||
|
const record = requireRecord(entry, 'league entry');
|
||||||
|
return {
|
||||||
|
queueType: requireString(record, 'queueType', 'league entry'),
|
||||||
|
tier: requireString(record, 'tier', 'league entry'),
|
||||||
|
rank: requireString(record, 'rank', 'league entry'),
|
||||||
|
leaguePoints: numberOrFallback(record, 'leaguePoints', 0),
|
||||||
|
wins: numberOrFallback(record, 'wins', 0),
|
||||||
|
losses: numberOrFallback(record, 'losses', 0),
|
||||||
|
veteran: optionalBoolean(record, 'veteran', false),
|
||||||
|
inactive: optionalBoolean(record, 'inactive', false),
|
||||||
|
freshBlood: optionalBoolean(record, 'freshBlood', false),
|
||||||
|
hotStreak: optionalBoolean(record, 'hotStreak', false),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseApexLeagueList(value: unknown): RiotApexLeagueListDto {
|
||||||
|
const record = requireRecord(value, 'apex league list');
|
||||||
|
const tier = requireString(record, 'tier', 'apex league list');
|
||||||
|
const queueType = requireString(record, 'queue', 'apex league list');
|
||||||
|
const entries = record.entries;
|
||||||
|
if (!Array.isArray(entries)) {
|
||||||
|
throw new RiotApiError(
|
||||||
|
'Riot apex league list response was missing array field "entries".',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
tier,
|
||||||
|
queueType,
|
||||||
|
entries: entries.map((entry) => {
|
||||||
|
const entryRecord = requireRecord(entry, 'apex league entry');
|
||||||
|
return {
|
||||||
|
puuid: requireString(entryRecord, 'puuid', 'apex league entry'),
|
||||||
|
queueType,
|
||||||
|
tier,
|
||||||
|
rank: requireString(entryRecord, 'rank', 'apex league entry'),
|
||||||
|
leaguePoints: numberOrFallback(entryRecord, 'leaguePoints', 0),
|
||||||
|
wins: numberOrFallback(entryRecord, 'wins', 0),
|
||||||
|
losses: numberOrFallback(entryRecord, 'losses', 0),
|
||||||
|
veteran: optionalBoolean(entryRecord, 'veteran', false),
|
||||||
|
inactive: optionalBoolean(entryRecord, 'inactive', false),
|
||||||
|
freshBlood: optionalBoolean(entryRecord, 'freshBlood', false),
|
||||||
|
hotStreak: optionalBoolean(entryRecord, 'hotStreak', false),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseMatchIds(value: unknown): string[] {
|
||||||
|
if (!Array.isArray(value)) {
|
||||||
|
throw new RiotApiError('Riot match id response had an unexpected shape.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const matchIds = value.filter(
|
||||||
|
(matchId): matchId is string => typeof matchId === 'string',
|
||||||
|
);
|
||||||
|
if (matchIds.length !== value.length) {
|
||||||
|
throw new RiotApiError('Riot match id response had an unexpected shape.');
|
||||||
|
}
|
||||||
|
return matchIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseMatchPayload(
|
||||||
|
value: unknown,
|
||||||
|
endpointName: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const record = requireRecord(value, endpointName);
|
||||||
|
requireRecordField(record, 'metadata', endpointName);
|
||||||
|
requireRecordField(record, 'info', endpointName);
|
||||||
|
return record;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { RiotRateLimiter } from './riot-rate-limiter';
|
||||||
|
|
||||||
|
class ManualClock {
|
||||||
|
public currentTimeMs = 0;
|
||||||
|
public sleeps: number[] = [];
|
||||||
|
|
||||||
|
now = () => this.currentTimeMs;
|
||||||
|
|
||||||
|
sleep = (durationMs: number): Promise<void> => {
|
||||||
|
this.sleeps.push(durationMs);
|
||||||
|
this.currentTimeMs += durationMs;
|
||||||
|
return Promise.resolve();
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('RiotRateLimiter', () => {
|
||||||
|
it('waits when the one-second development key window is exhausted', async () => {
|
||||||
|
const clock = new ManualClock();
|
||||||
|
const limiter = new RiotRateLimiter({ clock });
|
||||||
|
|
||||||
|
for (let index = 0; index < 20; index += 1) {
|
||||||
|
await limiter.waitForSlot('asia');
|
||||||
|
}
|
||||||
|
await limiter.waitForSlot('asia');
|
||||||
|
|
||||||
|
expect(clock.sleeps).toEqual([1000]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tracks windows independently per Riot routing value', async () => {
|
||||||
|
const clock = new ManualClock();
|
||||||
|
const limiter = new RiotRateLimiter({ clock });
|
||||||
|
|
||||||
|
for (let index = 0; index < 20; index += 1) {
|
||||||
|
await limiter.waitForSlot('asia');
|
||||||
|
}
|
||||||
|
await limiter.waitForSlot('kr');
|
||||||
|
|
||||||
|
expect(clock.sleeps).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('waits for the longest exhausted window before recording a new request', async () => {
|
||||||
|
const clock = new ManualClock();
|
||||||
|
const limiter = new RiotRateLimiter({
|
||||||
|
clock,
|
||||||
|
windows: [
|
||||||
|
{ limit: 2, durationMs: 1000 },
|
||||||
|
{ limit: 3, durationMs: 5000 },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
await limiter.waitForSlot('asia');
|
||||||
|
await limiter.waitForSlot('asia');
|
||||||
|
clock.currentTimeMs = 1000;
|
||||||
|
await limiter.waitForSlot('asia');
|
||||||
|
await limiter.waitForSlot('asia');
|
||||||
|
|
||||||
|
expect(clock.sleeps).toEqual([4000]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import { Inject, Injectable, Optional } from '@nestjs/common';
|
||||||
|
|
||||||
|
export const RIOT_RATE_LIMITER_OPTIONS = Symbol('RIOT_RATE_LIMITER_OPTIONS');
|
||||||
|
|
||||||
|
export interface RiotRateLimitWindow {
|
||||||
|
durationMs: number;
|
||||||
|
limit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiotRateLimiterClock {
|
||||||
|
now(): number;
|
||||||
|
sleep(durationMs: number): Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface RiotRateLimiterOptions {
|
||||||
|
clock?: RiotRateLimiterClock;
|
||||||
|
windows?: RiotRateLimitWindow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_RATE_LIMIT_WINDOWS: RiotRateLimitWindow[] = [
|
||||||
|
{ limit: 20, durationMs: 1000 },
|
||||||
|
{ limit: 100, durationMs: 120_000 },
|
||||||
|
];
|
||||||
|
|
||||||
|
// Single-process limiter for the MVP worker/API process. If workers split into
|
||||||
|
// multiple processes or hosts, replace this with Redis-backed coordination.
|
||||||
|
const DEFAULT_CLOCK: RiotRateLimiterClock = {
|
||||||
|
now: () => Date.now(),
|
||||||
|
sleep: (durationMs: number) =>
|
||||||
|
new Promise((resolve) => setTimeout(resolve, durationMs)),
|
||||||
|
};
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class RiotRateLimiter {
|
||||||
|
private readonly clock: RiotRateLimiterClock;
|
||||||
|
private readonly windows: RiotRateLimitWindow[];
|
||||||
|
private readonly requestTimestampsByRoutingValue = new Map<
|
||||||
|
string,
|
||||||
|
number[]
|
||||||
|
>();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@Optional()
|
||||||
|
@Inject(RIOT_RATE_LIMITER_OPTIONS)
|
||||||
|
options: RiotRateLimiterOptions = {},
|
||||||
|
) {
|
||||||
|
this.clock = options.clock ?? DEFAULT_CLOCK;
|
||||||
|
this.windows = options.windows ?? DEFAULT_RATE_LIMIT_WINDOWS;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async waitForSlot(routingValue: string): Promise<void> {
|
||||||
|
const requestTimestamps =
|
||||||
|
this.requestTimestampsByRoutingValue.get(routingValue) ?? [];
|
||||||
|
this.requestTimestampsByRoutingValue.set(routingValue, requestTimestamps);
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const now = this.clock.now();
|
||||||
|
this.pruneExpiredTimestamps(requestTimestamps, now);
|
||||||
|
|
||||||
|
const waitDurationMs = this.resolveWaitDurationMs(requestTimestamps, now);
|
||||||
|
if (waitDurationMs <= 0) {
|
||||||
|
requestTimestamps.push(now);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.clock.sleep(waitDurationMs);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private pruneExpiredTimestamps(
|
||||||
|
requestTimestamps: number[],
|
||||||
|
now: number,
|
||||||
|
): void {
|
||||||
|
const longestWindowDurationMs = Math.max(
|
||||||
|
...this.windows.map((window) => window.durationMs),
|
||||||
|
);
|
||||||
|
const firstRetainedIndex = requestTimestamps.findIndex(
|
||||||
|
(timestamp) => timestamp > now - longestWindowDurationMs,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (firstRetainedIndex === -1) {
|
||||||
|
requestTimestamps.splice(0, requestTimestamps.length);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (firstRetainedIndex > 0) {
|
||||||
|
requestTimestamps.splice(0, firstRetainedIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveWaitDurationMs(
|
||||||
|
requestTimestamps: number[],
|
||||||
|
now: number,
|
||||||
|
): number {
|
||||||
|
let waitDurationMs = 0;
|
||||||
|
|
||||||
|
for (const window of this.windows) {
|
||||||
|
const timestampsInWindow = requestTimestamps.filter(
|
||||||
|
(timestamp) => timestamp > now - window.durationMs,
|
||||||
|
);
|
||||||
|
if (timestampsInWindow.length < window.limit) continue;
|
||||||
|
|
||||||
|
const oldestTimestamp = timestampsInWindow[0];
|
||||||
|
waitDurationMs = Math.max(
|
||||||
|
waitDurationMs,
|
||||||
|
oldestTimestamp + window.durationMs - now,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return waitDurationMs;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Module } from '@nestjs/common';
|
||||||
|
import { SecretModule } from '../global/secret/secret.module';
|
||||||
|
import { RiotApiClient } from './riot-api.client';
|
||||||
|
import { RiotRateLimiter } from './riot-rate-limiter';
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
imports: [SecretModule],
|
||||||
|
providers: [RiotApiClient, RiotRateLimiter],
|
||||||
|
exports: [RiotApiClient, RiotRateLimiter],
|
||||||
|
})
|
||||||
|
export class RiotModule {}
|
||||||
@@ -17,12 +17,41 @@ export type RiotPlatformRoute =
|
|||||||
| 'ru'
|
| 'ru'
|
||||||
| 'me1'
|
| 'me1'
|
||||||
| 'oc1'
|
| 'oc1'
|
||||||
|
| 'ph2'
|
||||||
| 'sg2'
|
| 'sg2'
|
||||||
|
| 'th2'
|
||||||
| 'tw2'
|
| 'tw2'
|
||||||
| 'vn2';
|
| 'vn2';
|
||||||
|
|
||||||
export type RiotRegionalRoute = 'americas' | 'asia' | 'europe' | 'sea';
|
export type RiotRegionalRoute = 'americas' | 'asia' | 'europe' | 'sea';
|
||||||
|
|
||||||
|
export const RIOT_PLATFORM_ROUTES: readonly RiotPlatformRoute[] = [
|
||||||
|
'kr',
|
||||||
|
'jp1',
|
||||||
|
'na1',
|
||||||
|
'br1',
|
||||||
|
'la1',
|
||||||
|
'la2',
|
||||||
|
'euw1',
|
||||||
|
'eun1',
|
||||||
|
'tr1',
|
||||||
|
'ru',
|
||||||
|
'me1',
|
||||||
|
'oc1',
|
||||||
|
'ph2',
|
||||||
|
'sg2',
|
||||||
|
'th2',
|
||||||
|
'tw2',
|
||||||
|
'vn2',
|
||||||
|
];
|
||||||
|
|
||||||
|
export const RIOT_REGIONAL_ROUTES: readonly RiotRegionalRoute[] = [
|
||||||
|
'americas',
|
||||||
|
'asia',
|
||||||
|
'europe',
|
||||||
|
'sea',
|
||||||
|
];
|
||||||
|
|
||||||
export const PLATFORM_TO_REGIONAL_ROUTE: Record<
|
export const PLATFORM_TO_REGIONAL_ROUTE: Record<
|
||||||
RiotPlatformRoute,
|
RiotPlatformRoute,
|
||||||
RiotRegionalRoute
|
RiotRegionalRoute
|
||||||
@@ -39,7 +68,9 @@ export const PLATFORM_TO_REGIONAL_ROUTE: Record<
|
|||||||
ru: 'europe',
|
ru: 'europe',
|
||||||
me1: 'europe',
|
me1: 'europe',
|
||||||
oc1: 'sea',
|
oc1: 'sea',
|
||||||
|
ph2: 'sea',
|
||||||
sg2: 'sea',
|
sg2: 'sea',
|
||||||
|
th2: 'sea',
|
||||||
tw2: 'sea',
|
tw2: 'sea',
|
||||||
vn2: 'sea',
|
vn2: 'sea',
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,343 @@
|
|||||||
|
import {
|
||||||
|
ADVANTAGE_EVENT_WEIGHTS,
|
||||||
|
FEATURE_SCHEMA_VERSION,
|
||||||
|
METRICS,
|
||||||
|
SUMMONERS_RIFT_MAP,
|
||||||
|
SUMMONERS_RIFT_MAP_ZONES,
|
||||||
|
VECTOR_DIMENSION,
|
||||||
|
type AnalysisRequestAcceptedDto,
|
||||||
|
type AnalysisJobStatusDto,
|
||||||
|
type AnalysisRequestDto,
|
||||||
|
type PlayerAnalysisDto,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
|
|
||||||
|
const MVP_1_METRIC_IDS = [
|
||||||
|
'kda',
|
||||||
|
'killParticipation',
|
||||||
|
'damageShare',
|
||||||
|
'damagePerMin',
|
||||||
|
'goldPerMin',
|
||||||
|
'csPerMin',
|
||||||
|
'visionScorePerMin',
|
||||||
|
'wardsKilledPerMin',
|
||||||
|
'controlWardsPlaced',
|
||||||
|
'deathsPerMin',
|
||||||
|
'objectiveParticipation',
|
||||||
|
'soloKills',
|
||||||
|
];
|
||||||
|
const MVP_2_TIMELINE_METRIC_IDS = [
|
||||||
|
'goldDiffAt10',
|
||||||
|
'goldDiffAt14',
|
||||||
|
'csDiffAt10',
|
||||||
|
'xpDiffAt10',
|
||||||
|
'deathsBefore14',
|
||||||
|
'killParticipationBefore14',
|
||||||
|
'earlyWardsPerMin',
|
||||||
|
'objectivePreWardRate',
|
||||||
|
'eliteObjectiveParticipationRate',
|
||||||
|
'isolationTendency',
|
||||||
|
'teamfightFirstEngagementParticipationRate',
|
||||||
|
'teamfightCleanupKillParticipationRate',
|
||||||
|
'deathWithShutdownBountyGivenRate',
|
||||||
|
'ccTimePerMinute',
|
||||||
|
];
|
||||||
|
const MVP_2_INSIGHT_METRIC_IDS = [
|
||||||
|
'objectiveFightOpeningParticipationRate',
|
||||||
|
'objectiveFightOpeningConvertedToObjectiveRate',
|
||||||
|
'preObjectivePitPresenceRate',
|
||||||
|
'preObjectivePickParticipationRate',
|
||||||
|
'deathFollowedByTeamLossRate',
|
||||||
|
'deathTradedForTeamAdvantageRate',
|
||||||
|
'deathWhileIsolatedFromNearestAllyRate',
|
||||||
|
'earlyDeficitRecoveryRate',
|
||||||
|
'laneLeadConversionRate',
|
||||||
|
'roamConvertedToTeamAdvantageRate',
|
||||||
|
'shutdownGoldCollectedPerGame',
|
||||||
|
'platePresenceParticipationRate',
|
||||||
|
'objectiveBountyComebackParticipationRate',
|
||||||
|
];
|
||||||
|
const MVP_2_METRIC_IDS = [
|
||||||
|
...MVP_1_METRIC_IDS,
|
||||||
|
...MVP_2_TIMELINE_METRIC_IDS,
|
||||||
|
...MVP_2_INSIGHT_METRIC_IDS,
|
||||||
|
];
|
||||||
|
const MVP_2_TIMELINE_METRIC_CONTRACTS = [
|
||||||
|
{ id: 'goldDiffAt10', kind: 'scalar', direction: 'higherIsBetter' },
|
||||||
|
{ id: 'goldDiffAt14', kind: 'scalar', direction: 'higherIsBetter' },
|
||||||
|
{ id: 'csDiffAt10', kind: 'scalar', direction: 'higherIsBetter' },
|
||||||
|
{ id: 'xpDiffAt10', kind: 'scalar', direction: 'higherIsBetter' },
|
||||||
|
{ id: 'deathsBefore14', kind: 'scalar', direction: 'lowerIsBetter' },
|
||||||
|
{
|
||||||
|
id: 'killParticipationBefore14',
|
||||||
|
kind: 'scalar',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{ id: 'earlyWardsPerMin', kind: 'scalar', direction: 'higherIsBetter' },
|
||||||
|
{ id: 'objectivePreWardRate', kind: 'ratio', direction: 'higherIsBetter' },
|
||||||
|
{
|
||||||
|
id: 'eliteObjectiveParticipationRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{ id: 'isolationTendency', kind: 'scalar', direction: 'lowerIsBetter' },
|
||||||
|
{
|
||||||
|
id: 'teamfightFirstEngagementParticipationRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'teamfightCleanupKillParticipationRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'deathWithShutdownBountyGivenRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'lowerIsBetter',
|
||||||
|
},
|
||||||
|
{ id: 'ccTimePerMinute', kind: 'scalar', direction: 'higherIsBetter' },
|
||||||
|
] as const;
|
||||||
|
const MVP_2_INSIGHT_METRIC_CONTRACTS = [
|
||||||
|
{
|
||||||
|
id: 'objectiveFightOpeningParticipationRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'objectiveFightOpeningConvertedToObjectiveRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'preObjectivePitPresenceRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'preObjectivePickParticipationRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'deathFollowedByTeamLossRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'lowerIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'deathTradedForTeamAdvantageRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'deathWhileIsolatedFromNearestAllyRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'lowerIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'earlyDeficitRecoveryRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'laneLeadConversionRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'roamConvertedToTeamAdvantageRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'shutdownGoldCollectedPerGame',
|
||||||
|
kind: 'scalar',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'platePresenceParticipationRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'objectiveBountyComebackParticipationRate',
|
||||||
|
kind: 'ratio',
|
||||||
|
direction: 'higherIsBetter',
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
describe('shared feature registry', () => {
|
||||||
|
it('defines MVP 2 vector metrics in the documented order', () => {
|
||||||
|
expect(FEATURE_SCHEMA_VERSION).toBe(2);
|
||||||
|
expect(METRICS.map((metric) => metric.id)).toEqual(MVP_2_METRIC_IDS);
|
||||||
|
expect(VECTOR_DIMENSION).toBe(26);
|
||||||
|
expect(
|
||||||
|
METRICS.filter((metric) => metric.includeInVector).map(
|
||||||
|
(metric) => metric.id,
|
||||||
|
),
|
||||||
|
).toEqual([...MVP_1_METRIC_IDS, ...MVP_2_TIMELINE_METRIC_IDS]);
|
||||||
|
expect(METRICS.filter((metric) => metric.includeInVector)).toHaveLength(
|
||||||
|
VECTOR_DIMENSION,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps metric ids unique and every metric normalizable by role', () => {
|
||||||
|
const metricIds = METRICS.map((metric) => metric.id);
|
||||||
|
|
||||||
|
expect(new Set(metricIds).size).toBe(metricIds.length);
|
||||||
|
for (const metric of METRICS) {
|
||||||
|
expect(metric.label.trim()).toBeTruthy();
|
||||||
|
expect(metric.description.trim()).toBeTruthy();
|
||||||
|
expect(metric.baseline).toBeDefined();
|
||||||
|
expect(Object.keys(metric.baseline ?? {}).sort()).toEqual([
|
||||||
|
'BOTTOM',
|
||||||
|
'JUNGLE',
|
||||||
|
'MIDDLE',
|
||||||
|
'TOP',
|
||||||
|
'UTILITY',
|
||||||
|
]);
|
||||||
|
|
||||||
|
for (const range of Object.values(metric.baseline ?? {})) {
|
||||||
|
expect(range.min).toBeLessThan(range.max);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('marks deaths per minute as lower-is-better for strength scoring', () => {
|
||||||
|
expect(
|
||||||
|
METRICS.find((metric) => metric.id === 'deathsPerMin')?.direction,
|
||||||
|
).toBe('lowerIsBetter');
|
||||||
|
expect(
|
||||||
|
METRICS.find((metric) => metric.id === 'deathWithShutdownBountyGivenRate')
|
||||||
|
?.direction,
|
||||||
|
).toBe('lowerIsBetter');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defines MVP 2 timeline metric aggregation contracts', () => {
|
||||||
|
expect(
|
||||||
|
MVP_2_TIMELINE_METRIC_IDS.map((metricId) => {
|
||||||
|
const metric = METRICS.find((candidate) => candidate.id === metricId);
|
||||||
|
return {
|
||||||
|
id: metric?.id,
|
||||||
|
kind: metric?.kind,
|
||||||
|
direction: metric?.direction,
|
||||||
|
includeInVector: metric?.includeInVector,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
).toEqual(
|
||||||
|
MVP_2_TIMELINE_METRIC_CONTRACTS.map((metric) => ({
|
||||||
|
...metric,
|
||||||
|
includeInVector: true,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defines MVP 2 insight metric aggregation contracts outside the vector', () => {
|
||||||
|
expect(
|
||||||
|
MVP_2_INSIGHT_METRIC_IDS.map((metricId) => {
|
||||||
|
const metric = METRICS.find((candidate) => candidate.id === metricId);
|
||||||
|
return {
|
||||||
|
id: metric?.id,
|
||||||
|
kind: metric?.kind,
|
||||||
|
direction: metric?.direction,
|
||||||
|
includeInVector: metric?.includeInVector,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
).toEqual(
|
||||||
|
MVP_2_INSIGHT_METRIC_CONTRACTS.map((metric) => ({
|
||||||
|
...metric,
|
||||||
|
includeInVector: false,
|
||||||
|
})),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defines shared advantage event weights for timeline-derived metrics', () => {
|
||||||
|
expect(ADVANTAGE_EVENT_WEIGHTS).toEqual({
|
||||||
|
championKill: 1,
|
||||||
|
turretPlate: 0.5,
|
||||||
|
tower: 1.5,
|
||||||
|
dragon: 1.5,
|
||||||
|
riftHerald: 1.5,
|
||||||
|
baron: 3,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defines shared Summoner Rift map zones for timeline-derived metrics', () => {
|
||||||
|
expect(SUMMONERS_RIFT_MAP_ZONES).toEqual([
|
||||||
|
'blueBase',
|
||||||
|
'redBase',
|
||||||
|
'topLane',
|
||||||
|
'middleLane',
|
||||||
|
'bottomLane',
|
||||||
|
'river',
|
||||||
|
'northWestJungle',
|
||||||
|
'northEastJungle',
|
||||||
|
'southWestJungle',
|
||||||
|
'southEastJungle',
|
||||||
|
'dragonPit',
|
||||||
|
'baronPit',
|
||||||
|
'unknown',
|
||||||
|
]);
|
||||||
|
expect(SUMMONERS_RIFT_MAP).toEqual({
|
||||||
|
coordinateMin: 0,
|
||||||
|
coordinateMax: 15_000,
|
||||||
|
laneAxisHalfWidth: 1_500,
|
||||||
|
riverBandHalfWidth: 1_500,
|
||||||
|
jungleMidline: 7_500,
|
||||||
|
baseRadius: 2_200,
|
||||||
|
objectivePitRadius: 2_500,
|
||||||
|
dragonPit: { x: 9_866, y: 4_414 },
|
||||||
|
baronPit: { x: 5_007, y: 10_471 },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('shared DTO contracts', () => {
|
||||||
|
it('exports request, job status, and player analysis DTO shapes', () => {
|
||||||
|
const request: AnalysisRequestDto = {
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
platform: 'ph2',
|
||||||
|
matchCount: 20,
|
||||||
|
};
|
||||||
|
const jobStatus: AnalysisJobStatusDto = {
|
||||||
|
jobId: 'job-1',
|
||||||
|
status: 'processing',
|
||||||
|
stage: 'fetch-match-details',
|
||||||
|
puuid: 'puuid-1',
|
||||||
|
progress: { fetchedMatches: 3, totalMatches: 20 },
|
||||||
|
error: null,
|
||||||
|
};
|
||||||
|
const accepted: AnalysisRequestAcceptedDto = {
|
||||||
|
jobId: 'job-1',
|
||||||
|
status: 'queued',
|
||||||
|
};
|
||||||
|
const playstyle = Object.fromEntries(
|
||||||
|
MVP_2_METRIC_IDS.map((metricId) => [metricId, 0.5]),
|
||||||
|
) as PlayerAnalysisDto['profile']['playstyle'];
|
||||||
|
const analysis: PlayerAnalysisDto = {
|
||||||
|
account: {
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
profileIconId: 1,
|
||||||
|
tiers: [],
|
||||||
|
},
|
||||||
|
profile: {
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
queueId: 420,
|
||||||
|
sampleGameCount: 12,
|
||||||
|
championPool: [{ championId: 103, games: 4, wins: 3 }],
|
||||||
|
playstyle,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
confidence: 0.9,
|
||||||
|
},
|
||||||
|
strengths: [{ metricId: 'kda', value: 0.6 }],
|
||||||
|
weaknesses: [{ metricId: 'deathsPerMin', value: 0.7 }],
|
||||||
|
updatedAt: '2026-07-02T00:00:00.000Z',
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(request.platform).toBe('ph2');
|
||||||
|
expect(accepted.status).toBe('queued');
|
||||||
|
expect(jobStatus.progress.totalMatches).toBe(20);
|
||||||
|
expect(analysis.profile.mainRole).toBe('MIDDLE');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,26 +1,638 @@
|
|||||||
|
import { getQueueToken } from '@nestjs/bullmq';
|
||||||
import { Test, TestingModule } from '@nestjs/testing';
|
import { Test, TestingModule } from '@nestjs/testing';
|
||||||
import { INestApplication } from '@nestjs/common';
|
import { INestApplication } from '@nestjs/common';
|
||||||
|
import {
|
||||||
|
FEATURE_SCHEMA_VERSION,
|
||||||
|
type PlayerAnalysisDto,
|
||||||
|
type SimilarPlayersDto,
|
||||||
|
} from '@persona-lenz/shared';
|
||||||
import request from 'supertest';
|
import request from 'supertest';
|
||||||
import { App } from 'supertest/types';
|
import { App } from 'supertest/types';
|
||||||
|
import { configureApp } from './../src/app.setup';
|
||||||
import { AppModule } from './../src/app.module';
|
import { AppModule } from './../src/app.module';
|
||||||
|
import { AnalysisQueueService } from './../src/modules/analysis/analysis-queue.service';
|
||||||
|
import {
|
||||||
|
ANALYSIS_QUEUE_NAME,
|
||||||
|
SEED_COLLECTION_QUEUE_NAME,
|
||||||
|
} from './../src/modules/analysis/analysis.constants';
|
||||||
|
import { SimilarPlayerService } from './../src/modules/analysis/similar-player.service';
|
||||||
|
import { ConnectionService } from './../src/modules/global/database/connection.service';
|
||||||
|
import { REDIS_CLIENT } from './../src/modules/global/redis/redis.constants';
|
||||||
|
import { SecretService } from './../src/modules/global/secret/secret.service';
|
||||||
|
|
||||||
describe('AppController (e2e)', () => {
|
describe('AppController (e2e)', () => {
|
||||||
let app: INestApplication<App>;
|
let app: INestApplication<App>;
|
||||||
|
let analysisQueueService: {
|
||||||
|
enqueueUserAnalysis: jest.Mock;
|
||||||
|
enqueueSeedCollection: jest.Mock;
|
||||||
|
};
|
||||||
|
let similarPlayerService: {
|
||||||
|
findSimilarPlayers: jest.Mock;
|
||||||
|
};
|
||||||
|
let connectionService: {
|
||||||
|
getModel: jest.Mock;
|
||||||
|
};
|
||||||
|
|
||||||
|
function createLeanExec<T>(value: T) {
|
||||||
|
return {
|
||||||
|
lean: jest.fn(() => ({
|
||||||
|
exec: jest.fn().mockResolvedValue(value),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
|
analysisQueueService = {
|
||||||
|
enqueueUserAnalysis: jest.fn(),
|
||||||
|
enqueueSeedCollection: jest.fn(),
|
||||||
|
};
|
||||||
|
similarPlayerService = {
|
||||||
|
findSimilarPlayers: jest.fn(),
|
||||||
|
};
|
||||||
|
connectionService = {
|
||||||
|
getModel: jest.fn(),
|
||||||
|
};
|
||||||
const moduleFixture: TestingModule = await Test.createTestingModule({
|
const moduleFixture: TestingModule = await Test.createTestingModule({
|
||||||
imports: [AppModule],
|
imports: [AppModule],
|
||||||
}).compile();
|
})
|
||||||
|
.overrideProvider(ConnectionService)
|
||||||
|
.useValue(connectionService)
|
||||||
|
.overrideProvider(AnalysisQueueService)
|
||||||
|
.useValue(analysisQueueService)
|
||||||
|
.overrideProvider(SimilarPlayerService)
|
||||||
|
.useValue(similarPlayerService)
|
||||||
|
.overrideProvider(SecretService)
|
||||||
|
.useValue({
|
||||||
|
get: jest.fn((key: string) => {
|
||||||
|
if (key === 'REDIS_URL') {
|
||||||
|
return Promise.resolve('redis://localhost:6379/0');
|
||||||
|
}
|
||||||
|
if (key === 'ADMIN_API_TOKEN') {
|
||||||
|
return Promise.resolve('admin-token');
|
||||||
|
}
|
||||||
|
return Promise.resolve('');
|
||||||
|
}),
|
||||||
|
ready: jest.fn().mockResolvedValue(undefined),
|
||||||
|
})
|
||||||
|
.overrideProvider(REDIS_CLIENT)
|
||||||
|
.useValue({
|
||||||
|
destroy: jest.fn(),
|
||||||
|
quit: jest.fn().mockResolvedValue(undefined),
|
||||||
|
})
|
||||||
|
.overrideProvider(getQueueToken(ANALYSIS_QUEUE_NAME))
|
||||||
|
.useValue({
|
||||||
|
add: jest.fn(),
|
||||||
|
})
|
||||||
|
.overrideProvider(getQueueToken(SEED_COLLECTION_QUEUE_NAME))
|
||||||
|
.useValue({
|
||||||
|
add: jest.fn(),
|
||||||
|
})
|
||||||
|
.compile();
|
||||||
|
|
||||||
app = moduleFixture.createNestApplication();
|
app = moduleFixture.createNestApplication();
|
||||||
|
configureApp(app);
|
||||||
await app.init();
|
await app.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('/ (GET)', () => {
|
it('/api/health (GET)', () => {
|
||||||
return request(app.getHttpServer())
|
return request(app.getHttpServer())
|
||||||
.get('/')
|
.get('/api/health')
|
||||||
.expect(200)
|
.expect(200)
|
||||||
.expect('Hello World!');
|
.expect({ status: 'ok' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/analysis/request (POST) validates and enqueues analysis requests', async () => {
|
||||||
|
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
status: 'queued',
|
||||||
|
});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/analysis/request')
|
||||||
|
.send({
|
||||||
|
gameName: ' Hide on bush ',
|
||||||
|
ignored: 'field',
|
||||||
|
matchCount: 999,
|
||||||
|
tagLine: ' KR1 ',
|
||||||
|
})
|
||||||
|
.expect(202)
|
||||||
|
.expect({
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
status: 'queued',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(analysisQueueService.enqueueUserAnalysis).toHaveBeenCalledWith({
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
platformRoute: 'kr',
|
||||||
|
regionalRoute: 'asia',
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount: 50,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/analysis/request (POST) maps non-default platforms to regional routes', async () => {
|
||||||
|
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
status: 'queued',
|
||||||
|
});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/analysis/request')
|
||||||
|
.send({
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
matchCount: 0,
|
||||||
|
platform: 'ph2',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
})
|
||||||
|
.expect(202);
|
||||||
|
|
||||||
|
expect(analysisQueueService.enqueueUserAnalysis).toHaveBeenCalledWith({
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
platformRoute: 'ph2',
|
||||||
|
regionalRoute: 'sea',
|
||||||
|
queueId: 420,
|
||||||
|
requestedMatchCount: 1,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['short gameName', { gameName: 'x', tagLine: 'KR1' }],
|
||||||
|
['missing tagLine', { gameName: 'Hide on bush' }],
|
||||||
|
['long tagLine', { gameName: 'Hide on bush', tagLine: 'TOOLONG' }],
|
||||||
|
[
|
||||||
|
'unsupported platform',
|
||||||
|
{ gameName: 'Hide on bush', platform: 'bad', tagLine: 'KR1' },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'non-number matchCount',
|
||||||
|
{ gameName: 'Hide on bush', matchCount: '20', tagLine: 'KR1' },
|
||||||
|
],
|
||||||
|
])('/api/analysis/request (POST) rejects %s', async (_label, body) => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/analysis/request')
|
||||||
|
.send(body)
|
||||||
|
.expect(400);
|
||||||
|
|
||||||
|
expect(analysisQueueService.enqueueUserAnalysis).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/analysis/request (POST) throttles repeated accepted requests', async () => {
|
||||||
|
analysisQueueService.enqueueUserAnalysis.mockResolvedValue({
|
||||||
|
jobId: 'analysis-job-1',
|
||||||
|
status: 'queued',
|
||||||
|
});
|
||||||
|
|
||||||
|
for (let index = 0; index < 10; index += 1) {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/analysis/request')
|
||||||
|
.send({
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
})
|
||||||
|
.expect(202);
|
||||||
|
}
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/analysis/request')
|
||||||
|
.send({
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
})
|
||||||
|
.expect(429);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/admin/seed-collection/request (POST) validates admin token and enqueues seed collection', async () => {
|
||||||
|
analysisQueueService.enqueueSeedCollection.mockResolvedValue({
|
||||||
|
jobId: 'seed-job-1',
|
||||||
|
status: 'queued',
|
||||||
|
});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/seed-collection/request')
|
||||||
|
.set('Authorization', 'Bearer admin-token')
|
||||||
|
.send({
|
||||||
|
platform: 'kr',
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: 0,
|
||||||
|
grandmaster: 25,
|
||||||
|
master: 0,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.expect(202)
|
||||||
|
.expect({
|
||||||
|
jobId: 'seed-job-1',
|
||||||
|
status: 'queued',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(analysisQueueService.enqueueSeedCollection).toHaveBeenCalledWith({
|
||||||
|
platformRoute: 'kr',
|
||||||
|
queueId: 420,
|
||||||
|
sourceLimits: {
|
||||||
|
challenger: 0,
|
||||||
|
grandmaster: 25,
|
||||||
|
master: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/admin/seed-collection/request (POST) rejects missing admin token', async () => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/seed-collection/request')
|
||||||
|
.send({
|
||||||
|
sourceLimits: {
|
||||||
|
grandmaster: 25,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.expect(401);
|
||||||
|
|
||||||
|
expect(analysisQueueService.enqueueSeedCollection).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['unsupported source', { sourceLimits: { diamond: 10 } }],
|
||||||
|
['negative source limit', { sourceLimits: { grandmaster: -1 } }],
|
||||||
|
['fractional source limit', { sourceLimits: { grandmaster: 1.5 } }],
|
||||||
|
['oversized source limit', { sourceLimits: { grandmaster: 201 } }],
|
||||||
|
['unsupported queue', { queueId: 440 }],
|
||||||
|
])(
|
||||||
|
'/api/admin/seed-collection/request (POST) rejects %s',
|
||||||
|
async (_label, body) => {
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.post('/api/admin/seed-collection/request')
|
||||||
|
.set('Authorization', 'Bearer admin-token')
|
||||||
|
.send(body)
|
||||||
|
.expect(400);
|
||||||
|
|
||||||
|
expect(analysisQueueService.enqueueSeedCollection).not.toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it('/api/analysis/jobs/:jobId (GET) returns job statuses', async () => {
|
||||||
|
const records = new Map([
|
||||||
|
[
|
||||||
|
'queued-job',
|
||||||
|
{
|
||||||
|
error: undefined,
|
||||||
|
jobId: 'queued-job',
|
||||||
|
progress: { fetchedMatches: 0, totalMatches: 0 },
|
||||||
|
status: 'queued',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'completed-job',
|
||||||
|
{
|
||||||
|
error: undefined,
|
||||||
|
jobId: 'completed-job',
|
||||||
|
progress: { fetchedMatches: 20, totalMatches: 20 },
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
stage: 'completed',
|
||||||
|
status: 'completed',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'failed-job',
|
||||||
|
{
|
||||||
|
error: 'internal redis hostname leaked',
|
||||||
|
jobId: 'failed-job',
|
||||||
|
progress: { fetchedMatches: 4, totalMatches: 20 },
|
||||||
|
stage: 'fetch-match-details',
|
||||||
|
status: 'failed',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
]);
|
||||||
|
const findOne = jest.fn(({ jobId }: { jobId: string }) =>
|
||||||
|
createLeanExec(records.get(jobId) ?? null),
|
||||||
|
);
|
||||||
|
connectionService.getModel.mockResolvedValue({
|
||||||
|
findOne,
|
||||||
|
});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/api/analysis/jobs/queued-job')
|
||||||
|
.expect(200)
|
||||||
|
.expect({
|
||||||
|
error: null,
|
||||||
|
jobId: 'queued-job',
|
||||||
|
progress: { fetchedMatches: 0, totalMatches: 0 },
|
||||||
|
status: 'queued',
|
||||||
|
});
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/api/analysis/jobs/completed-job')
|
||||||
|
.expect(200)
|
||||||
|
.expect({
|
||||||
|
error: null,
|
||||||
|
jobId: 'completed-job',
|
||||||
|
progress: { fetchedMatches: 20, totalMatches: 20 },
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
stage: 'completed',
|
||||||
|
status: 'completed',
|
||||||
|
});
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/api/analysis/jobs/failed-job')
|
||||||
|
.expect(200)
|
||||||
|
.expect({
|
||||||
|
error: 'Analysis failed during processing.',
|
||||||
|
jobId: 'failed-job',
|
||||||
|
progress: { fetchedMatches: 4, totalMatches: 20 },
|
||||||
|
stage: 'fetch-match-details',
|
||||||
|
status: 'failed',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(findOne).toHaveBeenCalledWith({ jobId: 'queued-job' });
|
||||||
|
expect(findOne).toHaveBeenCalledWith({ jobId: 'completed-job' });
|
||||||
|
expect(findOne).toHaveBeenCalledWith({ jobId: 'failed-job' });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/analysis/jobs/:jobId (GET) returns 404 for missing jobs', async () => {
|
||||||
|
connectionService.getModel.mockResolvedValue({
|
||||||
|
findOne: jest.fn(() => createLeanExec(null)),
|
||||||
|
});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/api/analysis/jobs/missing-job')
|
||||||
|
.expect(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/players/:puuid/analysis/latest (GET) returns latest analysis', async () => {
|
||||||
|
const accountFindOne = jest.fn(() =>
|
||||||
|
createLeanExec({
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
profileIconId: 1,
|
||||||
|
tagLine: 'KR1',
|
||||||
|
tiers: [
|
||||||
|
{
|
||||||
|
fetchedAt: new Date('2026-07-01T00:00:00.000Z'),
|
||||||
|
leaguePoints: 100,
|
||||||
|
losses: 5,
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
rank: 'I',
|
||||||
|
tier: 'MASTER',
|
||||||
|
wins: 10,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const profileFindOne = jest.fn(() =>
|
||||||
|
createLeanExec({
|
||||||
|
championPool: [{ championId: 103, games: 4, wins: 3 }],
|
||||||
|
confidence: 0.9,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
profile: {
|
||||||
|
kda: 0.8,
|
||||||
|
killParticipation: 0.7,
|
||||||
|
damageShare: 0.6,
|
||||||
|
damagePerMin: 0.5,
|
||||||
|
goldPerMin: 0.4,
|
||||||
|
csPerMin: 0.3,
|
||||||
|
visionScorePerMin: 0.2,
|
||||||
|
wardsKilledPerMin: 0.1,
|
||||||
|
controlWardsPlaced: 0.2,
|
||||||
|
deathsPerMin: 0.1,
|
||||||
|
objectiveParticipation: 0.6,
|
||||||
|
soloKills: 0.4,
|
||||||
|
},
|
||||||
|
queueId: 420,
|
||||||
|
sampleGameCount: 12,
|
||||||
|
updatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
connectionService.getModel.mockImplementation((modelKey: string) => {
|
||||||
|
if (modelKey === 'account') {
|
||||||
|
return Promise.resolve({
|
||||||
|
findOne: accountFindOne,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (modelKey !== 'playerProfile') {
|
||||||
|
throw new Error(`Unexpected model ${modelKey}`);
|
||||||
|
}
|
||||||
|
return Promise.resolve({
|
||||||
|
findOne: profileFindOne,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.get('/api/players/target-puuid/analysis/latest')
|
||||||
|
.expect(200);
|
||||||
|
const responseBody = response.body as PlayerAnalysisDto;
|
||||||
|
|
||||||
|
expect(accountFindOne).toHaveBeenCalledWith({ puuid: 'target-puuid' });
|
||||||
|
expect(profileFindOne).toHaveBeenCalledWith({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
});
|
||||||
|
expect(responseBody).toMatchObject({
|
||||||
|
account: {
|
||||||
|
gameName: 'Hide on bush',
|
||||||
|
profileIconId: 1,
|
||||||
|
tagLine: 'KR1',
|
||||||
|
tiers: [
|
||||||
|
{
|
||||||
|
fetchedAt: '2026-07-01T00:00:00.000Z',
|
||||||
|
leaguePoints: 100,
|
||||||
|
losses: 5,
|
||||||
|
queueType: 'RANKED_SOLO_5x5',
|
||||||
|
rank: 'I',
|
||||||
|
tier: 'MASTER',
|
||||||
|
wins: 10,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
profile: {
|
||||||
|
championPool: [{ championId: 103, games: 4, wins: 3 }],
|
||||||
|
confidence: 0.9,
|
||||||
|
featureSchemaVersion: FEATURE_SCHEMA_VERSION,
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
playstyle: {
|
||||||
|
kda: 0.8,
|
||||||
|
killParticipation: 0.7,
|
||||||
|
damageShare: 0.6,
|
||||||
|
damagePerMin: 0.5,
|
||||||
|
goldPerMin: 0.4,
|
||||||
|
csPerMin: 0.3,
|
||||||
|
visionScorePerMin: 0.2,
|
||||||
|
wardsKilledPerMin: 0.1,
|
||||||
|
controlWardsPlaced: 0.2,
|
||||||
|
deathsPerMin: 0.1,
|
||||||
|
objectiveParticipation: 0.6,
|
||||||
|
soloKills: 0.4,
|
||||||
|
},
|
||||||
|
queueId: 420,
|
||||||
|
sampleGameCount: 12,
|
||||||
|
},
|
||||||
|
updatedAt: '2026-07-02T00:00:00.000Z',
|
||||||
|
});
|
||||||
|
expect(responseBody.strengths).toHaveLength(12);
|
||||||
|
expect(responseBody.weaknesses).toHaveLength(12);
|
||||||
|
expect(responseBody.strengths).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
{ metricId: 'deathsPerMin', value: 0.1 },
|
||||||
|
{ metricId: 'kda', value: 0.8 },
|
||||||
|
{ metricId: 'killParticipation', value: 0.7 },
|
||||||
|
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(responseBody.weaknesses).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
||||||
|
{ metricId: 'visionScorePerMin', value: 0.2 },
|
||||||
|
{ metricId: 'controlWardsPlaced', value: 0.2 },
|
||||||
|
{ metricId: 'deathsPerMin', value: 0.1 },
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
expect(responseBody.strengths.slice(0, 3)).toEqual([
|
||||||
|
{ metricId: 'deathsPerMin', value: 0.1 },
|
||||||
|
{ metricId: 'kda', value: 0.8 },
|
||||||
|
{ metricId: 'killParticipation', value: 0.7 },
|
||||||
|
]);
|
||||||
|
expect(responseBody.weaknesses.slice(0, 3)).toEqual([
|
||||||
|
{ metricId: 'wardsKilledPerMin', value: 0.1 },
|
||||||
|
{ metricId: 'visionScorePerMin', value: 0.2 },
|
||||||
|
{ metricId: 'controlWardsPlaced', value: 0.2 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/players/:puuid/analysis/latest (GET) returns 404 without a profile', async () => {
|
||||||
|
connectionService.getModel.mockImplementation((modelKey: string) => {
|
||||||
|
if (modelKey === 'playerProfile') {
|
||||||
|
return Promise.resolve({
|
||||||
|
findOne: jest.fn(() => createLeanExec(null)),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.resolve({
|
||||||
|
findOne: jest.fn(() => createLeanExec({})),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
await request(app.getHttpServer())
|
||||||
|
.get('/api/players/target-puuid/analysis/latest')
|
||||||
|
.expect(404)
|
||||||
|
.expect((response) => {
|
||||||
|
expect(response.body).toMatchObject({
|
||||||
|
message: '분석할 랭크 게임이 없음',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('/api/players/:puuid/similar-players (GET) returns similar players with display Riot IDs', async () => {
|
||||||
|
similarPlayerService.findSimilarPlayers.mockResolvedValue({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
profileUpdatedAt: new Date('2026-07-02T00:00:00.000Z'),
|
||||||
|
matches: [
|
||||||
|
{
|
||||||
|
puuid: 'similar-player-puuid',
|
||||||
|
similarityScore: 0.87,
|
||||||
|
finalScore: 0.81,
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
leaguePoints: 900,
|
||||||
|
tierComparison: 'higher',
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
|
||||||
|
sampleGameCount: 40,
|
||||||
|
similarMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'kda',
|
||||||
|
currentValue: 0.3,
|
||||||
|
otherValue: 0.31,
|
||||||
|
absoluteGap: 0.01,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
strongerMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'goldPerMin',
|
||||||
|
currentValue: 0.5,
|
||||||
|
otherValue: 0.8,
|
||||||
|
lead: 0.3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
weakerMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'visionScorePerMin',
|
||||||
|
currentValue: 0.6,
|
||||||
|
otherValue: 0.4,
|
||||||
|
lead: 0.2,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const accountFind = jest.fn(() =>
|
||||||
|
createLeanExec([
|
||||||
|
{
|
||||||
|
puuid: 'similar-player-puuid',
|
||||||
|
gameName: '프리리',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
connectionService.getModel.mockResolvedValue({
|
||||||
|
find: accountFind,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await request(app.getHttpServer())
|
||||||
|
.get('/api/players/target-puuid/similar-players?limit=3')
|
||||||
|
.expect(200);
|
||||||
|
const responseBody = response.body as SimilarPlayersDto;
|
||||||
|
|
||||||
|
expect(similarPlayerService.findSimilarPlayers).toHaveBeenCalledWith(
|
||||||
|
'target-puuid',
|
||||||
|
420,
|
||||||
|
3,
|
||||||
|
);
|
||||||
|
expect(accountFind).toHaveBeenCalledWith({
|
||||||
|
puuid: { $in: ['similar-player-puuid'] },
|
||||||
|
});
|
||||||
|
expect(responseBody).toEqual({
|
||||||
|
puuid: 'target-puuid',
|
||||||
|
queueId: 420,
|
||||||
|
profileUpdatedAt: '2026-07-02T00:00:00.000Z',
|
||||||
|
matches: [
|
||||||
|
{
|
||||||
|
displayId: 'similar-1',
|
||||||
|
riotId: {
|
||||||
|
gameName: '프리리',
|
||||||
|
tagLine: 'KR1',
|
||||||
|
},
|
||||||
|
similarityScore: 0.87,
|
||||||
|
finalScore: 0.81,
|
||||||
|
tier: 'CHALLENGER',
|
||||||
|
leaguePoints: 900,
|
||||||
|
tierComparison: 'higher',
|
||||||
|
mainRole: 'MIDDLE',
|
||||||
|
mainChampions: [{ championId: 103, games: 20, wins: 14 }],
|
||||||
|
sampleGameCount: 40,
|
||||||
|
similarMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'kda',
|
||||||
|
currentValue: 0.3,
|
||||||
|
otherValue: 0.31,
|
||||||
|
absoluteGap: 0.01,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
strongerMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'goldPerMin',
|
||||||
|
currentValue: 0.5,
|
||||||
|
otherValue: 0.8,
|
||||||
|
lead: 0.3,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
weakerMetrics: [
|
||||||
|
{
|
||||||
|
metricId: 'visionScorePerMin',
|
||||||
|
currentValue: 0.6,
|
||||||
|
otherValue: 0.4,
|
||||||
|
lead: 0.2,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(responseBody.matches[0]).not.toHaveProperty('puuid');
|
||||||
});
|
});
|
||||||
|
|
||||||
afterEach(async () => {
|
afterEach(async () => {
|
||||||
|
|||||||
@@ -1,4 +1,9 @@
|
|||||||
{
|
{
|
||||||
"extends": "./tsconfig.json",
|
"extends": "./tsconfig.json",
|
||||||
|
"compilerOptions": {
|
||||||
|
"rootDir": "./src",
|
||||||
|
"tsBuildInfoFile": "./dist/tsconfig.build.tsbuildinfo"
|
||||||
|
},
|
||||||
|
"include": ["src/**/*.ts"],
|
||||||
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
"exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
|
||||||
}
|
}
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
# React + TypeScript + Vite
|
|
||||||
|
|
||||||
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
|
|
||||||
|
|
||||||
Currently, two official plugins are available:
|
|
||||||
|
|
||||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
|
||||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
|
||||||
|
|
||||||
## React Compiler
|
|
||||||
|
|
||||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
|
||||||
|
|
||||||
## Expanding the ESLint configuration
|
|
||||||
|
|
||||||
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
|
|
||||||
|
|
||||||
```js
|
|
||||||
export default defineConfig([
|
|
||||||
globalIgnores(['dist']),
|
|
||||||
{
|
|
||||||
files: ['**/*.{ts,tsx}'],
|
|
||||||
extends: [
|
|
||||||
// Other configs...
|
|
||||||
|
|
||||||
// Remove tseslint.configs.recommended and replace with this
|
|
||||||
tseslint.configs.recommendedTypeChecked,
|
|
||||||
// Alternatively, use this for stricter rules
|
|
||||||
tseslint.configs.strictTypeChecked,
|
|
||||||
// Optionally, add this for stylistic rules
|
|
||||||
tseslint.configs.stylisticTypeChecked,
|
|
||||||
|
|
||||||
// Other configs...
|
|
||||||
],
|
|
||||||
languageOptions: {
|
|
||||||
parserOptions: {
|
|
||||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
|
||||||
tsconfigRootDir: import.meta.dirname,
|
|
||||||
},
|
|
||||||
// other options...
|
|
||||||
},
|
|
||||||
},
|
|
||||||
])
|
|
||||||
|
|
||||||
```
|
|
||||||
|
|
||||||
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
|
|
||||||
|
|
||||||
```js
|
|
||||||
// eslint.config.js
|
|
||||||
import reactX from 'eslint-plugin-react-x'
|
|
||||||
import reactDom from 'eslint-plugin-react-dom'
|
|
||||||
|
|
||||||
export default defineConfig([
|
|
||||||
globalIgnores(['dist']),
|
|
||||||
{
|
|
||||||
files: ['**/*.{ts,tsx}'],
|
|
||||||
extends: [
|
|
||||||
// Other configs...
|
|
||||||
// Enable lint rules for React
|
|
||||||
reactX.configs['recommended-typescript'],
|
|
||||||
// Enable lint rules for React DOM
|
|
||||||
reactDom.configs.recommended,
|
|
||||||
],
|
|
||||||
languageOptions: {
|
|
||||||
parserOptions: {
|
|
||||||
project: ['./tsconfig.node.json', './tsconfig.app.json'],
|
|
||||||
tsconfigRootDir: import.meta.dirname,
|
|
||||||
},
|
|
||||||
// other options...
|
|
||||||
},
|
|
||||||
},
|
|
||||||
])
|
|
||||||
|
|
||||||
```
|
|
||||||
@@ -19,4 +19,12 @@ export default defineConfig([
|
|||||||
globals: globals.browser,
|
globals: globals.browser,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
// StyleSeed 엔진 (벤더 코드) — shadcn식 variant export·matchMedia 구독 패턴 허용
|
||||||
|
files: ['src/components/ui/**', 'src/motion/**'],
|
||||||
|
rules: {
|
||||||
|
'react-refresh/only-export-components': 'off',
|
||||||
|
'react-hooks/set-state-in-effect': 'off',
|
||||||
|
},
|
||||||
|
},
|
||||||
])
|
])
|
||||||
+4
-3
@@ -1,10 +1,11 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html lang="en">
|
<html lang="ko">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="referrer" content="no-referrer" />
|
||||||
<title>web</title>
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
|
||||||
|
<title>PersonaLenz</title>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
+30
-1
@@ -12,11 +12,39 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@persona-lenz/shared": "workspace:*",
|
"@persona-lenz/shared": "workspace:*",
|
||||||
|
"@radix-ui/react-accordion": "^1.2.3",
|
||||||
|
"@radix-ui/react-avatar": "^1.1.3",
|
||||||
|
"@radix-ui/react-checkbox": "^1.1.4",
|
||||||
|
"@radix-ui/react-dialog": "^1.1.6",
|
||||||
|
"@radix-ui/react-dropdown-menu": "^2.1.6",
|
||||||
|
"@radix-ui/react-label": "^2.1.2",
|
||||||
|
"@radix-ui/react-popover": "^1.1.6",
|
||||||
|
"@radix-ui/react-progress": "^1.1.2",
|
||||||
|
"@radix-ui/react-radio-group": "^1.2.3",
|
||||||
|
"@radix-ui/react-scroll-area": "^1.2.3",
|
||||||
|
"@radix-ui/react-select": "^2.1.6",
|
||||||
|
"@radix-ui/react-separator": "^1.1.2",
|
||||||
|
"@radix-ui/react-slot": "^1.1.2",
|
||||||
|
"@radix-ui/react-switch": "^1.1.3",
|
||||||
|
"@radix-ui/react-tabs": "^1.1.3",
|
||||||
|
"@radix-ui/react-toggle": "^1.1.2",
|
||||||
|
"@radix-ui/react-toggle-group": "^1.1.2",
|
||||||
|
"@radix-ui/react-tooltip": "^1.1.8",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"framer-motion": "^12.23.0",
|
||||||
|
"lucide-react": "^0.487.0",
|
||||||
"react": "^19.2.7",
|
"react": "^19.2.7",
|
||||||
"react-dom": "^19.2.7"
|
"react-dom": "^19.2.7",
|
||||||
|
"react-hook-form": "^7.55.0",
|
||||||
|
"react-router-dom": "^7.18.1",
|
||||||
|
"recharts": "^3.9.1",
|
||||||
|
"tailwind-merge": "^3.2.0",
|
||||||
|
"tw-animate-css": "^1.3.8"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@eslint/js": "^10.0.1",
|
"@eslint/js": "^10.0.1",
|
||||||
|
"@tailwindcss/vite": "^4.1.0",
|
||||||
"@types/node": "^24.13.2",
|
"@types/node": "^24.13.2",
|
||||||
"@types/react": "^19.2.17",
|
"@types/react": "^19.2.17",
|
||||||
"@types/react-dom": "^19.2.3",
|
"@types/react-dom": "^19.2.3",
|
||||||
@@ -25,6 +53,7 @@
|
|||||||
"eslint-plugin-react-hooks": "^7.1.1",
|
"eslint-plugin-react-hooks": "^7.1.1",
|
||||||
"eslint-plugin-react-refresh": "^0.5.3",
|
"eslint-plugin-react-refresh": "^0.5.3",
|
||||||
"globals": "^17.7.0",
|
"globals": "^17.7.0",
|
||||||
|
"tailwindcss": "^4.1.0",
|
||||||
"typescript": "~6.0.2",
|
"typescript": "~6.0.2",
|
||||||
"typescript-eslint": "^8.62.0",
|
"typescript-eslint": "^8.62.0",
|
||||||
"vite": "^8.1.1"
|
"vite": "^8.1.1"
|
||||||
|
|||||||
@@ -1 +1,4 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="46" fill="none" viewBox="0 0 48 46"><path fill="#863bff" d="M25.946 44.938c-.664.845-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.287c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.497 0-3.578-1.842-3.578H1.237c-.92 0-1.456-1.04-.92-1.788L10.013.474c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.579 1.842 3.579h11.377c.943 0 1.473 1.088.89 1.83L25.947 44.94z" style="fill:#863bff;fill:color(display-p3 .5252 .23 1);fill-opacity:1"/><mask id="a" width="48" height="46" x="0" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M25.842 44.938c-.664.844-2.021.375-2.021-.698V33.937a2.26 2.26 0 0 0-2.262-2.262H10.183c-.92 0-1.456-1.04-.92-1.788l7.48-10.471c1.07-1.498 0-3.579-1.842-3.579H1.133c-.92 0-1.456-1.04-.92-1.787L9.91.473c.214-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.471c-1.07 1.498 0 3.578 1.842 3.578h11.377c.943 0 1.473 1.088.89 1.832L25.843 44.94z" style="fill:#000;fill-opacity:1"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#ede6ff" rx="5.508" ry="14.704" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -4.47 31.516)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#ede6ff" rx="10.399" ry="29.851" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -39.328 7.883)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#7e14ff" rx="5.508" ry="30.487" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -25.913 -14.639)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.814 -32.644 -3.334)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#7e14ff" rx="5.508" ry="30.599" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="matrix(.00324 1 1 -.00324 -34.34 30.47)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#ede6ff" rx="14.072" ry="22.078" style="fill:#ede6ff;fill:color(display-p3 .9275 .9033 1);fill-opacity:1" transform="rotate(93.35 24.506 48.493)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#7e14ff" rx="3.47" ry="21.501" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(89.009 28.708 47.59)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx=".387" cy="8.972" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(39.51 .387 8.972)"/></g><g filter="url(#k)"><ellipse cx="47.523" cy="-6.092" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 47.523 -6.092)"/></g><g filter="url(#l)"><ellipse cx="41.412" cy="6.333" fill="#47bfff" rx="5.971" ry="9.665" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 41.412 6.333)"/></g><g filter="url(#m)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#n)"><ellipse cx="-1.879" cy="38.332" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 -1.88 38.332)"/></g><g filter="url(#o)"><ellipse cx="35.651" cy="29.907" fill="#7e14ff" rx="4.407" ry="29.108" style="fill:#7e14ff;fill:color(display-p3 .4922 .0767 1);fill-opacity:1" transform="rotate(37.892 35.651 29.907)"/></g><g filter="url(#p)"><ellipse cx="38.418" cy="32.4" fill="#47bfff" rx="5.971" ry="15.297" style="fill:#47bfff;fill:color(display-p3 .2799 .748 1);fill-opacity:1" transform="rotate(37.892 38.418 32.4)"/></g></g><defs><filter id="b" width="60.045" height="41.654" x="-19.77" y="16.149" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-54.613" y="-7.533" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17158" stdDeviation="7.659"/></filtLine truncated
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||||
|
<rect width="64" height="64" rx="12" fill="#0d1110"/>
|
||||||
|
<path d="M18 44V20h13c5 0 8 3 8 7s-3 7-8 7h-6v10h-7Zm7-16h5c2 0 3-1 3-2s-1-2-3-2h-5v4Zm19 16V20h7v18h9v6H44Z" fill="#4cc9a7"/>
|
||||||
|
</svg>
|
||||||
|
Before Width: | Height: | Size: 9.3 KiB After Width: | Height: | Size: 253 B |
@@ -1,24 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg">
|
|
||||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
|
||||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
|
||||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
|
||||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
|
||||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
|
||||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
|
||||||
</symbol>
|
|
||||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
|
||||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
|
||||||
</symbol>
|
|
||||||
</svg>
|
|
||||||
|
Before Width: | Height: | Size: 4.9 KiB |
@@ -1,184 +0,0 @@
|
|||||||
.counter {
|
|
||||||
font-size: 16px;
|
|
||||||
padding: 5px 10px;
|
|
||||||
border-radius: 5px;
|
|
||||||
color: var(--accent);
|
|
||||||
background: var(--accent-bg);
|
|
||||||
border: 2px solid transparent;
|
|
||||||
transition: border-color 0.3s;
|
|
||||||
margin-bottom: 24px;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
border-color: var(--accent-border);
|
|
||||||
}
|
|
||||||
&:focus-visible {
|
|
||||||
outline: 2px solid var(--accent);
|
|
||||||
outline-offset: 2px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.hero {
|
|
||||||
position: relative;
|
|
||||||
|
|
||||||
.base,
|
|
||||||
.framework,
|
|
||||||
.vite {
|
|
||||||
inset-inline: 0;
|
|
||||||
margin: 0 auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.base {
|
|
||||||
width: 170px;
|
|
||||||
position: relative;
|
|
||||||
z-index: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.framework,
|
|
||||||
.vite {
|
|
||||||
position: absolute;
|
|
||||||
}
|
|
||||||
|
|
||||||
.framework {
|
|
||||||
z-index: 1;
|
|
||||||
top: 34px;
|
|
||||||
height: 28px;
|
|
||||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
|
|
||||||
scale(1.4);
|
|
||||||
}
|
|
||||||
|
|
||||||
.vite {
|
|
||||||
z-index: 0;
|
|
||||||
top: 107px;
|
|
||||||
height: 26px;
|
|
||||||
width: auto;
|
|
||||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
|
|
||||||
scale(0.8);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#center {
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
gap: 25px;
|
|
||||||
place-content: center;
|
|
||||||
place-items: center;
|
|
||||||
flex-grow: 1;
|
|
||||||
|
|
||||||
@media (max-width: 1024px) {
|
|
||||||
padding: 32px 20px 24px;
|
|
||||||
gap: 18px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#next-steps {
|
|
||||||
display: flex;
|
|
||||||
border-top: 1px solid var(--border);
|
|
||||||
text-align: left;
|
|
||||||
|
|
||||||
& > div {
|
|
||||||
flex: 1 1 0;
|
|
||||||
padding: 32px;
|
|
||||||
@media (max-width: 1024px) {
|
|
||||||
padding: 24px 20px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.icon {
|
|
||||||
margin-bottom: 16px;
|
|
||||||
width: 22px;
|
|
||||||
height: 22px;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 1024px) {
|
|
||||||
flex-direction: column;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#docs {
|
|
||||||
border-right: 1px solid var(--border);
|
|
||||||
|
|
||||||
@media (max-width: 1024px) {
|
|
||||||
border-right: none;
|
|
||||||
border-bottom: 1px solid var(--border);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#next-steps ul {
|
|
||||||
list-style: none;
|
|
||||||
padding: 0;
|
|
||||||
display: flex;
|
|
||||||
gap: 8px;
|
|
||||||
margin: 32px 0 0;
|
|
||||||
|
|
||||||
.logo {
|
|
||||||
height: 18px;
|
|
||||||
}
|
|
||||||
|
|
||||||
a {
|
|
||||||
color: var(--text-h);
|
|
||||||
font-size: 16px;
|
|
||||||
border-radius: 6px;
|
|
||||||
background: var(--social-bg);
|
|
||||||
display: flex;
|
|
||||||
padding: 6px 12px;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
text-decoration: none;
|
|
||||||
transition: box-shadow 0.3s;
|
|
||||||
|
|
||||||
&:hover {
|
|
||||||
box-shadow: var(--shadow);
|
|
||||||
}
|
|
||||||
.button-icon {
|
|
||||||
height: 18px;
|
|
||||||
width: 18px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 1024px) {
|
|
||||||
margin-top: 20px;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
justify-content: center;
|
|
||||||
|
|
||||||
li {
|
|
||||||
flex: 1 1 calc(50% - 8px);
|
|
||||||
}
|
|
||||||
|
|
||||||
a {
|
|
||||||
width: 100%;
|
|
||||||
justify-content: center;
|
|
||||||
box-sizing: border-box;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#spacer {
|
|
||||||
height: 88px;
|
|
||||||
border-top: 1px solid var(--border);
|
|
||||||
@media (max-width: 1024px) {
|
|
||||||
height: 48px;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
.ticks {
|
|
||||||
position: relative;
|
|
||||||
width: 100%;
|
|
||||||
|
|
||||||
&::before,
|
|
||||||
&::after {
|
|
||||||
content: '';
|
|
||||||
position: absolute;
|
|
||||||
top: -4.5px;
|
|
||||||
border: 5px solid transparent;
|
|
||||||
}
|
|
||||||
|
|
||||||
&::before {
|
|
||||||
left: 0;
|
|
||||||
border-left-color: var(--border);
|
|
||||||
}
|
|
||||||
&::after {
|
|
||||||
right: 0;
|
|
||||||
border-right-color: var(--border);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,122 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import reactLogo from './assets/react.svg'
|
|
||||||
import viteLogo from './assets/vite.svg'
|
|
||||||
import heroImg from './assets/hero.png'
|
|
||||||
import './App.css'
|
|
||||||
|
|
||||||
function App() {
|
|
||||||
const [count, setCount] = useState(0)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<section id="center">
|
|
||||||
<div className="hero">
|
|
||||||
<img src={heroImg} className="base" width="170" height="179" alt="" />
|
|
||||||
<img src={reactLogo} className="framework" alt="React logo" />
|
|
||||||
<img src={viteLogo} className="vite" alt="Vite logo" />
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<h1>Get started</h1>
|
|
||||||
<p>
|
|
||||||
Edit <code>src/App.tsx</code> and save to test <code>HMR</code>
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="counter"
|
|
||||||
onClick={() => setCount((count) => count + 1)}
|
|
||||||
>
|
|
||||||
Count is {count}
|
|
||||||
</button>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<div className="ticks"></div>
|
|
||||||
|
|
||||||
<section id="next-steps">
|
|
||||||
<div id="docs">
|
|
||||||
<svg className="icon" role="presentation" aria-hidden="true">
|
|
||||||
<use href="/icons.svg#documentation-icon"></use>
|
|
||||||
</svg>
|
|
||||||
<h2>Documentation</h2>
|
|
||||||
<p>Your questions, answered</p>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
<a href="https://vite.dev/" target="_blank">
|
|
||||||
<img className="logo" src={viteLogo} alt="" />
|
|
||||||
Explore Vite
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<a href="https://react.dev/" target="_blank">
|
|
||||||
<img className="button-icon" src={reactLogo} alt="" />
|
|
||||||
Learn more
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
<div id="social">
|
|
||||||
<svg className="icon" role="presentation" aria-hidden="true">
|
|
||||||
<use href="/icons.svg#social-icon"></use>
|
|
||||||
</svg>
|
|
||||||
<h2>Connect with us</h2>
|
|
||||||
<p>Join the Vite community</p>
|
|
||||||
<ul>
|
|
||||||
<li>
|
|
||||||
<a href="https://github.com/vitejs/vite" target="_blank">
|
|
||||||
<svg
|
|
||||||
className="button-icon"
|
|
||||||
role="presentation"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<use href="/icons.svg#github-icon"></use>
|
|
||||||
</svg>
|
|
||||||
GitHub
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<a href="https://chat.vite.dev/" target="_blank">
|
|
||||||
<svg
|
|
||||||
className="button-icon"
|
|
||||||
role="presentation"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<use href="/icons.svg#discord-icon"></use>
|
|
||||||
</svg>
|
|
||||||
Discord
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<a href="https://x.com/vite_js" target="_blank">
|
|
||||||
<svg
|
|
||||||
className="button-icon"
|
|
||||||
role="presentation"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<use href="/icons.svg#x-icon"></use>
|
|
||||||
</svg>
|
|
||||||
X.com
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
<li>
|
|
||||||
<a href="https://bsky.app/profile/vite.dev" target="_blank">
|
|
||||||
<svg
|
|
||||||
className="button-icon"
|
|
||||||
role="presentation"
|
|
||||||
aria-hidden="true"
|
|
||||||
>
|
|
||||||
<use href="/icons.svg#bluesky-icon"></use>
|
|
||||||
</svg>
|
|
||||||
Bluesky
|
|
||||||
</a>
|
|
||||||
</li>
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<div className="ticks"></div>
|
|
||||||
<section id="spacer"></section>
|
|
||||||
</>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default App
|
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
/* Scaffolded with StyleSeed · github.com/bitjaru/styleseed — safe to remove */
|
||||||
|
import * as React from 'react'
|
||||||
|
import { Routes, Route } from 'react-router-dom'
|
||||||
|
import { HomePage } from '../pages/home'
|
||||||
|
import { AnalysisProgressPage } from '../pages/analysis-progress'
|
||||||
|
|
||||||
|
// recharts를 포함한 대시보드는 무거우므로 분리 로딩 — 홈/진행 화면 첫 로드를 가볍게 유지
|
||||||
|
const PlayerDashboardPage = React.lazy(() =>
|
||||||
|
import('../pages/player-dashboard').then((module) => ({ default: module.PlayerDashboardPage })),
|
||||||
|
)
|
||||||
|
|
||||||
|
export default function App() {
|
||||||
|
return (
|
||||||
|
<Routes>
|
||||||
|
<Route path="/" element={<HomePage />} />
|
||||||
|
<Route path="/analysis/:jobId" element={<AnalysisProgressPage />} />
|
||||||
|
<Route
|
||||||
|
path="/players/:puuid"
|
||||||
|
element={
|
||||||
|
<React.Suspense fallback={<div className="min-h-dvh bg-surface-page" />}>
|
||||||
|
<PlayerDashboardPage />
|
||||||
|
</React.Suspense>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</Routes>
|
||||||
|
)
|
||||||
|
}
|
||||||
Binary file not shown.
|
Before Width: | Height: | Size: 13 KiB |
@@ -1 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
|
||||||
|
Before Width: | Height: | Size: 4.0 KiB |
@@ -1 +0,0 @@
|
|||||||
<svg xmlns="http://www.w3.org/2000/svg" width="77" height="47" fill="none" aria-labelledby="vite-logo-title" viewBox="0 0 77 47"><title id="vite-logo-title">Vite</title><style>.parenthesis{fill:#000}@media (prefers-color-scheme:dark){.parenthesis{fill:#fff}}</style><path fill="#9135ff" d="M40.151 45.71c-.663.844-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.493c-.92 0-1.457-1.04-.92-1.788l7.479-10.471c1.07-1.498 0-3.578-1.842-3.578H15.443c-.92 0-1.456-1.04-.92-1.788l9.696-13.576c.213-.297.556-.474.92-.474h28.894c.92 0 1.456 1.04.92 1.788l-7.48 10.472c-1.07 1.497 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.087.89 1.83L40.153 45.712z"/><mask id="a" width="48" height="47" x="14" y="0" maskUnits="userSpaceOnUse" style="mask-type:alpha"><path fill="#000" d="M40.047 45.71c-.663.843-2.02.374-2.02-.699V34.708a2.26 2.26 0 0 0-2.262-2.262H24.389c-.92 0-1.457-1.04-.92-1.788l7.479-10.472c1.07-1.497 0-3.578-1.842-3.578H15.34c-.92 0-1.456-1.04-.92-1.788l9.696-13.575c.213-.297.556-.474.92-.474H53.93c.92 0 1.456 1.04.92 1.788L47.37 13.03c-1.07 1.498 0 3.578 1.842 3.578h11.376c.944 0 1.474 1.088.89 1.831L40.049 45.712z"/></mask><g mask="url(#a)"><g filter="url(#b)"><ellipse cx="5.508" cy="14.704" fill="#eee6ff" rx="5.508" ry="14.704" transform="rotate(269.814 20.96 11.29)scale(-1 1)"/></g><g filter="url(#c)"><ellipse cx="10.399" cy="29.851" fill="#eee6ff" rx="10.399" ry="29.851" transform="rotate(89.814 -16.902 -8.275)scale(1 -1)"/></g><g filter="url(#d)"><ellipse cx="5.508" cy="30.487" fill="#8900ff" rx="5.508" ry="30.487" transform="rotate(89.814 -19.197 -7.127)scale(1 -1)"/></g><g filter="url(#e)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.928 4.177)scale(1 -1)"/></g><g filter="url(#f)"><ellipse cx="5.508" cy="30.599" fill="#8900ff" rx="5.508" ry="30.599" transform="rotate(89.814 -25.738 5.52)scale(1 -1)"/></g><g filter="url(#g)"><ellipse cx="14.072" cy="22.078" fill="#eee6ff" rx="14.072" ry="22.078" transform="rotate(93.35 31.245 55.578)scale(-1 1)"/></g><g filter="url(#h)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#i)"><ellipse cx="3.47" cy="21.501" fill="#8900ff" rx="3.47" ry="21.501" transform="rotate(89.009 35.419 55.202)scale(-1 1)"/></g><g filter="url(#j)"><ellipse cx="14.592" cy="9.743" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(39.51 14.592 9.743)"/></g><g filter="url(#k)"><ellipse cx="61.728" cy="-5.321" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 61.728 -5.32)"/></g><g filter="url(#l)"><ellipse cx="55.618" cy="7.104" fill="#00c2ff" rx="5.971" ry="9.665" transform="rotate(37.892 55.618 7.104)"/></g><g filter="url(#m)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#n)"><ellipse cx="12.326" cy="39.103" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 12.326 39.103)"/></g><g filter="url(#o)"><ellipse cx="49.857" cy="30.678" fill="#8900ff" rx="4.407" ry="29.108" transform="rotate(37.892 49.857 30.678)"/></g><g filter="url(#p)"><ellipse cx="52.623" cy="33.171" fill="#00c2ff" rx="5.971" ry="15.297" transform="rotate(37.892 52.623 33.17)"/></g></g><path d="M6.919 0c-9.198 13.166-9.252 33.575 0 46.789h6.215c-9.25-13.214-9.196-33.623 0-46.789zm62.424 0h-6.215c9.198 13.166 9.252 33.575 0 46.789h6.215c9.25-13.214 9.196-33.623 0-46.789" class="parenthesis"/><defs><filter id="b" width="60.045" height="41.654" x="-5.564" y="16.92" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="c" width="90.34" height="51.437" x="-40.407" y="-6.762" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="7.659"/></filter><filter id="d" width="79.355" height="29.4" x="-35.435" y="2.801" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="e" width="79.579" height="29.4" x="-30.84" y="20.8" color-interpolation-filters="sRGB" filterUnits="userSpaceOnUse"><feFlood flood-opacity="0" result="BackgroundImageFix"/><feBlend in="SourceGraphic" in2="BackgroundImageFix" result="shape"/><feGaussianBlur result="effect1_foregroundBlur_2002_17286" stdDeviation="4.596"/></filter><filter id="f" width="79.579" height="29.4" x="-29.307" y="21.949" color-interpolation-filters="sRGB" filterUnits="usLine truncated
|
|
||||||
|
Before Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,52 @@
|
|||||||
|
import type { ChampionPoolEntryDto } from '@persona-lenz/shared'
|
||||||
|
import type { ChampionIndex } from '../../lib/ddragon'
|
||||||
|
import { championImageUrl } from '../../lib/ddragon'
|
||||||
|
|
||||||
|
interface ChampionPoolCardProps {
|
||||||
|
championPool: ChampionPoolEntryDto[]
|
||||||
|
champions: ChampionIndex | null
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 분석 표본에 포함된 챔피언 풀 — 판수 내림차순 상위 5개 */
|
||||||
|
export function ChampionPoolCard({ championPool, champions }: ChampionPoolCardProps) {
|
||||||
|
const entries = championPool.slice(0, 5)
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||||
|
<h2 className="text-[18px] font-bold text-text-primary">챔피언 풀</h2>
|
||||||
|
<p className="mt-1 text-[13px] text-text-tertiary">이번 분석 표본에서 많이 플레이한 순이에요.</p>
|
||||||
|
<ul className="mt-4 divide-y divide-border">
|
||||||
|
{entries.map((entry) => {
|
||||||
|
const champion = champions?.byId.get(entry.championId)
|
||||||
|
const winRate = entry.games > 0 ? Math.round((entry.wins / entry.games) * 100) : 0
|
||||||
|
return (
|
||||||
|
<li key={entry.championId} className="flex items-center gap-4 py-3">
|
||||||
|
{champion && champions ? (
|
||||||
|
<img
|
||||||
|
src={championImageUrl(champions.version, champion.slug)}
|
||||||
|
alt=""
|
||||||
|
className="size-10 rounded-lg"
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<span aria-hidden className="size-10 rounded-lg bg-surface-muted" />
|
||||||
|
)}
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-[15px] font-bold text-text-primary">
|
||||||
|
{champion?.name ?? `챔피언 #${entry.championId}`}
|
||||||
|
</p>
|
||||||
|
<p className="text-[13px] tabular-nums text-text-tertiary">
|
||||||
|
{entry.games}전 {entry.wins}승
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<span className="text-[17px] font-bold tabular-nums text-text-primary">
|
||||||
|
{winRate}
|
||||||
|
<span className="text-[11px] font-medium text-text-tertiary">%</span>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import type { MetricId } from '@persona-lenz/shared'
|
||||||
|
import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs'
|
||||||
|
import { METRIC_BY_ID, METRIC_CATEGORIES, displayScore } from '../../lib/metrics'
|
||||||
|
|
||||||
|
interface MetricDetailTabsProps {
|
||||||
|
playstyle: Partial<Record<MetricId, number>>
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 39개 전체 지표를 6개 카테고리 탭으로 드릴다운. 막대는 상태가 아니라 크기이므로 중립색 */
|
||||||
|
export function MetricDetailTabs({ playstyle }: MetricDetailTabsProps) {
|
||||||
|
const categories = METRIC_CATEGORIES.map((category) => ({
|
||||||
|
...category,
|
||||||
|
metrics: category.metricIds
|
||||||
|
.filter((metricId) => playstyle[metricId] != null)
|
||||||
|
.map((metricId) => ({
|
||||||
|
metric: METRIC_BY_ID.get(metricId),
|
||||||
|
metricId,
|
||||||
|
score: displayScore(metricId, playstyle[metricId]!),
|
||||||
|
})),
|
||||||
|
})).filter((category) => category.metrics.length > 0)
|
||||||
|
|
||||||
|
if (categories.length === 0) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||||
|
<h2 className="text-[18px] font-bold text-text-primary">전체 지표</h2>
|
||||||
|
<p className="mt-1 text-[13px] text-text-tertiary">
|
||||||
|
같은 포지션 기준으로 정규화한 0~100 점수예요. 낮을수록 좋은 지표는 반전해서 표시합니다.
|
||||||
|
</p>
|
||||||
|
<Tabs defaultValue={categories[0].id} className="mt-4">
|
||||||
|
<TabsList className="h-auto w-full flex-wrap justify-start">
|
||||||
|
{categories.map((category) => (
|
||||||
|
<TabsTrigger key={category.id} value={category.id}>
|
||||||
|
{category.label}
|
||||||
|
</TabsTrigger>
|
||||||
|
))}
|
||||||
|
</TabsList>
|
||||||
|
{categories.map((category) => (
|
||||||
|
<TabsContent key={category.id} value={category.id}>
|
||||||
|
<ul className="divide-y divide-border">
|
||||||
|
{category.metrics.map(({ metric, metricId, score }) => (
|
||||||
|
<li key={metricId} className="flex items-center gap-6 py-4">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-[15px] font-medium text-text-primary">{metric?.label ?? metricId}</p>
|
||||||
|
<p className="mt-0.5 text-[13px] leading-relaxed text-text-tertiary">{metric?.description}</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex w-32 shrink-0 items-center gap-3 sm:w-44">
|
||||||
|
<div
|
||||||
|
aria-hidden
|
||||||
|
className="h-1.5 flex-1 overflow-hidden rounded-full bg-surface-muted"
|
||||||
|
>
|
||||||
|
<div className="h-full rounded-full bg-primary/40" style={{ width: `${score}%` }} />
|
||||||
|
</div>
|
||||||
|
<span className="w-7 text-right text-[15px] font-bold tabular-nums text-text-primary">
|
||||||
|
{score}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</TabsContent>
|
||||||
|
))}
|
||||||
|
</Tabs>
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
import { TrendingDown, TrendingUp } from 'lucide-react'
|
||||||
|
import type { MetricValueDto } from '@persona-lenz/shared'
|
||||||
|
import { METRIC_BY_ID, displayScore } from '../../lib/metrics'
|
||||||
|
|
||||||
|
interface MetricHighlightsProps {
|
||||||
|
strengths: MetricValueDto[]
|
||||||
|
weaknesses: MetricValueDto[]
|
||||||
|
}
|
||||||
|
|
||||||
|
function HighlightList({ items, tone }: { items: MetricValueDto[]; tone: 'strength' | 'weakness' }) {
|
||||||
|
return (
|
||||||
|
<ol className="mt-5 space-y-5">
|
||||||
|
{items.map(({ metricId, value }, index) => {
|
||||||
|
const metric = METRIC_BY_ID.get(metricId)
|
||||||
|
return (
|
||||||
|
<li key={metricId} className="flex items-start gap-4">
|
||||||
|
<span className="w-5 shrink-0 pt-0.5 text-[15px] font-bold tabular-nums text-text-tertiary">
|
||||||
|
{index + 1}
|
||||||
|
</span>
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<p className="text-[15px] font-bold text-text-primary">{metric?.label ?? metricId}</p>
|
||||||
|
<p className="mt-1 text-[13px] leading-relaxed text-text-tertiary">{metric?.description}</p>
|
||||||
|
</div>
|
||||||
|
<span
|
||||||
|
className={`shrink-0 text-[17px] font-bold tabular-nums ${
|
||||||
|
tone === 'strength' ? 'text-brand' : 'text-warning'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{displayScore(metricId, value)}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ol>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 강점/약점 Top 3 — direction 반영 점수(0~100)와 지표 설명을 함께 보여준다 */
|
||||||
|
export function MetricHighlights({ strengths, weaknesses }: MetricHighlightsProps) {
|
||||||
|
return (
|
||||||
|
<div className="grid gap-6 md:grid-cols-2">
|
||||||
|
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||||
|
<h2 className="flex items-center gap-2 text-[18px] font-bold text-text-primary">
|
||||||
|
<TrendingUp aria-hidden className="size-5 text-brand" />
|
||||||
|
이런 플레이가 강해요
|
||||||
|
</h2>
|
||||||
|
<HighlightList items={strengths.slice(0, 3)} tone="strength" />
|
||||||
|
</section>
|
||||||
|
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||||
|
<h2 className="flex items-center gap-2 text-[18px] font-bold text-text-primary">
|
||||||
|
<TrendingDown aria-hidden className="size-5 text-warning" />
|
||||||
|
여기를 보완하면 좋아요
|
||||||
|
</h2>
|
||||||
|
<HighlightList items={weaknesses.slice(0, 3)} tone="weakness" />
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { PolarAngleAxis, PolarGrid, PolarRadiusAxis, Radar, RadarChart, ResponsiveContainer } from 'recharts'
|
||||||
|
import type { CategoryScore } from '../../lib/metrics'
|
||||||
|
|
||||||
|
interface PlaystyleRadarProps {
|
||||||
|
scores: CategoryScore[]
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 6개 카테고리 집계 점수를 보여주는 플레이스타일 레이더. 대시보드의 focal 요소 */
|
||||||
|
export function PlaystyleRadar({ scores }: PlaystyleRadarProps) {
|
||||||
|
const data = scores.map(({ category, score }) => ({
|
||||||
|
label: category.label,
|
||||||
|
score: score ?? 0,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="h-[300px] w-full" role="img" aria-label="플레이스타일 카테고리 레이더 차트">
|
||||||
|
<ResponsiveContainer width="100%" height="100%">
|
||||||
|
<RadarChart data={data} outerRadius="72%" margin={{ top: 12, right: 24, bottom: 12, left: 24 }}>
|
||||||
|
<PolarGrid stroke="var(--border)" />
|
||||||
|
<PolarAngleAxis
|
||||||
|
dataKey="label"
|
||||||
|
tick={{ fill: 'var(--text-secondary)', fontSize: 13, fontWeight: 500 }}
|
||||||
|
/>
|
||||||
|
<PolarRadiusAxis domain={[0, 100]} tick={false} axisLine={false} />
|
||||||
|
<Radar
|
||||||
|
dataKey="score"
|
||||||
|
stroke="var(--brand)"
|
||||||
|
strokeWidth={2}
|
||||||
|
fill="var(--brand)"
|
||||||
|
fillOpacity={0.16}
|
||||||
|
isAnimationActive={false}
|
||||||
|
/>
|
||||||
|
</RadarChart>
|
||||||
|
</ResponsiveContainer>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { Users } from 'lucide-react'
|
||||||
|
import type { SimilarPlayerDto } from '@persona-lenz/shared'
|
||||||
|
import type { ChampionIndex } from '../../lib/ddragon'
|
||||||
|
import { championImageUrl } from '../../lib/ddragon'
|
||||||
|
import { METRIC_BY_ID, ROLE_LABELS, formatTier } from '../../lib/metrics'
|
||||||
|
|
||||||
|
interface SimilarPlayersSectionProps {
|
||||||
|
players: SimilarPlayerDto[] | null
|
||||||
|
champions: ChampionIndex | null
|
||||||
|
}
|
||||||
|
|
||||||
|
function LeadChips({ player }: { player: SimilarPlayerDto }) {
|
||||||
|
if (player.strongerMetrics.length === 0) return null
|
||||||
|
return (
|
||||||
|
<div className="mt-3 flex flex-wrap items-center gap-2">
|
||||||
|
<span className="text-[13px] text-text-tertiary">이 플레이어가 앞서는 지표</span>
|
||||||
|
{player.strongerMetrics.slice(0, 3).map((lead) => (
|
||||||
|
<span
|
||||||
|
key={lead.metricId}
|
||||||
|
className="rounded-md bg-surface-muted px-2 py-1 text-[13px] font-medium text-text-secondary"
|
||||||
|
>
|
||||||
|
{METRIC_BY_ID.get(lead.metricId)?.label ?? lead.metricId} +{Math.round(lead.lead * 100)}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 나와 비슷한 플레이스타일의 상위 티어 유저 비교 카드 목록 */
|
||||||
|
export function SimilarPlayersSection({ players, champions }: SimilarPlayersSectionProps) {
|
||||||
|
return (
|
||||||
|
<section className="rounded-2xl border border-border bg-card p-6 shadow-[var(--shadow-card)]">
|
||||||
|
<h2 className="text-[18px] font-bold text-text-primary">나와 비슷한 상위 티어 플레이어</h2>
|
||||||
|
<p className="mt-1 text-[13px] text-text-tertiary">
|
||||||
|
플레이스타일 벡터가 가까운 유저 중 더 높은 티어를 우선으로 보여드려요.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{players == null || players.length === 0 ? (
|
||||||
|
<div className="mt-6 flex flex-col items-center rounded-xl bg-surface-subtle px-6 py-10 text-center">
|
||||||
|
<Users aria-hidden className="size-8 text-text-disabled" />
|
||||||
|
<p className="mt-3 text-[15px] font-medium text-text-primary">아직 비교 결과를 준비 중이에요</p>
|
||||||
|
<p className="mt-1 text-[14px] text-text-tertiary">
|
||||||
|
비교 풀이 채워지면 자동으로 나타나요. 다음 분석 때 다시 확인해 주세요.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ul className="mt-5 space-y-4">
|
||||||
|
{players.map((player) => {
|
||||||
|
const name = player.riotId ? `${player.riotId.gameName}#${player.riotId.tagLine}` : player.displayId
|
||||||
|
const tier = formatTier(player.tier, player.division)
|
||||||
|
return (
|
||||||
|
<li key={player.displayId} className="rounded-xl bg-surface-subtle p-5">
|
||||||
|
<div className="flex flex-wrap items-center gap-x-3 gap-y-2">
|
||||||
|
<p className="text-[15px] font-bold text-text-primary">{name}</p>
|
||||||
|
{tier && (
|
||||||
|
<span className="rounded-md bg-surface-muted px-2 py-0.5 text-[13px] font-medium text-text-secondary">
|
||||||
|
{tier}
|
||||||
|
{player.leaguePoints != null ? ` · ${player.leaguePoints}LP` : ''}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{player.tierComparison === 'higher' && (
|
||||||
|
<span className="rounded-md bg-brand-tint px-2 py-0.5 text-[13px] font-bold text-brand">
|
||||||
|
상위 티어
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
<span className="ms-auto text-[15px] font-bold tabular-nums text-text-primary">
|
||||||
|
유사도 {Math.round(player.similarityScore * 100)}
|
||||||
|
<span className="text-[11px] font-medium text-text-tertiary">%</span>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mt-3 flex items-center gap-3">
|
||||||
|
<span className="text-[13px] text-text-tertiary">{ROLE_LABELS[player.mainRole]}</span>
|
||||||
|
<span aria-hidden className="size-0.5 rounded-full bg-text-disabled" />
|
||||||
|
<span className="text-[13px] text-text-tertiary">{player.sampleGameCount}게임 표본</span>
|
||||||
|
{champions && player.mainChampions.length > 0 && (
|
||||||
|
<div className="ms-2 flex items-center gap-1.5">
|
||||||
|
{player.mainChampions.slice(0, 3).map((entry) => {
|
||||||
|
const champion = champions.byId.get(entry.championId)
|
||||||
|
if (!champion) return null
|
||||||
|
return (
|
||||||
|
<img
|
||||||
|
key={entry.championId}
|
||||||
|
src={championImageUrl(champions.version, champion.slug)}
|
||||||
|
alt={champion.name}
|
||||||
|
title={champion.name}
|
||||||
|
className="size-7 rounded-md"
|
||||||
|
loading="lazy"
|
||||||
|
/>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<LeadChips player={player} />
|
||||||
|
</li>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
import type { LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
|
interface NavItem {
|
||||||
|
name: string
|
||||||
|
icon: LucideIcon
|
||||||
|
href?: string
|
||||||
|
onClick?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BottomNavProps extends React.ComponentProps<"nav"> {
|
||||||
|
items: NavItem[]
|
||||||
|
activeIndex?: number
|
||||||
|
maxWidth?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function BottomNav({
|
||||||
|
items,
|
||||||
|
activeIndex = 0,
|
||||||
|
maxWidth = "430px",
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: BottomNavProps) {
|
||||||
|
return (
|
||||||
|
<nav
|
||||||
|
data-slot="bottom-nav"
|
||||||
|
className={cn(
|
||||||
|
"fixed bottom-0 left-0 right-0 bg-card border-t border-surface-muted pb-safe",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="mx-auto flex items-center justify-around px-6 py-3"
|
||||||
|
style={{ maxWidth }}
|
||||||
|
>
|
||||||
|
{items.map((item, index) => {
|
||||||
|
const Icon = item.icon
|
||||||
|
const isActive = index === activeIndex
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={item.name}
|
||||||
|
onClick={item.onClick}
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col items-center gap-1 min-w-11 min-h-11 justify-center",
|
||||||
|
"transition-colors duration-[var(--duration-fast)]",
|
||||||
|
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 rounded-lg",
|
||||||
|
isActive ? "text-brand" : "text-text-disabled",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<Icon className="size-5" strokeWidth={2} />
|
||||||
|
<span className="text-[10px] font-semibold">{item.name}</span>
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { BottomNav }
|
||||||
|
export type { BottomNavProps, NavItem }
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
import type { LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
|
interface BriefingItem {
|
||||||
|
icon: LucideIcon
|
||||||
|
badge: string
|
||||||
|
badgeColor: string
|
||||||
|
title: string
|
||||||
|
description: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BriefingCarouselProps extends React.ComponentProps<"div"> {
|
||||||
|
title?: string
|
||||||
|
items: BriefingItem[]
|
||||||
|
cardWidth?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function BriefingCarousel({
|
||||||
|
title,
|
||||||
|
items,
|
||||||
|
cardWidth = "280px",
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: BriefingCarouselProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="briefing-carousel"
|
||||||
|
className={cn("px-6", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{title && (
|
||||||
|
<h3 className="text-text-primary font-bold text-[18px] leading-snug mb-4">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
)}
|
||||||
|
<div className="flex gap-3 overflow-x-auto pb-2 scrollbar-hide">
|
||||||
|
{items.map((item, index) => {
|
||||||
|
const IconComponent = item.icon
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex-shrink-0 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]"
|
||||||
|
style={{ width: cardWidth }}
|
||||||
|
>
|
||||||
|
<div className="mb-4">
|
||||||
|
<div className="flex items-center gap-1.5 mb-3">
|
||||||
|
<IconComponent
|
||||||
|
className="size-4"
|
||||||
|
style={{ color: item.badgeColor }}
|
||||||
|
strokeWidth={2.5}
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
className="text-[12px] font-bold uppercase tracking-[0.05em]"
|
||||||
|
style={{ color: item.badgeColor }}
|
||||||
|
>
|
||||||
|
{item.badge}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<p className="text-text-primary text-[15px] font-bold mb-2 leading-tight">
|
||||||
|
{item.title}
|
||||||
|
</p>
|
||||||
|
<p className="text-text-tertiary text-[13px]">
|
||||||
|
{item.description}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { BriefingCarousel }
|
||||||
|
export type { BriefingCarouselProps, BriefingItem }
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface ChartStat {
|
||||||
|
label: string
|
||||||
|
value: string | number
|
||||||
|
unit?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ChartCardProps extends React.ComponentProps<"div"> {
|
||||||
|
title?: string
|
||||||
|
headerLeft?: React.ReactNode
|
||||||
|
periods?: string[]
|
||||||
|
activePeriod?: string
|
||||||
|
onPeriodChange?: (period: string) => void
|
||||||
|
stats?: ChartStat[]
|
||||||
|
statsColumns?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function ChartCard({
|
||||||
|
title,
|
||||||
|
headerLeft,
|
||||||
|
periods,
|
||||||
|
activePeriod,
|
||||||
|
onPeriodChange,
|
||||||
|
stats,
|
||||||
|
statsColumns = 3,
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: ChartCardProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="chart-card"
|
||||||
|
className={cn(
|
||||||
|
"mx-6 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between mb-6">
|
||||||
|
<div>
|
||||||
|
{title && (
|
||||||
|
<h3 className="text-text-primary font-bold text-[18px] leading-snug">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
)}
|
||||||
|
{headerLeft}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{periods && (
|
||||||
|
<div className="flex gap-1 bg-surface-muted p-1 rounded-full">
|
||||||
|
{periods.map((period) => (
|
||||||
|
<button
|
||||||
|
key={period}
|
||||||
|
onClick={() => onPeriodChange?.(period)}
|
||||||
|
className={cn(
|
||||||
|
"px-4 py-1.5 text-[11px] font-semibold rounded-full transition-all",
|
||||||
|
activePeriod === period
|
||||||
|
? "bg-brand text-white shadow-sm"
|
||||||
|
: "text-text-tertiary",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{period}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="h-40 -mx-2 mb-6">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{stats && stats.length > 0 && (
|
||||||
|
<div
|
||||||
|
className="gap-3 pt-5 border-t border-surface-muted"
|
||||||
|
style={{
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: `repeat(${statsColumns}, 1fr)`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{stats.map((stat) => (
|
||||||
|
<div key={stat.label} className="text-center">
|
||||||
|
<p className="text-[11px] text-text-secondary mb-2 font-medium uppercase">
|
||||||
|
{stat.label}
|
||||||
|
</p>
|
||||||
|
<p className="text-text-primary font-bold text-[18px] leading-none whitespace-nowrap">
|
||||||
|
{stat.value}
|
||||||
|
{stat.unit && <span className="text-[10px] ms-0.5">{stat.unit}</span>}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ChartCard }
|
||||||
|
export type { ChartCardProps, ChartStat }
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface DonutItem {
|
||||||
|
name: string
|
||||||
|
value: number
|
||||||
|
stock?: string | number
|
||||||
|
unit?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface BottomStat {
|
||||||
|
label: string
|
||||||
|
value: string | number
|
||||||
|
subLabel?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface DonutChartCardProps extends React.ComponentProps<"div"> {
|
||||||
|
title: string
|
||||||
|
centerValue?: string | number
|
||||||
|
centerUnit?: string
|
||||||
|
centerLabel?: string
|
||||||
|
items: DonutItem[]
|
||||||
|
selectedItem?: string | null
|
||||||
|
onItemSelect?: (name: string | null) => void
|
||||||
|
bottomStats?: BottomStat[]
|
||||||
|
bottomColumns?: number
|
||||||
|
chartElement: React.ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
function DonutChartCard({
|
||||||
|
title,
|
||||||
|
centerValue,
|
||||||
|
centerUnit,
|
||||||
|
centerLabel,
|
||||||
|
items,
|
||||||
|
selectedItem,
|
||||||
|
onItemSelect,
|
||||||
|
bottomStats,
|
||||||
|
bottomColumns = 4,
|
||||||
|
chartElement,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: DonutChartCardProps) {
|
||||||
|
const grayColors = ["#D4D4D4", "#A8A8A8", "#8B8B8B", "#6B6B6B"]
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="donut-chart-card"
|
||||||
|
className={cn(
|
||||||
|
"mx-6 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<h3 className="text-text-primary font-bold text-[18px] leading-snug mb-4">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-8">
|
||||||
|
<div className="relative size-32 flex-shrink-0">
|
||||||
|
{chartElement}
|
||||||
|
{(centerValue !== undefined || centerLabel) && (
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center">
|
||||||
|
<div className="text-center">
|
||||||
|
{centerValue !== undefined && (
|
||||||
|
<p className="text-text-primary text-[24px] font-bold leading-none whitespace-nowrap">
|
||||||
|
{centerValue}
|
||||||
|
{centerUnit && <span className="text-[12px] ms-0.5">{centerUnit}</span>}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{centerLabel && (
|
||||||
|
<p className="text-text-tertiary text-[10px] mt-1 font-medium uppercase">
|
||||||
|
{centerLabel}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex-1 space-y-3.5">
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<div
|
||||||
|
key={item.name}
|
||||||
|
className="flex items-center justify-between cursor-pointer transition-all duration-300"
|
||||||
|
onClick={() => onItemSelect?.(selectedItem === item.name ? null : item.name)}
|
||||||
|
style={{
|
||||||
|
opacity: selectedItem === null || selectedItem === undefined || selectedItem === item.name ? 1 : 0.3,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2.5">
|
||||||
|
<div
|
||||||
|
className="size-3 rounded-full transition-all duration-300"
|
||||||
|
style={{
|
||||||
|
backgroundColor: selectedItem === item.name ? "var(--brand)" : grayColors[index % grayColors.length],
|
||||||
|
boxShadow: selectedItem === item.name ? "0 0 0 2px color-mix(in srgb, var(--brand) 25%, transparent)" : "none",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<span className="text-text-primary text-[13px] font-semibold">{item.name}</span>
|
||||||
|
</div>
|
||||||
|
{item.stock !== undefined && (
|
||||||
|
<span className="text-text-primary text-[15px] font-bold whitespace-nowrap">
|
||||||
|
{item.stock}
|
||||||
|
{item.unit && <span className="text-[10px] ms-0.5">{item.unit}</span>}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{bottomStats && bottomStats.length > 0 && (
|
||||||
|
<div
|
||||||
|
className="gap-3 mt-6 pt-6 border-t border-surface-muted"
|
||||||
|
style={{
|
||||||
|
display: "grid",
|
||||||
|
gridTemplateColumns: `repeat(${bottomColumns}, 1fr)`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{bottomStats.map((stat) => (
|
||||||
|
<div key={stat.label} className="text-center">
|
||||||
|
<p className="text-[11px] text-text-secondary mb-1.5 font-medium uppercase">
|
||||||
|
{stat.label}
|
||||||
|
</p>
|
||||||
|
<p className="text-text-primary font-bold text-[20px] leading-none">
|
||||||
|
{stat.value}
|
||||||
|
</p>
|
||||||
|
{stat.subLabel && (
|
||||||
|
<p className="text-[11px] text-text-secondary mt-0.5">{stat.subLabel}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { DonutChartCard }
|
||||||
|
export type { DonutChartCardProps, DonutItem, BottomStat }
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
import type { LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
|
interface EmptyStateProps extends React.ComponentProps<"div"> {
|
||||||
|
icon?: LucideIcon
|
||||||
|
title: string
|
||||||
|
description?: string
|
||||||
|
action?: React.ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
function EmptyState({
|
||||||
|
icon: Icon,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
action,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: EmptyStateProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="empty-state"
|
||||||
|
className={cn(
|
||||||
|
"flex flex-col items-center justify-center py-12 px-6 text-center",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{Icon && (
|
||||||
|
<div className="size-8 rounded-xl bg-surface-muted flex items-center justify-center mb-3">
|
||||||
|
<Icon className="size-4 text-text-tertiary" strokeWidth={1.5} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<h3 className="text-[16px] font-bold text-text-primary tracking-[-0.01em] mb-1.5">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
{description && (
|
||||||
|
<p className="text-[14px] leading-normal text-text-secondary mb-6 max-w-[280px]">
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{action}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { EmptyState }
|
||||||
|
export type { EmptyStateProps }
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
import { TrendingUp, TrendingDown, type LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
|
interface HeroCardProps extends React.ComponentProps<"div"> {
|
||||||
|
icon: LucideIcon
|
||||||
|
label: string
|
||||||
|
value: string | number
|
||||||
|
unit?: string
|
||||||
|
trend?: {
|
||||||
|
value: string
|
||||||
|
direction: "up" | "down"
|
||||||
|
label?: string
|
||||||
|
}
|
||||||
|
backgroundElement?: React.ReactNode
|
||||||
|
watermarkIcon?: LucideIcon
|
||||||
|
}
|
||||||
|
|
||||||
|
function HeroCard({
|
||||||
|
icon: Icon,
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
unit,
|
||||||
|
trend,
|
||||||
|
backgroundElement,
|
||||||
|
watermarkIcon: WatermarkIcon,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: HeroCardProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="hero-card"
|
||||||
|
className={cn(
|
||||||
|
"mx-6 rounded-2xl bg-card p-8 shadow-[var(--shadow-card)] relative overflow-hidden",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{backgroundElement && (
|
||||||
|
<div className="absolute inset-0 opacity-[0.15]">
|
||||||
|
{backgroundElement}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{WatermarkIcon && (
|
||||||
|
<div className="absolute right-6 top-1/2 -translate-y-1/2 opacity-[0.06]">
|
||||||
|
<WatermarkIcon className="size-32 text-brand" strokeWidth={1.5} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="relative z-10">
|
||||||
|
<div className="flex items-center gap-2 mb-3">
|
||||||
|
<div className="size-8 rounded-xl bg-brand/10 flex items-center justify-center">
|
||||||
|
<Icon className="size-[18px] text-brand" strokeWidth={2} />
|
||||||
|
</div>
|
||||||
|
<p className="text-[12px] text-text-secondary font-medium uppercase tracking-[0.05em]">
|
||||||
|
{label}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-text-primary text-[48px] font-bold leading-none tracking-[-0.02em] mb-4 whitespace-nowrap">
|
||||||
|
{value}
|
||||||
|
{unit && <span className="text-[24px] ms-0.5 tracking-normal">{unit}</span>}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{trend && (
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"text-[15px] font-bold",
|
||||||
|
trend.direction === "up" ? "text-success" : "text-destructive",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{trend.value}
|
||||||
|
</span>
|
||||||
|
{trend.direction === "up" ? (
|
||||||
|
<TrendingUp className="size-4 text-success" strokeWidth={2.5} />
|
||||||
|
) : (
|
||||||
|
<TrendingDown className="size-4 text-destructive" strokeWidth={2.5} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{trend.label && (
|
||||||
|
<span className="text-[13px] text-text-tertiary font-medium">
|
||||||
|
{trend.label}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { HeroCard }
|
||||||
|
export type { HeroCardProps }
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
import type { LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
|
interface InsightCardProps extends React.ComponentProps<"div"> {
|
||||||
|
icon?: LucideIcon
|
||||||
|
title: string
|
||||||
|
description: string
|
||||||
|
tags?: { label: string; icon?: LucideIcon }[]
|
||||||
|
action?: React.ReactNode
|
||||||
|
variant?: "default" | "highlighted"
|
||||||
|
}
|
||||||
|
|
||||||
|
function InsightCard({
|
||||||
|
icon: Icon,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
tags,
|
||||||
|
action,
|
||||||
|
variant = "default",
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: InsightCardProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="insight-card"
|
||||||
|
className={cn(
|
||||||
|
"mx-6 rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||||
|
variant === "highlighted"
|
||||||
|
? "bg-brand-tint border border-brand/20"
|
||||||
|
: "bg-card",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{Icon && (
|
||||||
|
<div className="size-8 rounded-xl bg-brand/10 flex items-center justify-center mb-3">
|
||||||
|
<Icon className="size-[18px] text-brand" strokeWidth={2} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<p className="text-text-primary font-bold text-[15px] leading-tight mb-2">
|
||||||
|
{title}
|
||||||
|
</p>
|
||||||
|
<p className="text-text-tertiary text-[13px] leading-normal mb-4">
|
||||||
|
{description}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{tags && tags.length > 0 && (
|
||||||
|
<div className="flex flex-wrap gap-2 mb-4">
|
||||||
|
{tags.map((tag, i) => (
|
||||||
|
<span
|
||||||
|
key={i}
|
||||||
|
className="inline-flex items-center gap-1 px-2.5 py-1 bg-surface-muted rounded-full text-[11px] font-medium text-text-secondary"
|
||||||
|
>
|
||||||
|
{tag.icon && <tag.icon className="size-3" />}
|
||||||
|
{tag.label}
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{action}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { InsightCard }
|
||||||
|
export type { InsightCardProps }
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface ListItemProps extends React.ComponentProps<"div"> {
|
||||||
|
leading?: React.ReactNode
|
||||||
|
title: string
|
||||||
|
subtitle?: React.ReactNode
|
||||||
|
trailing?: React.ReactNode
|
||||||
|
status?: {
|
||||||
|
label: string
|
||||||
|
color: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ListItem({
|
||||||
|
leading,
|
||||||
|
title,
|
||||||
|
subtitle,
|
||||||
|
trailing,
|
||||||
|
status,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: ListItemProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="list-item"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center justify-between p-5 rounded-xl bg-surface-subtle",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3.5">
|
||||||
|
{leading}
|
||||||
|
<div>
|
||||||
|
<p className="text-text-primary font-bold text-[14px] leading-snug mb-1.5">
|
||||||
|
{title}
|
||||||
|
</p>
|
||||||
|
{status && (
|
||||||
|
<div className="inline-flex items-center">
|
||||||
|
<span
|
||||||
|
className="size-1.5 rounded-full me-1.5"
|
||||||
|
style={{ backgroundColor: status.color }}
|
||||||
|
/>
|
||||||
|
<span
|
||||||
|
className="text-[11px] font-bold"
|
||||||
|
style={{ color: status.color }}
|
||||||
|
>
|
||||||
|
{status.label}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{subtitle && !status && (
|
||||||
|
<p className="text-[12px] text-text-secondary">{subtitle}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{trailing && <div className="flex-shrink-0">{trailing}</div>}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ListItem }
|
||||||
|
export type { ListItemProps }
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface NewsCardProps extends React.ComponentProps<"div"> {
|
||||||
|
title: string
|
||||||
|
summary?: string
|
||||||
|
source?: string
|
||||||
|
timestamp?: string
|
||||||
|
trend?: "up" | "down" | "neutral"
|
||||||
|
onClick?: () => void
|
||||||
|
}
|
||||||
|
|
||||||
|
function NewsCard({
|
||||||
|
title,
|
||||||
|
summary,
|
||||||
|
source,
|
||||||
|
timestamp,
|
||||||
|
trend,
|
||||||
|
onClick,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: NewsCardProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="news-card"
|
||||||
|
className={cn(
|
||||||
|
"bg-card rounded-2xl p-5 shadow-[var(--shadow-card)]",
|
||||||
|
onClick && "cursor-pointer active:bg-surface-subtle transition-colors duration-150",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
onClick={onClick}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="flex items-start justify-between gap-3">
|
||||||
|
<div className="flex-1 min-w-0">
|
||||||
|
<p className="text-text-primary font-bold text-[14px] leading-snug line-clamp-2 mb-1.5">
|
||||||
|
{title}
|
||||||
|
</p>
|
||||||
|
{summary && (
|
||||||
|
<p className="text-text-tertiary text-[13px] leading-normal line-clamp-2 mb-2">
|
||||||
|
{summary}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<div className="flex items-center gap-2 text-[11px] text-text-disabled">
|
||||||
|
{source && <span>{source}</span>}
|
||||||
|
{source && timestamp && <span>·</span>}
|
||||||
|
{timestamp && <span>{timestamp}</span>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{trend && trend !== "neutral" && (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"shrink-0 text-[12px] font-bold mt-0.5",
|
||||||
|
trend === "up" ? "text-destructive" : "text-info",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{trend === "up" ? "▲" : "▼"}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { NewsCard }
|
||||||
|
export type { NewsCardProps }
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface PageShellProps extends React.ComponentProps<"div"> {
|
||||||
|
maxWidth?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function PageShell({
|
||||||
|
maxWidth = "430px",
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: PageShellProps) {
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-surface-page" {...props}>
|
||||||
|
<div
|
||||||
|
data-slot="page-shell"
|
||||||
|
className={cn("mx-auto bg-surface-page min-h-screen relative", className)}
|
||||||
|
style={{ maxWidth }}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
type PageContentProps = React.ComponentProps<"main">
|
||||||
|
|
||||||
|
function PageContent({ className, children, ...props }: PageContentProps) {
|
||||||
|
return (
|
||||||
|
<main
|
||||||
|
data-slot="page-content"
|
||||||
|
className={cn("pb-24 space-y-6", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { PageShell, PageContent }
|
||||||
|
export type { PageShellProps, PageContentProps }
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
/* === Linear Progress Bar === */
|
||||||
|
|
||||||
|
interface ProgressBarProps extends React.ComponentProps<"div"> {
|
||||||
|
value: number
|
||||||
|
max?: number
|
||||||
|
height?: string
|
||||||
|
label?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProgressBar({
|
||||||
|
value,
|
||||||
|
max = 100,
|
||||||
|
height = "h-4",
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: ProgressBarProps) {
|
||||||
|
const percent = Math.min(100, Math.max(0, (value / max) * 100))
|
||||||
|
return (
|
||||||
|
<div data-slot="progress-bar" className={cn("", className)} {...props}>
|
||||||
|
<div className={cn("bg-surface-muted rounded-full overflow-hidden", height)}>
|
||||||
|
<div
|
||||||
|
className={cn("bg-brand h-full rounded-full transition-all duration-300")}
|
||||||
|
style={{ width: `${percent}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{label && (
|
||||||
|
<p className="text-[11px] text-text-primary mt-2 font-bold">{label}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* === Discrete Bar Segments (게이지) === */
|
||||||
|
|
||||||
|
interface DiscreteBarProps extends React.ComponentProps<"div"> {
|
||||||
|
total: number
|
||||||
|
filled: number
|
||||||
|
height?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function DiscreteBar({
|
||||||
|
total,
|
||||||
|
filled,
|
||||||
|
height = "h-6",
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: DiscreteBarProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="discrete-bar"
|
||||||
|
className={cn("flex gap-1", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{[...Array(total)].map((_, i) => (
|
||||||
|
<div
|
||||||
|
key={i}
|
||||||
|
className={cn(
|
||||||
|
"flex-1 rounded",
|
||||||
|
height,
|
||||||
|
i < filled ? "bg-brand" : "bg-surface-muted",
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/* === Progress Bar with Label (오늘 방문 스타일) === */
|
||||||
|
|
||||||
|
interface ProgressBarWithLabelProps extends React.ComponentProps<"div"> {
|
||||||
|
value: number
|
||||||
|
max?: number
|
||||||
|
label: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function ProgressBarWithLabel({
|
||||||
|
value,
|
||||||
|
max = 100,
|
||||||
|
label,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: ProgressBarWithLabelProps) {
|
||||||
|
const percent = Math.min(100, Math.max(0, (value / max) * 100))
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="progress-bar-with-label"
|
||||||
|
className={cn("flex items-center gap-2", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="flex-1 bg-surface-muted rounded-full h-4">
|
||||||
|
<div
|
||||||
|
className="bg-brand h-full rounded-full transition-all duration-300"
|
||||||
|
style={{ width: `${percent}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className="text-[11px] text-text-primary font-bold">{label}</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ProgressBar, DiscreteBar, ProgressBarWithLabel }
|
||||||
|
export type { ProgressBarProps, DiscreteBarProps, ProgressBarWithLabelProps }
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface RankedItem {
|
||||||
|
rank: number
|
||||||
|
name: string
|
||||||
|
value: string | number
|
||||||
|
isHighlighted?: boolean
|
||||||
|
badge?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RankedListProps extends React.ComponentProps<"div"> {
|
||||||
|
title: string
|
||||||
|
items: RankedItem[]
|
||||||
|
footer?: React.ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
function RankedList({
|
||||||
|
title,
|
||||||
|
items,
|
||||||
|
footer,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: RankedListProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="ranked-list"
|
||||||
|
className={cn(
|
||||||
|
"mx-6 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<h3 className="text-text-primary font-bold text-[18px] leading-snug mb-5">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
|
||||||
|
<div className="space-y-3">
|
||||||
|
{items.map((item) => (
|
||||||
|
<div
|
||||||
|
key={item.rank}
|
||||||
|
className={cn(
|
||||||
|
"flex items-center justify-between p-5 rounded-xl transition-all",
|
||||||
|
item.isHighlighted
|
||||||
|
? "bg-brand-tint border-2 border-brand"
|
||||||
|
: "bg-surface-subtle",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"size-8 rounded-lg flex items-center justify-center text-[12px] font-bold",
|
||||||
|
item.isHighlighted
|
||||||
|
? "bg-brand text-white"
|
||||||
|
: "bg-surface-muted text-text-tertiary",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{item.rank}
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<p
|
||||||
|
className={cn(
|
||||||
|
"font-bold text-[14px]",
|
||||||
|
item.isHighlighted ? "text-brand" : "text-text-primary",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{item.name}
|
||||||
|
</p>
|
||||||
|
{item.badge && (
|
||||||
|
<span className="px-2 py-0.5 bg-brand text-white text-[9px] font-bold rounded uppercase tracking-wider">
|
||||||
|
{item.badge}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-text-primary font-bold text-[17px]">
|
||||||
|
{item.value}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{footer && (
|
||||||
|
<p className="text-[12px] text-text-secondary text-center mt-5 font-medium">
|
||||||
|
{footer}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { RankedList }
|
||||||
|
export type { RankedListProps, RankedItem }
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface SectionCardProps extends React.ComponentProps<"div"> {
|
||||||
|
title?: string
|
||||||
|
headerRight?: React.ReactNode
|
||||||
|
footer?: React.ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
function SectionCard({
|
||||||
|
title,
|
||||||
|
headerRight,
|
||||||
|
footer,
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: SectionCardProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="section-card"
|
||||||
|
className={cn(
|
||||||
|
"mx-6 bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{(title || headerRight) && (
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
{title && (
|
||||||
|
<h3 className="text-text-primary font-bold text-[18px] leading-snug">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
)}
|
||||||
|
{headerRight}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{children}
|
||||||
|
{footer && (
|
||||||
|
<div className="mt-5">
|
||||||
|
{footer}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { SectionCard }
|
||||||
|
export type { SectionCardProps }
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
import { TrendingUp, TrendingDown, type LucideIcon } from "lucide-react"
|
||||||
|
|
||||||
|
interface StatCardProps extends React.ComponentProps<"div"> {
|
||||||
|
icon: LucideIcon
|
||||||
|
label: string
|
||||||
|
value: string | number
|
||||||
|
unit?: string
|
||||||
|
trend?: {
|
||||||
|
value: string
|
||||||
|
direction: "up" | "down"
|
||||||
|
}
|
||||||
|
children?: React.ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatCard({
|
||||||
|
icon: Icon,
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
unit,
|
||||||
|
trend,
|
||||||
|
children,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: StatCardProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="stat-card"
|
||||||
|
className={cn(
|
||||||
|
"bg-card rounded-2xl p-6 shadow-[var(--shadow-card)]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-2 mb-3">
|
||||||
|
<div className="size-7 rounded-lg bg-brand/10 flex items-center justify-center">
|
||||||
|
<Icon className="size-4 text-brand" strokeWidth={2} />
|
||||||
|
</div>
|
||||||
|
<p className="text-[12px] text-text-secondary font-medium uppercase tracking-[0.05em]">
|
||||||
|
{label}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="text-text-primary text-[36px] font-bold leading-none tracking-[-0.02em] mb-3 whitespace-nowrap">
|
||||||
|
{value}
|
||||||
|
{unit && <span className="text-[18px] ms-0.5 tracking-normal">{unit}</span>}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{trend && (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"text-[13px] font-bold",
|
||||||
|
trend.direction === "up" ? "text-success" : "text-destructive",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{trend.value}
|
||||||
|
</span>
|
||||||
|
{trend.direction === "up" ? (
|
||||||
|
<TrendingUp className="size-3.5 text-success" strokeWidth={2.5} />
|
||||||
|
) : (
|
||||||
|
<TrendingDown className="size-3.5 text-destructive" strokeWidth={2.5} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { StatCard }
|
||||||
|
export type { StatCardProps }
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface TopBarProps extends React.ComponentProps<"header"> {
|
||||||
|
logo?: React.ReactNode
|
||||||
|
subtitle?: string
|
||||||
|
actions?: React.ReactNode
|
||||||
|
}
|
||||||
|
|
||||||
|
function TopBar({
|
||||||
|
logo,
|
||||||
|
subtitle,
|
||||||
|
actions,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: TopBarProps) {
|
||||||
|
return (
|
||||||
|
<header
|
||||||
|
data-slot="top-bar"
|
||||||
|
className={cn("px-6 pt-8 pb-6", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<div className="flex items-center gap-3">{logo}</div>
|
||||||
|
{actions && (
|
||||||
|
<div className="flex items-center gap-3">{actions}</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{subtitle && (
|
||||||
|
<p className="text-[13px] text-text-tertiary font-medium mt-3">
|
||||||
|
{subtitle}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TopBarActionProps extends React.ComponentProps<"button"> {
|
||||||
|
badge?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function TopBarAction({
|
||||||
|
badge,
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: TopBarActionProps) {
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
data-slot="top-bar-action"
|
||||||
|
className={cn(
|
||||||
|
"relative size-10 rounded-full bg-card shadow-[var(--shadow-button)] flex items-center justify-center",
|
||||||
|
"hover:shadow-[var(--shadow-card-hover)] transition-all",
|
||||||
|
"focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
{badge && (
|
||||||
|
<span className="absolute top-1 right-1 size-1.5 bg-alert-badge rounded-full" />
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { TopBar, TopBarAction }
|
||||||
|
export type { TopBarProps, TopBarActionProps }
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "../ui/utils"
|
||||||
|
|
||||||
|
interface ValueDisplayProps extends React.ComponentProps<"div"> {
|
||||||
|
value: number
|
||||||
|
change?: number
|
||||||
|
prefix?: string
|
||||||
|
size?: "sm" | "md" | "lg"
|
||||||
|
formatType?: "integer" | "decimal"
|
||||||
|
showArrow?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function ValueDisplay({
|
||||||
|
value,
|
||||||
|
change,
|
||||||
|
prefix = "₩",
|
||||||
|
size = "md",
|
||||||
|
formatType = "integer",
|
||||||
|
showArrow = true,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: ValueDisplayProps) {
|
||||||
|
const formatValue = (n: number) => {
|
||||||
|
if (formatType === "decimal") {
|
||||||
|
return n.toLocaleString("ko-KR", { minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
||||||
|
}
|
||||||
|
return Math.round(n).toLocaleString("ko-KR")
|
||||||
|
}
|
||||||
|
|
||||||
|
const sizeStyles = {
|
||||||
|
sm: { value: "text-[16px] font-semibold leading-tight tracking-[-0.01em]", change: "text-[12px]" },
|
||||||
|
md: { value: "text-[20px] font-semibold leading-tight tracking-[-0.02em]", change: "text-[14px]" },
|
||||||
|
lg: { value: "text-[24px] font-bold leading-none tracking-[-0.02em]", change: "text-[14px]" },
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="value-display"
|
||||||
|
className={cn("flex flex-col items-end justify-center min-w-20", className)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<p className={cn("text-text-primary whitespace-nowrap", sizeStyles[size].value)}>
|
||||||
|
{prefix}{formatValue(value)}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{change !== undefined && change !== 0 && (
|
||||||
|
<p
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-0.5 whitespace-nowrap",
|
||||||
|
sizeStyles[size].change,
|
||||||
|
change > 0 ? "text-destructive" : "text-info",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{showArrow && <span>{change > 0 ? "▲" : "▼"}</span>}
|
||||||
|
<span>{formatValue(Math.abs(change))}</span>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ValueDisplay }
|
||||||
|
export type { ValueDisplayProps }
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import * as AccordionPrimitive from "@radix-ui/react-accordion";
|
||||||
|
import { ChevronDownIcon } from "lucide-react";
|
||||||
|
|
||||||
|
import { cn } from "./utils";
|
||||||
|
|
||||||
|
function Accordion({
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||||
|
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionItem({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Item
|
||||||
|
data-slot="accordion-item"
|
||||||
|
className={cn("border-b last:border-b-0", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionTrigger({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Header className="flex">
|
||||||
|
<AccordionPrimitive.Trigger
|
||||||
|
data-slot="accordion-trigger"
|
||||||
|
className={cn(
|
||||||
|
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{children}
|
||||||
|
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
|
||||||
|
</AccordionPrimitive.Trigger>
|
||||||
|
</AccordionPrimitive.Header>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccordionContent({
|
||||||
|
className,
|
||||||
|
children,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||||
|
return (
|
||||||
|
<AccordionPrimitive.Content
|
||||||
|
data-slot="accordion-content"
|
||||||
|
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className={cn("pt-0 pb-4", className)}>{children}</div>
|
||||||
|
</AccordionPrimitive.Content>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
|
||||||
|
import { cn } from "./utils";
|
||||||
|
|
||||||
|
const alertVariants = cva(
|
||||||
|
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default: "bg-card text-card-foreground",
|
||||||
|
destructive:
|
||||||
|
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
function Alert({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert"
|
||||||
|
role="alert"
|
||||||
|
className={cn(alertVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-title"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AlertDescription({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="alert-description"
|
||||||
|
className={cn(
|
||||||
|
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Alert, AlertTitle, AlertDescription };
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||||
|
|
||||||
|
import { cn } from "./utils";
|
||||||
|
|
||||||
|
function Avatar({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Root
|
||||||
|
data-slot="avatar"
|
||||||
|
className={cn(
|
||||||
|
"relative flex size-10 shrink-0 overflow-hidden rounded-full",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarImage({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Image
|
||||||
|
data-slot="avatar-image"
|
||||||
|
className={cn("aspect-square size-full", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AvatarFallback({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||||
|
return (
|
||||||
|
<AvatarPrimitive.Fallback
|
||||||
|
data-slot="avatar-fallback"
|
||||||
|
className={cn(
|
||||||
|
"bg-muted flex size-full items-center justify-center rounded-full",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Avatar, AvatarImage, AvatarFallback };
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
|
||||||
|
import { cn } from "./utils";
|
||||||
|
|
||||||
|
const badgeVariants = cva(
|
||||||
|
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default:
|
||||||
|
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||||
|
secondary:
|
||||||
|
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||||
|
destructive:
|
||||||
|
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
function Badge({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"span"> &
|
||||||
|
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
|
||||||
|
const Comp = asChild ? Slot : "span";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="badge"
|
||||||
|
className={cn(badgeVariants({ variant }), className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Badge, badgeVariants };
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
import { Slot } from "@radix-ui/react-slot";
|
||||||
|
import { cva, type VariantProps } from "class-variance-authority";
|
||||||
|
|
||||||
|
import { cn } from "./utils";
|
||||||
|
|
||||||
|
const buttonVariants = cva(
|
||||||
|
"inline-flex items-center justify-center whitespace-nowrap font-bold transition-colors duration-150 disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 shrink-0 outline-none focus-visible:ring-2 focus-visible:ring-brand/20",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
// 토스 스타일: brandSolid — 키컬러 배경, 흰 텍스트
|
||||||
|
default:
|
||||||
|
"bg-brand text-white active:bg-brand/85 disabled:bg-surface-muted disabled:text-text-disabled",
|
||||||
|
// neutralSolid — 어두운 배경, 흰 텍스트
|
||||||
|
neutral:
|
||||||
|
"bg-[#2A2A2A] text-white active:bg-[#3C3C3C] disabled:bg-surface-muted disabled:text-text-disabled dark:bg-[#E0E0E0] dark:text-[#121212] dark:active:bg-[#C0C0C0]",
|
||||||
|
// neutralWeak — 연한 회색 배경, 어두운 텍스트
|
||||||
|
secondary:
|
||||||
|
"bg-[#F3F4F5] text-text-primary active:bg-[#EAEBEC] disabled:bg-surface-muted disabled:text-text-disabled dark:bg-[#2B2E35] dark:text-[#E0E0E0] dark:active:bg-[#393D46]",
|
||||||
|
// criticalSolid — 위험 액션
|
||||||
|
destructive:
|
||||||
|
"bg-destructive text-white active:bg-destructive/85 focus-visible:ring-destructive/20 disabled:bg-surface-muted disabled:text-text-disabled",
|
||||||
|
// outline — 테두리만
|
||||||
|
outline:
|
||||||
|
"border border-border bg-transparent text-text-primary active:bg-surface-muted/50 disabled:border-surface-muted disabled:text-text-disabled dark:border-white/8",
|
||||||
|
// ghost — 배경/테두리 없음
|
||||||
|
ghost:
|
||||||
|
"bg-transparent text-text-primary active:bg-surface-muted/50 disabled:text-text-disabled",
|
||||||
|
// brandGhost — 키컬러 텍스트, 배경 없음
|
||||||
|
brandGhost:
|
||||||
|
"bg-transparent text-brand active:bg-brand/8 disabled:text-text-disabled",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
// 토스 기준 4단계: xsmall(32) / small(36) / medium(40) / large(52)
|
||||||
|
xs: "h-8 px-3.5 gap-1 text-[13px] rounded-full [&_svg:not([class*='size-'])]:size-3.5",
|
||||||
|
sm: "h-9 px-3.5 gap-1 text-[14px] rounded-lg [&_svg:not([class*='size-'])]:size-3.5",
|
||||||
|
md: "h-10 px-4 gap-1.5 text-[14px] rounded-lg [&_svg:not([class*='size-'])]:size-4",
|
||||||
|
lg: "h-[52px] px-5 gap-2 text-[18px] rounded-xl [&_svg:not([class*='size-'])]:size-[22px]",
|
||||||
|
icon: "size-10 rounded-full [&_svg:not([class*='size-'])]:size-[18px]",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "md",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
function Button({
|
||||||
|
className,
|
||||||
|
variant,
|
||||||
|
size,
|
||||||
|
asChild = false,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<"button"> &
|
||||||
|
VariantProps<typeof buttonVariants> & {
|
||||||
|
asChild?: boolean;
|
||||||
|
}) {
|
||||||
|
const Comp = asChild ? Slot : "button";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Comp
|
||||||
|
data-slot="button"
|
||||||
|
className={cn(buttonVariants({ variant, size, className }))}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Button, buttonVariants };
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import * as React from "react";
|
||||||
|
|
||||||
|
import { cn } from "./utils";
|
||||||
|
|
||||||
|
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card"
|
||||||
|
className={cn(
|
||||||
|
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-header"
|
||||||
|
className={cn(
|
||||||
|
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 pt-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<h4
|
||||||
|
data-slot="card-title"
|
||||||
|
className={cn("leading-none", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<p
|
||||||
|
data-slot="card-description"
|
||||||
|
className={cn("text-muted-foreground", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-action"
|
||||||
|
className={cn(
|
||||||
|
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-content"
|
||||||
|
className={cn("px-6 [&:last-child]:pb-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="card-footer"
|
||||||
|
className={cn("flex items-center px-6 pb-6 [.border-t]:pt-6", className)}
|
||||||
|
{...props}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export {
|
||||||
|
Card,
|
||||||
|
CardHeader,
|
||||||
|
CardFooter,
|
||||||
|
CardTitle,
|
||||||
|
CardAction,
|
||||||
|
CardDescription,
|
||||||
|
CardContent,
|
||||||
|
};
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import * as React from "react";
|
||||||
|
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
|
||||||
|
import { CheckIcon } from "lucide-react";
|
||||||
|
|
||||||
|
import { cn } from "./utils";
|
||||||
|
|
||||||
|
function Checkbox({
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||||
|
return (
|
||||||
|
<CheckboxPrimitive.Root
|
||||||
|
data-slot="checkbox"
|
||||||
|
className={cn(
|
||||||
|
"peer border bg-input-background dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<CheckboxPrimitive.Indicator
|
||||||
|
data-slot="checkbox-indicator"
|
||||||
|
className="flex items-center justify-center text-current transition-none"
|
||||||
|
>
|
||||||
|
<CheckIcon className="size-3.5" />
|
||||||
|
</CheckboxPrimitive.Indicator>
|
||||||
|
</CheckboxPrimitive.Root>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { Checkbox };
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "./utils"
|
||||||
|
|
||||||
|
interface ConfirmModalProps extends React.ComponentProps<"div"> {
|
||||||
|
isOpen: boolean
|
||||||
|
onConfirm: () => void
|
||||||
|
onCancel: () => void
|
||||||
|
title: string
|
||||||
|
message: string | string[]
|
||||||
|
confirmText?: string
|
||||||
|
cancelText?: string
|
||||||
|
variant?: "default" | "destructive"
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConfirmModal({
|
||||||
|
isOpen,
|
||||||
|
onConfirm,
|
||||||
|
onCancel,
|
||||||
|
title,
|
||||||
|
message,
|
||||||
|
confirmText = "확인",
|
||||||
|
cancelText = "닫기",
|
||||||
|
variant = "default",
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: ConfirmModalProps) {
|
||||||
|
const messages = Array.isArray(message) ? message : [message]
|
||||||
|
|
||||||
|
if (!isOpen) return null
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="confirm-modal"
|
||||||
|
className="fixed inset-0 bg-black/40 backdrop-blur-sm flex items-center justify-center z-50"
|
||||||
|
onClick={onCancel}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className={cn(
|
||||||
|
"bg-card rounded-2xl p-5 mx-4 max-w-sm w-full shadow-[var(--shadow-modal)]",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col gap-5 items-center text-center">
|
||||||
|
{/* Content */}
|
||||||
|
<div className="flex flex-col gap-2 items-center w-full">
|
||||||
|
<h3 className="text-text-primary text-[16px] font-semibold leading-tight tracking-[-0.01em]">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
<div className="text-text-secondary text-[14px] leading-normal">
|
||||||
|
{messages.map((line, i) => (
|
||||||
|
<p key={i}>{line}</p>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Buttons — 토스 규칙: 좌측=닫기, 우측=확인 */}
|
||||||
|
<div className="flex gap-2 w-full">
|
||||||
|
<button
|
||||||
|
onClick={onCancel}
|
||||||
|
className="flex-1 h-11 rounded-full text-[16px] font-semibold border border-brand text-brand bg-card active:bg-brand/8 transition-colors duration-150"
|
||||||
|
>
|
||||||
|
{cancelText}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={onConfirm}
|
||||||
|
className={cn(
|
||||||
|
"flex-1 h-11 rounded-full text-[16px] font-semibold text-white active:opacity-85 transition-colors duration-150",
|
||||||
|
variant === "destructive" ? "bg-destructive" : "bg-brand",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{confirmText}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { ConfirmModal }
|
||||||
|
export type { ConfirmModalProps }
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import * as React from "react"
|
||||||
|
import { cn } from "./utils"
|
||||||
|
|
||||||
|
interface DataDisplayProps extends React.ComponentProps<"div"> {
|
||||||
|
label: string
|
||||||
|
value: string | number
|
||||||
|
icon?: React.ReactNode
|
||||||
|
highlighted?: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
function DataDisplay({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
icon,
|
||||||
|
highlighted = false,
|
||||||
|
className,
|
||||||
|
...props
|
||||||
|
}: DataDisplayProps) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
data-slot="data-display"
|
||||||
|
className={cn(
|
||||||
|
"flex items-center gap-2 px-4 py-3 bg-card rounded-lg border border-surface-muted min-h-12",
|
||||||
|
className,
|
||||||
|
)}
|
||||||
|
{...props}
|
||||||
|
>
|
||||||
|
{icon && (
|
||||||
|
<div className="size-6 text-brand shrink-0">{icon}</div>
|
||||||
|
)}
|
||||||
|
<span className="text-[12px] font-medium text-text-secondary min-w-20">
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"text-[14px] font-semibold flex-1",
|
||||||
|
highlighted ? "text-brand" : "text-text-primary",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{typeof value === "number" ? value.toLocaleString("ko-KR") : value}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export { DataDisplay }
|
||||||
|
export type { DataDisplayProps }
|
||||||
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user