This commit is contained in:
dahyeon committed 2026-04-27 19:23:26 -07:00
1 parent 1bbfc901e8
commit 4dba82ca03
18 files changed
+2146 -15

No files matched your search

+2
View File
@@ -8,6 +8,7 @@ import { CommunityModule } from './modules/community/community.module';
import { CommunityStatsModule } from './modules/community-stats/community-stats.module';
import { DakaoModule } from './modules/dakao/dakao.module';
import { GlobalModule } from './modules/global/global.module';
import { LegacyImportModule } from './modules/legacy-import/legacy-import.module';
import { MatchHistoryModule } from './modules/match-history/match-history.module';
import { MatchModule } from './modules/match/match.module';
import { RiotModule } from './modules/riot/riot.module';
@@ -28,6 +29,7 @@ import { UserModule } from './modules/user/user.module';
CommunityStatsModule,
MatchModule,
MatchHistoryModule,
LegacyImportModule,
TournamentCodeModule,
TournamentResultModule,
AuctionModule,
@@ -66,6 +66,20 @@ export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [
'failed',
];
export type LegacyImportJobState =
| 'pending'
| 'running'
| 'completed'
| 'failed'
| 'cancelled';
export const LEGACY_IMPORT_JOB_STATES: LegacyImportJobState[] = [
'pending',
'running',
'completed',
'failed',
'cancelled',
];
export interface PositionPreference {
position: Position;
priority: number; // 1 = 최우선, 숫자가 작을수록 높은 우선순위
@@ -382,6 +396,13 @@ export interface Match extends MongooseTimestamps {
teams: MatchTeam[];
result?: MatchResult;
resultPollState?: MatchResultPollState;
legacyImported?: boolean;
legacyImportSource?: {
importedAt: Date;
importedBy: mongoose.Types.ObjectId;
triggeringPuuid: string;
jobId?: string;
};
prizes: string[];
notices: string[];
schedule: MatchScheduleItem[];
@@ -389,6 +410,43 @@ export interface Match extends MongooseTimestamps {
export type MatchDocument = HydratedDocument<Match>;
// ===== Legacy Import Job =====
export interface LegacyImportJobMemberOverride {
userId: mongoose.Types.ObjectId;
puuid: string;
startTime: Date;
endTime: Date;
}
export interface LegacyImportJobError {
puuid?: string;
matchId?: string;
reason: string;
at: Date;
}
export interface LegacyImportJob extends MongooseTimestamps {
jobId: string;
communityId: mongoose.Types.ObjectId;
triggeredBy: mongoose.Types.ObjectId;
startedAt: Date;
completedAt?: Date;
state: LegacyImportJobState;
windowStart: Date;
windowEnd: Date;
memberOverrides: LegacyImportJobMemberOverride[];
totalMembers: number;
processedMembers: number;
totalDiscoveredMatchIds: number;
totalImportedMatches: number;
totalSkippedDuplicate: number;
totalErrors: number;
averageMemberSeconds?: number;
errors?: LegacyImportJobError[];
}
export type LegacyImportJobDocument = HydratedDocument<LegacyImportJob>;
// ===== Auction (경매) =====
export interface AuctionPlayerSnapshot {
userId: mongoose.Types.ObjectId;
@@ -916,6 +974,16 @@ const MatchScheduleItemSubSchema = new Schema<MatchScheduleItem>(
{ _id: false },
);
const MatchLegacyImportSourceSubSchema = new Schema<NonNullable<Match['legacyImportSource']>>(
{
importedAt: { type: Date, required: true },
importedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
triggeringPuuid: { type: String, required: true },
jobId: { type: String },
},
{ _id: false },
);
export const MatchSchema = new Schema<Match>(
{
communityId: {
@@ -960,6 +1028,11 @@ export const MatchSchema = new Schema<Match>(
type: MatchResultPollStateSubSchema,
required: false,
},
legacyImported: { type: Boolean, required: false, default: false },
legacyImportSource: {
type: MatchLegacyImportSourceSubSchema,
required: false,
},
prizes: { type: [String], required: true, default: [] },
notices: { type: [String], required: true, default: [] },
schedule: {
@@ -976,8 +1049,78 @@ export const MatchSchema = new Schema<Match>(
MatchSchema.index({ communityId: 1, scheduledAt: -1 });
MatchSchema.index({ communityId: 1, status: 1, scheduledAt: -1 });
MatchSchema.index({ legacyImported: 1, scheduledAt: -1 });
MatchSchema.index({ 'result.games.riotMatchId': 1 }, { sparse: true });
MatchSchema.index({ title: 'text', description: 'text' });
const LegacyImportJobMemberOverrideSubSchema =
new Schema<LegacyImportJobMemberOverride>(
{
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
puuid: { type: String, required: true },
startTime: { type: Date, required: true },
endTime: { type: Date, required: true },
},
{ _id: false },
);
const LegacyImportJobErrorSubSchema = new Schema<LegacyImportJobError>(
{
puuid: { type: String },
matchId: { type: String },
reason: { type: String, required: true },
at: { type: Date, required: true, default: Date.now },
},
{ _id: false },
);
export const LegacyImportJobSchema = new Schema<LegacyImportJob>(
{
jobId: { type: String, required: true, unique: true },
communityId: {
type: Schema.Types.ObjectId,
ref: 'community',
required: true,
},
triggeredBy: { type: Schema.Types.ObjectId, ref: 'user', required: true },
startedAt: { type: Date, required: true, default: Date.now },
completedAt: { type: Date },
state: {
type: String,
enum: LEGACY_IMPORT_JOB_STATES,
required: true,
default: 'pending',
},
windowStart: { type: Date, required: true },
windowEnd: { type: Date, required: true },
memberOverrides: {
type: [LegacyImportJobMemberOverrideSubSchema],
required: true,
default: [],
},
totalMembers: { type: Number, required: true, default: 0 },
processedMembers: { type: Number, required: true, default: 0 },
totalDiscoveredMatchIds: { type: Number, required: true, default: 0 },
totalImportedMatches: { type: Number, required: true, default: 0 },
totalSkippedDuplicate: { type: Number, required: true, default: 0 },
totalErrors: { type: Number, required: true, default: 0 },
averageMemberSeconds: { type: Number },
errors: {
type: [LegacyImportJobErrorSubSchema],
required: true,
default: [],
},
},
{
timestamps: true,
collection: 'legacy_import_job',
suppressReservedKeysWarning: true,
},
);
LegacyImportJobSchema.index({ communityId: 1, startedAt: -1 });
LegacyImportJobSchema.index({ communityId: 1, state: 1 });
const AuctionPlayerSnapshotSubSchema = new Schema<AuctionPlayerSnapshot>(
{
userId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
@@ -1080,6 +1223,11 @@ export const tournamentModelDefinitions: ModelDefinition[] = [
schema: TournamentCodeSchema,
schemaName: 'tournamentCode',
},
{
name: 'legacyImportJob',
schema: LegacyImportJobSchema,
schemaName: 'legacyImportJob',
},
{ name: 'match', schema: MatchSchema, schemaName: 'match' },
{ name: 'auction', schema: AuctionSchema, schemaName: 'auction' },
];
@@ -1090,6 +1238,7 @@ export interface TournamentModelTypes {
user: User;
riotMatch: RiotMatch;
tournamentCode: TournamentCode;
legacyImportJob: LegacyImportJob;
match: Match;
auction: Auction;
}
@@ -0,0 +1,140 @@
import {
BadRequestException,
Body,
Controller,
Get,
Param,
Post,
Query,
UseGuards,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { CurrentUser } from '../auth/current-user.decorator';
import { Roles } from '../auth/roles.decorator';
import { RolesGuard } from '../auth/roles.guard';
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
import type { UserDocument } from '../global/database/schema';
import type {
BulkDeleteLegacyMatchesRequest,
StartLegacyImportRequest,
} from './legacy-import.types';
import { LegacyImportService } from './legacy-import.service';
@Controller('communities/:communityId')
@Roles('owner', 'admin')
@UseGuards(RolesGuard)
export class LegacyImportController {
constructor(private readonly legacyImportService: LegacyImportService) {}
@Get('legacy-import/members')
public previewMembers(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('windowStart') windowStart?: string,
@Query('windowEnd') windowEnd?: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.previewMembers({
communityId,
windowStart,
windowEnd,
});
}
@Post('legacy-import')
public start(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: StartLegacyImportRequest,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.start({
communityId,
triggeredBy: currentUser._id,
body,
});
}
@Get('legacy-import-jobs')
public listJobs(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('limit') limit?: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.listJobs({
communityId,
limit: this.toNumber(limit),
});
}
@Get('legacy-import-jobs/:jobId')
public getJob(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('jobId') jobId: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.getJob({ communityId, jobId });
}
@Post('legacy-import-jobs/:jobId/cancel')
public cancel(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('jobId') jobId: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.cancel({ communityId, jobId });
}
@Get('legacy-matches')
public listLegacyMatches(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Query('cursor') cursor?: string,
@Query('limit') limit?: string,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.listLegacyMatches({
communityId,
cursor: this.toNumber(cursor),
limit: this.toNumber(limit),
});
}
@Post('legacy-matches/bulk-delete')
public bulkDeleteLegacyMatches(
@CurrentUser() currentUser: UserDocument,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Body() body: BulkDeleteLegacyMatchesRequest,
) {
this.assertSameCommunity(currentUser, communityId);
return this.legacyImportService.bulkDeleteLegacyMatches({
communityId,
body,
});
}
private assertSameCommunity(
user: UserDocument,
communityId: mongoose.Types.ObjectId,
): void {
if (!user.communityId.equals(communityId)) {
throw new BadRequestException('Different community.');
}
}
private toNumber(value: string | undefined): number | undefined {
if (!value) return undefined;
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : undefined;
}
}
@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { RiotModule } from '../riot/riot.module';
import { LegacyImportController } from './legacy-import.controller';
import { LegacyImportService } from './legacy-import.service';
@Module({
imports: [RiotModule, CommunityStatsModule],
controllers: [LegacyImportController],
providers: [LegacyImportService],
exports: [LegacyImportService],
})
export class LegacyImportModule {}
@@ -0,0 +1,677 @@
import {
BadRequestException,
ConflictException,
Injectable,
Logger,
NotFoundException,
} from '@nestjs/common';
import { randomUUID } from 'crypto';
import mongoose from 'mongoose';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import type {
LegacyImportJobDocument,
Match,
RiotMatch as StoredRiotMatch,
UserDocument,
} from '../global/database/schema';
import { GarnetService } from '../global/garnet/garnet.service';
import { RIOT_JOB_LOW_STREAM } from '../riot-job-queue/riot-job-queue.types';
import { RiotMatchService } from '../riot/riot-match.service';
import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types';
import {
buildGameResult,
buildParticipantsSnapshot,
buildTeams,
buildUserByPuuidMap,
countKnownParticipants,
resolveExternalCount,
resolveTeam100IsBlue,
type UserByPuuidMap,
} from './match-builder.util';
import {
LEGACY_IMPORT_DEFAULT_START_ISO,
LEGACY_IMPORT_LOCK_TTL_SECONDS,
LEGACY_IMPORT_MEMBER_AVG_SECONDS,
type BulkDeleteLegacyMatchesRequest,
type LegacyImportMemberJob,
type LegacyImportMemberWindowView,
type LegacyMatchListResponse,
type StartLegacyImportRequest,
type StartLegacyImportResponse,
} from './legacy-import.types';
const MATCH_IMPORT_LOCK_TTL_SECONDS = 60;
const MATCH_ID_PAGE_SIZE = 100;
type ImportOutcome = 'imported' | 'duplicate' | 'skipped' | 'error';
@Injectable()
export class LegacyImportService {
private readonly logger = new Logger(LegacyImportService.name);
constructor(
private readonly connectionService: ConnectionService,
private readonly garnetService: GarnetService,
private readonly riotMatchService: RiotMatchService,
private readonly communityStatsService: CommunityStatsService,
) {}
public async previewMembers(params: {
communityId: mongoose.Types.ObjectId;
windowStart?: string;
windowEnd?: string;
}): Promise<{ members: LegacyImportMemberWindowView[] }> {
const { windowStart, windowEnd } = this.resolveWindow(params);
const users = await this.findImportableUsers(params.communityId);
return {
members: users.map((user) =>
this.toMemberWindowView(user, windowStart, windowEnd),
),
};
}
public async start(params: {
communityId: mongoose.Types.ObjectId;
triggeredBy: mongoose.Types.ObjectId;
body: StartLegacyImportRequest;
}): Promise<StartLegacyImportResponse> {
const lockKey = this.communityLockKey(params.communityId);
const jobId = randomUUID();
const acquired = await this.garnetService.setStringIfAbsent(
lockKey,
jobId,
LEGACY_IMPORT_LOCK_TTL_SECONDS,
);
if (!acquired) {
throw new ConflictException('Legacy import is already running.');
}
try {
const CommunityModel = await this.connectionService.getModel('community');
const community = await CommunityModel.findById(params.communityId)
.select({ riotRegion: 1 })
.lean()
.exec();
if (!community) throw new NotFoundException('Community not found.');
const { windowStart, windowEnd } = this.resolveWindow({
windowStart: params.body.windowStart,
windowEnd: params.body.windowEnd,
});
const users = await this.findImportableUsers(params.communityId);
const overrides = new Map(
(params.body.memberOverrides ?? []).map((override) => [
override.userId,
override,
]),
);
const windows = users
.map((user) => this.resolveMemberWindow(user, windowStart, windowEnd, overrides))
.filter((window) => window.startTime.getTime() <= window.endTime.getTime());
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
await LegacyImportJobModel.create({
jobId,
communityId: params.communityId,
triggeredBy: params.triggeredBy,
startedAt: new Date(),
state: 'running',
windowStart,
windowEnd,
memberOverrides: windows,
totalMembers: windows.length,
processedMembers: 0,
totalDiscoveredMatchIds: 0,
totalImportedMatches: 0,
totalSkippedDuplicate: 0,
totalErrors: 0,
averageMemberSeconds: LEGACY_IMPORT_MEMBER_AVG_SECONDS,
});
for (const window of windows) {
const job: LegacyImportMemberJob = {
kind: 'legacy-import-member',
jobId: randomUUID(),
parentJobId: jobId,
communityId: params.communityId.toString(),
userId: window.userId.toString(),
puuid: window.puuid,
startTime: Math.floor(window.startTime.getTime() / 1000),
endTime: Math.floor(window.endTime.getTime() / 1000),
triggeredBy: params.triggeredBy.toString(),
region: (community.riotRegion ?? 'asia') as RiotRegionalRoute,
};
await this.garnetService.appendStream(
RIOT_JOB_LOW_STREAM,
{ job: JSON.stringify(job) },
{ maxLen: 10_000 },
);
}
if (windows.length === 0) {
await LegacyImportJobModel.updateOne(
{ jobId },
{ $set: { state: 'completed', completedAt: new Date() } },
).exec();
await this.garnetService.delete(lockKey);
}
return {
jobId,
totalMembers: windows.length,
etaSeconds: windows.length * LEGACY_IMPORT_MEMBER_AVG_SECONDS,
};
} catch (error) {
await this.garnetService.delete(lockKey);
throw error;
}
}
public async listJobs(params: {
communityId: mongoose.Types.ObjectId;
limit?: number;
}): Promise<{ jobs: LegacyImportJobDocument[] }> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const jobs = await LegacyImportJobModel.find({ communityId: params.communityId })
.sort({ startedAt: -1 })
.limit(Math.min(params.limit ?? 10, 50))
.exec();
return { jobs };
}
public async getJob(params: {
communityId: mongoose.Types.ObjectId;
jobId: string;
}): Promise<LegacyImportJobDocument> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOne({
communityId: params.communityId,
jobId: params.jobId,
}).exec();
if (!job) throw new NotFoundException('Legacy import job not found.');
return job;
}
public async cancel(params: {
communityId: mongoose.Types.ObjectId;
jobId: string;
}): Promise<LegacyImportJobDocument> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOneAndUpdate(
{
communityId: params.communityId,
jobId: params.jobId,
state: { $in: ['pending', 'running'] },
},
{ $set: { state: 'cancelled', completedAt: new Date() } },
{ new: true },
).exec();
if (!job) throw new NotFoundException('Running legacy import job not found.');
await this.garnetService.delete(this.communityLockKey(params.communityId));
return job;
}
public async processMemberJob(job: LegacyImportMemberJob): Promise<void> {
const started = Date.now();
const legacyJob = await this.getRunnableJob(job);
if (!legacyJob) return;
let discovered = 0;
let imported = 0;
let duplicates = 0;
let errors = 0;
try {
const userByPuuid = await this.buildUserByPuuidMap(
new mongoose.Types.ObjectId(job.communityId),
);
const matchIds = await this.collectMatchIds(job);
discovered = matchIds.size;
for (const matchId of matchIds) {
if (await this.isCancelled(job.parentJobId)) break;
const outcome = await this.importSingleMatch(matchId, job, userByPuuid);
if (outcome === 'imported') imported += 1;
if (outcome === 'duplicate') duplicates += 1;
if (outcome === 'error') errors += 1;
}
} catch (error) {
errors += 1;
await this.recordError(job.parentJobId, {
puuid: job.puuid,
reason: error instanceof Error ? error.message : String(error),
});
this.logger.warn(
`Legacy import member job failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
} finally {
await this.finishMemberJob(job, {
discovered,
imported,
duplicates,
errors,
elapsedSeconds: Math.max(1, Math.round((Date.now() - started) / 1000)),
});
}
}
public async listLegacyMatches(params: {
communityId: mongoose.Types.ObjectId;
cursor?: number;
limit?: number;
}): Promise<LegacyMatchListResponse> {
const MatchModel = await this.connectionService.getModel('match');
const limit = Math.max(1, Math.min(params.limit ?? 30, 100));
const filter: Record<string, unknown> = {
communityId: params.communityId,
legacyImported: true,
};
if (params.cursor) {
filter.scheduledAt = { $lt: new Date(params.cursor) };
}
const matches = await MatchModel.find(filter)
.sort({ scheduledAt: -1 })
.limit(limit + 1)
.exec();
const visible = matches.slice(0, limit);
const riotMatchIds = visible
.map((match) => match.result?.games[0]?.riotMatchId)
.filter((matchId): matchId is string => Boolean(matchId));
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const rawDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } })
.lean()
.exec();
const rawById = new Map(
rawDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]),
);
const userByPuuid = await this.buildUserByPuuidMap(params.communityId);
return {
matches: visible.map((match) => {
const riotMatchId = match.result?.games[0]?.riotMatchId ?? null;
const raw = riotMatchId ? rawById.get(riotMatchId) : undefined;
const memberCount = match.result?.games[0]?.participants.length ?? 0;
return {
matchId: match._id.toString(),
title: match.title,
scheduledAt: match.scheduledAt.toISOString(),
riotMatchId,
memberCount,
externalCount: raw
? resolveExternalCount(raw, userByPuuid)
: Math.max(0, 10 - memberCount),
blueScore: match.result?.blueScore ?? 0,
redScore: match.result?.redScore ?? 0,
winnerSide: match.result?.winnerSide,
};
}),
nextCursor:
matches.length > limit
? visible[visible.length - 1]?.scheduledAt.getTime() ?? null
: null,
};
}
public async bulkDeleteLegacyMatches(params: {
communityId: mongoose.Types.ObjectId;
body: BulkDeleteLegacyMatchesRequest;
}): Promise<{ deleted: number }> {
const ids = (params.body.matchIds ?? [])
.filter((id) => mongoose.isValidObjectId(id))
.map((id) => new mongoose.Types.ObjectId(id));
if (ids.length === 0) return { deleted: 0 };
const MatchModel = await this.connectionService.getModel('match');
const result = await MatchModel.deleteMany({
_id: { $in: ids },
communityId: params.communityId,
legacyImported: true,
}).exec();
await this.communityStatsService.invalidateCommunity(params.communityId);
return { deleted: result.deletedCount ?? 0 };
}
private async collectMatchIds(job: LegacyImportMemberJob): Promise<Set<string>> {
const matchIds = new Set<string>();
let start = 0;
while (true) {
const ids = await this.riotMatchService.getMatchIdsByPuuid(job.puuid, {
region: job.region,
type: 'tourney',
startTime: job.startTime,
endTime: job.endTime,
start,
count: MATCH_ID_PAGE_SIZE,
});
ids.forEach((matchId) => matchIds.add(matchId));
if (ids.length < MATCH_ID_PAGE_SIZE) break;
start += MATCH_ID_PAGE_SIZE;
}
return matchIds;
}
private async importSingleMatch(
riotMatchId: string,
job: LegacyImportMemberJob,
userByPuuid: UserByPuuidMap,
): Promise<ImportOutcome> {
const lockKey = `legacy-import:match:${riotMatchId}`;
const acquired = await this.garnetService.setStringIfAbsent(
lockKey,
job.parentJobId,
MATCH_IMPORT_LOCK_TTL_SECONDS,
);
if (!acquired) return 'duplicate';
try {
const MatchModel = await this.connectionService.getModel('match');
const existing = await MatchModel.exists({
'result.games.riotMatchId': riotMatchId,
});
if (existing) return 'duplicate';
const detail = await this.ensureRiotMatchPersisted(riotMatchId, job.region);
if (!detail.info.tournamentCode) return 'skipped';
const counts = countKnownParticipants(detail, userByPuuid);
if (counts.total === 0) return 'skipped';
const team100IsBlue = resolveTeam100IsBlue(detail, userByPuuid);
const gameResult = buildGameResult(detail, userByPuuid, team100IsBlue, 1);
if (!gameResult || gameResult.participants.length === 0) return 'skipped';
const winnerSide = gameResult.winnerSide;
const matchPayload: Partial<Match> = {
communityId: new mongoose.Types.ObjectId(job.communityId),
title: `[Legacy] ${this.formatLegacyDate(detail.info.gameCreation)}`,
description: 'Legacy import (자동 생성)',
mapId: detail.info.mapId ?? 11,
status: 'finished',
scheduledAt: new Date(detail.info.gameCreation),
maxParticipants: 10,
gameCount: 1,
tournamentCodeIds: [],
teamBuiltAt: new Date(detail.info.gameCreation),
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
participants: buildParticipantsSnapshot(detail, userByPuuid),
teams: buildTeams(detail, userByPuuid, team100IsBlue),
result: {
winnerSide,
blueScore: winnerSide === 'blue' ? 1 : 0,
redScore: winnerSide === 'red' ? 1 : 0,
riotMatchIds: [riotMatchId],
games: [gameResult],
},
legacyImported: true,
legacyImportSource: {
importedAt: new Date(),
importedBy: new mongoose.Types.ObjectId(job.triggeredBy),
triggeringPuuid: job.puuid,
jobId: job.parentJobId,
},
prizes: [],
notices: [],
schedule: [],
};
await MatchModel.create(matchPayload);
return 'imported';
} catch (error) {
await this.recordError(job.parentJobId, {
puuid: job.puuid,
matchId: riotMatchId,
reason: error instanceof Error ? error.message : String(error),
});
return 'error';
} finally {
await this.garnetService.delete(lockKey);
}
}
private async ensureRiotMatchPersisted(
riotMatchId: string,
region: RiotRegionalRoute,
): Promise<RiotMatchDto> {
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
const stored = await RiotMatchModel.findOne({ matchId: riotMatchId }).exec();
if (isRiotMatchDto(stored?.raw)) return stored.raw;
const dto = await this.riotMatchService.getMatch(riotMatchId, { region });
const payload: Partial<StoredRiotMatch> = {
matchId: dto.metadata.matchId,
gameCreation: dto.info.gameCreation,
gameDuration: dto.info.gameDuration,
gameVersion: dto.info.gameVersion,
queueId: dto.info.queueId,
participantPuuids: dto.metadata.participants,
raw: dto as unknown as Record<string, unknown>,
fetchedAt: new Date(),
};
await RiotMatchModel.updateOne(
{ matchId: dto.metadata.matchId },
{ $set: payload },
{ upsert: true },
).exec();
return dto;
}
private async finishMemberJob(
job: LegacyImportMemberJob,
stats: {
discovered: number;
imported: number;
duplicates: number;
errors: number;
elapsedSeconds: number;
},
): Promise<void> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const current = await LegacyImportJobModel.findOne({
jobId: job.parentJobId,
}).exec();
if (!current || current.state === 'cancelled') return;
const average =
current.averageMemberSeconds === undefined
? stats.elapsedSeconds
: Math.round(current.averageMemberSeconds * 0.7 + stats.elapsedSeconds * 0.3);
const nextProcessed = current.processedMembers + 1;
const completed = nextProcessed >= current.totalMembers;
await LegacyImportJobModel.updateOne(
{ jobId: job.parentJobId },
{
$set: {
state: completed ? 'completed' : current.state,
completedAt: completed ? new Date() : current.completedAt,
averageMemberSeconds: average,
},
$inc: {
processedMembers: 1,
totalDiscoveredMatchIds: stats.discovered,
totalImportedMatches: stats.imported,
totalSkippedDuplicate: stats.duplicates,
totalErrors: stats.errors,
},
},
).exec();
if (completed) {
await Promise.all([
this.garnetService.delete(
this.communityLockKey(new mongoose.Types.ObjectId(job.communityId)),
),
this.communityStatsService.invalidateCommunity(
new mongoose.Types.ObjectId(job.communityId),
),
]);
}
}
private async getRunnableJob(
job: LegacyImportMemberJob,
): Promise<LegacyImportJobDocument | null> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const legacyJob = await LegacyImportJobModel.findOne({
jobId: job.parentJobId,
}).exec();
if (!legacyJob || legacyJob.state === 'cancelled') return null;
if (legacyJob.state === 'completed' || legacyJob.state === 'failed') return null;
return legacyJob;
}
private async isCancelled(parentJobId: string): Promise<boolean> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
const job = await LegacyImportJobModel.findOne({ jobId: parentJobId })
.select({ state: 1 })
.lean()
.exec();
return job?.state === 'cancelled';
}
private async recordError(
jobId: string,
error: { puuid?: string; matchId?: string; reason: string },
): Promise<void> {
const LegacyImportJobModel =
await this.connectionService.getModel('legacyImportJob');
await LegacyImportJobModel.updateOne(
{ jobId },
{
$push: {
errors: {
...error,
at: new Date(),
},
},
},
).exec();
}
private async buildUserByPuuidMap(
communityId: mongoose.Types.ObjectId,
): Promise<UserByPuuidMap> {
const users = await this.findImportableUsers(communityId);
return buildUserByPuuidMap(users);
}
private async findImportableUsers(
communityId: mongoose.Types.ObjectId,
): Promise<UserDocument[]> {
const UserModel = await this.connectionService.getModel('user');
return UserModel.find({
communityId,
'riotAccounts.0': { $exists: true },
}).exec();
}
private toMemberWindowView(
user: UserDocument,
windowStart: Date,
windowEnd: Date,
): LegacyImportMemberWindowView {
const resolved = this.resolveMemberWindow(user, windowStart, windowEnd, new Map());
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
return {
userId: user._id.toString(),
puuid: account.puuid,
displayName:
user.kakaoTalkNickname ??
user.discordNickname ??
account.gameName ??
user._id.toString(),
gameName: account.gameName,
tagLine: account.tagLine,
profileIconId: account.profileIconId,
isActivated: user.isActivated,
startTime: resolved.startTime.toISOString(),
endTime: resolved.endTime.toISOString(),
};
}
private resolveMemberWindow(
user: UserDocument,
windowStart: Date,
windowEnd: Date,
overrides: Map<string, { startTime?: string; endTime?: string }>,
) {
const account =
user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ??
user.riotAccounts[0];
if (!account) throw new BadRequestException('Riot account not found.');
const override = overrides.get(user._id.toString());
const overrideStart = this.parseOptionalDate(override?.startTime);
const overrideEnd = this.parseOptionalDate(override?.endTime);
const activeEnd = user.isActivated ? windowEnd : user.updatedAt;
const startTime = this.maxDate(windowStart, user.createdAt, overrideStart);
const endTime = this.minDate(windowEnd, activeEnd, overrideEnd);
return {
userId: user._id,
puuid: account.puuid,
startTime,
endTime,
};
}
private resolveWindow(params: {
windowStart?: string;
windowEnd?: string;
}) {
const windowStart =
this.parseOptionalDate(params.windowStart) ??
new Date(LEGACY_IMPORT_DEFAULT_START_ISO);
const windowEnd = this.parseOptionalDate(params.windowEnd) ?? new Date();
if (windowStart.getTime() > windowEnd.getTime()) {
throw new BadRequestException('windowStart must be before windowEnd.');
}
return { windowStart, windowEnd };
}
private parseOptionalDate(value: string | undefined): Date | undefined {
if (!value) return undefined;
const parsed = new Date(value);
if (Number.isNaN(parsed.getTime())) {
throw new BadRequestException('Invalid date.');
}
return parsed;
}
private maxDate(...values: Array<Date | undefined>): Date {
return new Date(Math.max(...values.filter(Boolean).map((date) => date!.getTime())));
}
private minDate(...values: Array<Date | undefined>): Date {
return new Date(Math.min(...values.filter(Boolean).map((date) => date!.getTime())));
}
private formatLegacyDate(gameCreation: number): string {
return new Intl.DateTimeFormat('ko-KR', {
timeZone: 'Asia/Seoul',
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(gameCreation));
}
private communityLockKey(communityId: mongoose.Types.ObjectId): string {
return `legacy-import:lock:${communityId.toString()}`;
}
}
function isRiotMatchDto(value: unknown): value is RiotMatchDto {
return Boolean(
value &&
typeof value === 'object' &&
'metadata' in value &&
'info' in value,
);
}
@@ -0,0 +1,67 @@
import type { RiotRegionalRoute } from '../riot/riot.types';
export const LEGACY_IMPORT_DEFAULT_START_ISO = '2024-05-01T00:00:00.000Z';
export const LEGACY_IMPORT_LOCK_TTL_SECONDS = 6 * 60 * 60;
export const LEGACY_IMPORT_MEMBER_AVG_SECONDS = 60;
export interface LegacyImportMemberJob {
kind: 'legacy-import-member';
jobId: string;
parentJobId: string;
communityId: string;
userId: string;
puuid: string;
startTime: number;
endTime: number;
triggeredBy: string;
region: RiotRegionalRoute;
}
export interface LegacyImportMemberOverrideRequest {
userId: string;
startTime?: string;
endTime?: string;
}
export interface StartLegacyImportRequest {
windowStart?: string;
windowEnd?: string;
memberOverrides?: LegacyImportMemberOverrideRequest[];
}
export interface LegacyImportMemberWindowView {
userId: string;
puuid: string;
displayName: string;
gameName: string;
tagLine: string;
profileIconId: number;
isActivated: boolean;
startTime: string;
endTime: string;
}
export interface StartLegacyImportResponse {
jobId: string;
totalMembers: number;
etaSeconds: number;
}
export interface LegacyMatchListResponse {
matches: Array<{
matchId: string;
title: string;
scheduledAt: string;
riotMatchId: string | null;
memberCount: number;
externalCount: number;
blueScore: number;
redScore: number;
winnerSide?: 'blue' | 'red';
}>;
nextCursor: number | null;
}
export interface BulkDeleteLegacyMatchesRequest {
matchIds?: string[];
}
@@ -0,0 +1,189 @@
import mongoose from 'mongoose';
import type {
MatchGameResult,
MatchParticipant,
MatchTeam,
Position,
RiotAccount,
TeamSide,
UserDocument,
} from '../global/database/schema';
import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types';
const RIOT_BLUE_TEAM_ID = 100;
const RIOT_RED_TEAM_ID = 200;
export interface LegacyUserSnapshot {
userId: mongoose.Types.ObjectId;
account: RiotAccount;
displayName: string;
preferredPositions: UserDocument['preferredPositions'];
}
export type UserByPuuidMap = Map<string, LegacyUserSnapshot>;
export function buildUserByPuuidMap(users: UserDocument[]): UserByPuuidMap {
const entries = new Map<string, LegacyUserSnapshot>();
for (const user of users) {
for (const account of user.riotAccounts) {
entries.set(account.puuid, {
userId: user._id,
account,
displayName:
user.kakaoTalkNickname ??
user.discordNickname ??
account.gameName ??
user._id.toString(),
preferredPositions: user.preferredPositions ?? [],
});
}
}
return entries;
}
export function countKnownParticipants(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
): { team100: number; team200: number; total: number } {
const team100 = detail.info.participants.filter(
(participant) =>
participant.teamId === RIOT_BLUE_TEAM_ID && userByPuuid.has(participant.puuid),
).length;
const team200 = detail.info.participants.filter(
(participant) =>
participant.teamId === RIOT_RED_TEAM_ID && userByPuuid.has(participant.puuid),
).length;
return { team100, team200, total: team100 + team200 };
}
export function resolveTeam100IsBlue(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
): boolean {
const counts = countKnownParticipants(detail, userByPuuid);
return counts.team100 >= counts.team200;
}
export function buildParticipantsSnapshot(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
): MatchParticipant[] {
return detail.info.participants
.map((participant): MatchParticipant | null => {
const user = userByPuuid.get(participant.puuid);
if (!user) return null;
return {
userId: user.userId,
puuid: user.account.puuid,
gameName: user.account.gameName || participant.riotIdGameName,
tagLine: user.account.tagLine || participant.riotIdTagLine,
profileIconId: user.account.profileIconId,
tier:
user.account.tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ??
user.account.tiers[0],
preferredPositions: user.preferredPositions,
joinedAt: new Date(detail.info.gameCreation),
};
})
.filter((participant): participant is MatchParticipant => Boolean(participant));
}
export function buildTeams(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
team100IsBlue: boolean,
): MatchTeam[] {
return (['blue', 'red'] as TeamSide[]).map((side) => {
const teamId = resolveRiotTeamId(side, team100IsBlue);
const members = detail.info.participants
.filter((participant) => participant.teamId === teamId)
.map((participant) => {
const user = userByPuuid.get(participant.puuid);
if (!user) return null;
return {
userId: user.userId,
assignedPosition: resolveAssignedPosition(participant, user),
};
})
.filter((member): member is NonNullable<typeof member> => Boolean(member));
return {
side,
name: side === 'blue' ? '블루팀' : '레드팀',
members,
};
});
}
export function buildGameResult(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
team100IsBlue: boolean,
gameNumber = 1,
): MatchGameResult | null {
const winningTeam = detail.info.teams.find((team) => team.win);
if (!winningTeam) return null;
const winnerSide = resolveSide(winningTeam.teamId, team100IsBlue);
if (!winnerSide) return null;
const participants = detail.info.participants
.map((participant) => {
const user = userByPuuid.get(participant.puuid);
const side = resolveSide(participant.teamId, team100IsBlue);
if (!user || !side) return null;
return {
userId: user.userId,
side,
championId: participant.championId,
kills: participant.kills,
deaths: participant.deaths,
assists: participant.assists,
win: participant.win,
};
})
.filter((participant): participant is NonNullable<typeof participant> =>
Boolean(participant),
);
return {
gameNumber,
riotMatchId: detail.metadata.matchId,
winnerSide,
gameCreation: detail.info.gameCreation,
gameDuration: detail.info.gameDuration,
participants,
};
}
export function resolveExternalCount(
detail: RiotMatchDto,
userByPuuid: UserByPuuidMap,
): number {
return detail.info.participants.filter(
(participant) => !userByPuuid.has(participant.puuid),
).length;
}
function resolveRiotTeamId(side: TeamSide, team100IsBlue: boolean): number {
if (side === 'blue') {
return team100IsBlue ? RIOT_BLUE_TEAM_ID : RIOT_RED_TEAM_ID;
}
return team100IsBlue ? RIOT_RED_TEAM_ID : RIOT_BLUE_TEAM_ID;
}
function resolveSide(teamId: number, team100IsBlue: boolean): TeamSide | null {
if (teamId === RIOT_BLUE_TEAM_ID) return team100IsBlue ? 'blue' : 'red';
if (teamId === RIOT_RED_TEAM_ID) return team100IsBlue ? 'red' : 'blue';
return null;
}
function resolveAssignedPosition(
participant: RiotMatchParticipantDto,
user: LegacyUserSnapshot,
): Position {
const lane = participant.teamPosition || participant.individualPosition;
if (lane === 'TOP') return 'TOP';
if (lane === 'JUNGLE') return 'JGL';
if (lane === 'MIDDLE') return 'MID';
if (lane === 'BOTTOM') return 'ADC';
if (lane === 'UTILITY') return 'SUP';
return user.preferredPositions[0]?.position ?? 'TOP';
}
+2 -1
View File
@@ -1,10 +1,11 @@
import { Module } from '@nestjs/common';
import { CommunityStatsModule } from '../community-stats/community-stats.module';
import { TournamentCodeModule } from '../tournament-code/tournament-code.module';
import { MatchController } from './match.controller';
import { MatchService } from './match.service';
@Module({
imports: [TournamentCodeModule],
imports: [TournamentCodeModule, CommunityStatsModule],
controllers: [MatchController],
providers: [MatchService],
exports: [MatchService],
@@ -4,6 +4,7 @@ import {
NotFoundException,
} from '@nestjs/common';
import mongoose from 'mongoose';
import { CommunityStatsService } from '../community-stats/community-stats.service';
import { ConnectionService } from '../global/database/connection.service';
import {
Match,
@@ -46,6 +47,7 @@ export class MatchService {
constructor(
private readonly connectionService: ConnectionService,
private readonly tournamentCodeService: TournamentCodeService,
private readonly communityStatsService: CommunityStatsService,
) {}
public async create(params: CreateMatchParams): Promise<MatchDocument> {
@@ -140,6 +142,7 @@ export class MatchService {
}
await this.tournamentCodeService.releaseFromMatch(match);
await match.deleteOne();
await this.communityStatsService.invalidateCommunity(params.communityId);
}
public async join(params: JoinMatchParams): Promise<MatchDocument> {
@@ -1,4 +1,5 @@
import { forwardRef, Module } from '@nestjs/common';
import { LegacyImportModule } from '../legacy-import/legacy-import.module';
import { RiotModule } from '../riot/riot.module';
import { TournamentResultModule } from '../tournament-result/tournament-result.module';
import { RiotJobQueueController } from './riot-job-queue.controller';
@@ -7,7 +8,7 @@ import { RiotJobWorkerService } from './riot-job-worker.service';
import { RiotRefreshGateway } from './riot-refresh.gateway';
@Module({
imports: [RiotModule, forwardRef(() => TournamentResultModule)],
imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)],
controllers: [RiotJobQueueController],
providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway],
exports: [RiotJobQueueService],
@@ -4,6 +4,7 @@ import type {
} from '../riot/riot.types';
import type { RiotQueueGroup } from '../riot/riot-queue.constants';
import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types';
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
export const RIOT_JOB_HIGH_STREAM = 'riot:queue:high';
export const RIOT_JOB_LOW_STREAM = 'riot:queue:low';
@@ -33,7 +34,10 @@ export interface RiotRefreshSubJob {
priority: RiotJobPriority;
}
export type RiotJobPayload = RiotRefreshSubJob | PollTournamentResultJob;
export type RiotJobPayload =
| RiotRefreshSubJob
| PollTournamentResultJob
| LegacyImportMemberJob;
export interface RiotJobStatus {
jobId: string;
@@ -7,6 +7,8 @@ import {
import mongoose from 'mongoose';
import { ConnectionService } from '../global/database/connection.service';
import { GarnetService, StreamEntry } from '../global/garnet/garnet.service';
import { LegacyImportService } from '../legacy-import/legacy-import.service';
import type { LegacyImportMemberJob } from '../legacy-import/legacy-import.types';
import { RiotRecentMatchesService } from '../riot/riot-recent-matches.service';
import {
RIOT_JOB_GROUP,
@@ -36,6 +38,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
private readonly connectionService: ConnectionService,
private readonly refreshGateway: RiotRefreshGateway,
private readonly tournamentResultService: TournamentResultService,
private readonly legacyImportService: LegacyImportService,
) {}
public async onModuleInit() {
@@ -86,6 +89,10 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
await this.tournamentResultService.processPollJob(job);
return;
}
if (this.isLegacyImportJob(job)) {
await this.legacyImportService.processMemberJob(job);
return;
}
await this.jobQueueService.markProcessing(job);
for (const queueId of job.queueIds) {
@@ -107,6 +114,14 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
);
return;
}
if (this.isLegacyImportJob(job)) {
this.logger.warn(
`Legacy import member job failed ${job.jobId}: ${
error instanceof Error ? error.message : error
}`,
);
return;
}
const event = await this.jobQueueService.markFailed(job, error);
this.refreshGateway.broadcastRefreshEvent(event);
@@ -154,6 +169,12 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy {
return job.kind === 'poll-tournament-result';
}
private isLegacyImportJob(
job: RiotJobPayload,
): job is LegacyImportMemberJob {
return job.kind === 'legacy-import-member';
}
private async readOne(
stream: string,
blockMs: number,
+10
View File
@@ -12,6 +12,8 @@ import AuctionPage from './pages/AuctionPage';
import UserHistoryPage from './pages/UserHistoryPage';
import CommunityInternalStatsPage from './pages/CommunityInternalStatsPage';
import InternalMatchDetailPage from './pages/InternalMatchDetailPage';
import LegacyImportPage from './pages/admin/LegacyImportPage';
import LegacyMatchesPage from './pages/admin/LegacyMatchesPage';
import TournamentCodesPage from './pages/admin/TournamentCodesPage';
function MsalHeaderActions() {
@@ -86,6 +88,14 @@ function App() {
path="/admin/communities/:cid/tournament-codes"
element={<TournamentCodesPage />}
/>
<Route
path="/admin/communities/:cid/legacy-import"
element={<LegacyImportPage />}
/>
<Route
path="/admin/communities/:cid/legacy-matches"
element={<LegacyMatchesPage />}
/>
</Routes>
<DevAuthSwitcher />
</div>
+114
View File
@@ -16,6 +16,9 @@ import type {
ApiInternalMatchDetailResponse,
ApiInternalMatchListResponse,
ApiLeaderboardResponse,
LegacyImportJobsResponse,
LegacyImportMembersResponse,
LegacyMatchListResponse,
ApiMatch,
ApiRecentMatchesResponse,
ApiRecentSummaryResponse,
@@ -24,6 +27,8 @@ import type {
ApiUserInternalHistoryResponse,
ApiUserHistoryProfile,
DdragonManifest,
StartLegacyImportRequest,
StartLegacyImportResponse,
MatchStatus,
MatchesResponse,
MeResponse,
@@ -505,6 +510,115 @@ export function usePollTournamentResult(communityId = DEFAULT_COMMUNITY_ID) {
});
}
export function useLegacyImportMembers(
options: { windowStart?: string; windowEnd?: string },
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: [
'legacy-import-members',
communityId,
options.windowStart ?? null,
options.windowEnd ?? null,
],
queryFn: () => {
const searchParams = new URLSearchParams();
if (options.windowStart) searchParams.set('windowStart', options.windowStart);
if (options.windowEnd) searchParams.set('windowEnd', options.windowEnd);
const queryString = searchParams.toString();
return apiFetch<LegacyImportMembersResponse>(
`/communities/${communityId}/legacy-import/members${queryString ? `?${queryString}` : ''}`,
);
},
enabled: Boolean(communityId && enabled),
});
}
export function useLegacyImportJobs(
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useQuery({
queryKey: ['legacy-import-jobs', communityId],
queryFn: () =>
apiFetch<LegacyImportJobsResponse>(
`/communities/${communityId}/legacy-import-jobs?limit=10`,
),
enabled: Boolean(communityId && enabled),
refetchInterval: (query) =>
query.state.data?.jobs.some(
(job) => job.state === 'pending' || job.state === 'running',
)
? 5_000
: false,
});
}
export function useStartLegacyImport(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (body: StartLegacyImportRequest) =>
apiFetch<StartLegacyImportResponse>(
`/communities/${communityId}/legacy-import`,
{
method: 'POST',
body: JSON.stringify(body),
},
),
});
}
export function useCancelLegacyImport(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (jobId: string) =>
apiFetch<void>(
`/communities/${communityId}/legacy-import-jobs/${jobId}/cancel`,
{ method: 'POST' },
),
});
}
export function useLegacyMatches(
communityId = DEFAULT_COMMUNITY_ID,
enabled = true,
) {
return useInfiniteQuery({
queryKey: ['legacy-matches', communityId],
queryFn: ({ pageParam }) => {
const searchParams = new URLSearchParams({ limit: '50' });
if (pageParam) searchParams.set('cursor', String(pageParam));
return apiFetch<LegacyMatchListResponse>(
`/communities/${communityId}/legacy-matches?${searchParams.toString()}`,
);
},
initialPageParam: null as number | null,
getNextPageParam: (lastPage) => lastPage.nextCursor,
enabled: Boolean(communityId && enabled),
});
}
export function useDeleteMatch(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (matchId: string) =>
apiFetch<void>(`/communities/${communityId}/matches/${matchId}`, {
method: 'DELETE',
}),
});
}
export function useBulkDeleteLegacyMatches(communityId = DEFAULT_COMMUNITY_ID) {
return useMutation({
mutationFn: (matchIds: string[]) =>
apiFetch<{ deleted: number }>(
`/communities/${communityId}/legacy-matches/bulk-delete`,
{
method: 'POST',
body: JSON.stringify({ matchIds }),
},
),
});
}
export function useMe() {
const authUserId = useAuthUserId();
const { accounts, inProgress, instance } = useMsal();
+91
View File
@@ -613,6 +613,97 @@ export interface ApiUserInternalHistoryResponse {
lastFetchedAt: string | null;
}
export type LegacyImportJobState =
| 'pending'
| 'running'
| 'completed'
| 'failed'
| 'cancelled';
export interface LegacyImportMemberWindow {
userId: string;
puuid: string;
displayName: string;
gameName: string;
tagLine: string;
profileIconId: number;
isActivated: boolean;
startTime: string;
endTime: string;
}
export interface LegacyImportMembersResponse {
members: LegacyImportMemberWindow[];
}
export interface StartLegacyImportRequest {
windowStart?: string;
windowEnd?: string;
memberOverrides?: Array<{
userId: string;
startTime?: string;
endTime?: string;
}>;
}
export interface StartLegacyImportResponse {
jobId: string;
totalMembers: number;
etaSeconds: number;
}
export interface LegacyImportJob {
_id: string;
jobId: string;
communityId: string;
triggeredBy: string;
startedAt: string;
completedAt?: string;
state: LegacyImportJobState;
windowStart: string;
windowEnd: string;
memberOverrides: Array<{
userId: string;
puuid: string;
startTime: string;
endTime: string;
}>;
totalMembers: number;
processedMembers: number;
totalDiscoveredMatchIds: number;
totalImportedMatches: number;
totalSkippedDuplicate: number;
totalErrors: number;
averageMemberSeconds?: number;
errors?: Array<{
puuid?: string;
matchId?: string;
reason: string;
at: string;
}>;
}
export interface LegacyImportJobsResponse {
jobs: LegacyImportJob[];
}
export interface LegacyMatchListItem {
matchId: string;
title: string;
scheduledAt: string;
riotMatchId: string | null;
memberCount: number;
externalCount: number;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
}
export interface LegacyMatchListResponse {
matches: LegacyMatchListItem[];
nextCursor: number | null;
}
export type ApiRiotJobPriority = 'high' | 'low';
export type ApiRiotJobState = 'queued' | 'processing' | 'completed' | 'failed';
@@ -0,0 +1,406 @@
import { useEffect, useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Link, useParams } from 'react-router';
import {
useCancelLegacyImport,
useLegacyImportJobs,
useLegacyImportMembers,
useMe,
useStartLegacyImport,
} from '../../api/hooks';
import type { LegacyImportJob, StartLegacyImportRequest } from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config';
const DEFAULT_START = '2024-05-01T00:00:00.000Z';
function toInputValue(value: string) {
const date = new Date(value);
const local = new Date(date.getTime() - date.getTimezoneOffset() * 60_000);
return local.toISOString().slice(0, 16);
}
function fromInputValue(value: string) {
return value ? new Date(value).toISOString() : undefined;
}
function formatDate(value: string | undefined) {
if (!value) return '-';
return new Intl.DateTimeFormat('ko-KR', {
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function formatEta(seconds: number) {
if (seconds < 60) return `${Math.max(1, Math.ceil(seconds))}초`;
if (seconds < 3600) return `${Math.ceil(seconds / 60)}분`;
return `${Math.ceil(seconds / 3600)}시간`;
}
function progress(job: LegacyImportJob) {
if (job.totalMembers === 0) return 100;
return Math.round((job.processedMembers / job.totalMembers) * 100);
}
function JobCard({
job,
onCancel,
cancelling,
}: {
job: LegacyImportJob;
onCancel: (jobId: string) => void;
cancelling: boolean;
}) {
const running = job.state === 'pending' || job.state === 'running';
const remaining = Math.max(0, job.totalMembers - job.processedMembers);
const eta = remaining * (job.averageMemberSeconds ?? 60);
return (
<div className="border border-base-content/10 bg-base-100 p-4">
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-3">
<div>
<div className="text-[11px] font-mono text-base-content/35">
{job.jobId}
</div>
<div className="mt-1 flex flex-wrap items-center gap-2">
<span className="text-sm font-black text-base-content">
{job.state}
</span>
<span className="text-xs text-base-content/40">
{job.processedMembers}/{job.totalMembers}명 · 발견{' '}
{job.totalDiscoveredMatchIds} · import {job.totalImportedMatches} ·
중복 {job.totalSkippedDuplicate} · 에러 {job.totalErrors}
</span>
</div>
</div>
{running && (
<button
type="button"
className="btn btn-ghost btn-xs px-3 text-red-400"
disabled={cancelling}
onClick={() => onCancel(job.jobId)}
>
취소
</button>
)}
</div>
<div className="mt-3 h-2 bg-base-content/8">
<div
className="h-full bg-primary"
style={{ width: `${progress(job)}%` }}
/>
</div>
<div className="mt-2 flex flex-wrap justify-between gap-2 text-[11px] text-base-content/35">
<span>
{formatDate(job.windowStart)} ~ {formatDate(job.windowEnd)}
</span>
<span>{running ? `예상 남은 시간 ${formatEta(eta)}` : formatDate(job.completedAt)}</span>
</div>
</div>
);
}
export default function LegacyImportPage() {
const { cid } = useParams();
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const queryClient = useQueryClient();
const meQuery = useMe();
const [windowStart, setWindowStart] = useState(toInputValue(DEFAULT_START));
const [windowEnd, setWindowEnd] = useState('');
const [message, setMessage] = useState<string | null>(null);
const [overrides, setOverrides] = useState<
Record<string, { startTime: string; endTime: string }>
>({});
const currentUser =
meQuery.data?.memberships.find(
(membership) => membership.community?._id === communityId,
)?.user ?? null;
const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin';
const membersQuery = useLegacyImportMembers(
{
windowStart: fromInputValue(windowStart),
windowEnd: fromInputValue(windowEnd),
},
communityId,
canManage,
);
const jobsQuery = useLegacyImportJobs(communityId, canManage);
const startMutation = useStartLegacyImport(communityId);
const cancelMutation = useCancelLegacyImport(communityId);
const members = membersQuery.data?.members ?? [];
useEffect(() => {
setOverrides(
Object.fromEntries(
members.map((member) => [
member.userId,
{
startTime: toInputValue(member.startTime),
endTime: toInputValue(member.endTime),
},
]),
),
);
}, [members]);
const manageableMemberships =
meQuery.data?.memberships.filter((membership) => {
const role = membership.user.role;
return Boolean(
membership.community && (role === 'owner' || role === 'admin'),
);
}) ?? [];
const runningJob = useMemo(
() =>
jobsQuery.data?.jobs.find(
(job) => job.state === 'pending' || job.state === 'running',
),
[jobsQuery.data?.jobs],
);
async function invalidate() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['legacy-import-jobs', communityId] }),
queryClient.invalidateQueries({ queryKey: ['legacy-matches', communityId] }),
queryClient.invalidateQueries({
queryKey: ['community-internal-stats-matches', communityId],
}),
queryClient.invalidateQueries({
queryKey: ['community-internal-stats-leaderboard', communityId],
}),
]);
}
function handleStart() {
if (!window.confirm('과거 type=tourney 매치 백필을 시작할까요? 야간/유휴 시간대 실행을 권장합니다.')) {
return;
}
const payload: StartLegacyImportRequest = {
windowStart: fromInputValue(windowStart),
windowEnd: fromInputValue(windowEnd),
memberOverrides: members.map((member) => ({
userId: member.userId,
startTime: fromInputValue(overrides[member.userId]?.startTime ?? ''),
endTime: fromInputValue(overrides[member.userId]?.endTime ?? ''),
})),
};
startMutation.mutate(payload, {
onSuccess: async (result) => {
await invalidate();
setMessage(
`백필 작업을 시작했습니다. ${result.totalMembers}명, 예상 ${formatEta(result.etaSeconds)}.`,
);
},
onError: (error) => {
setMessage(error instanceof Error ? error.message : '백필 시작 실패');
},
});
}
if (!communityId) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">커뮤니티 설정이 필요합니다</h1>
</main>
);
}
if (meQuery.isPending) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한 확인 중...</h1>
</main>
);
}
if (!canManage) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한이 필요합니다</h1>
<p className="mt-2 text-sm text-base-content/40">
Legacy 백필은 owner/admin만 실행할 수 있습니다.
</p>
{manageableMemberships.length > 0 && (
<div className="mt-5 flex flex-wrap justify-center gap-2">
{manageableMemberships.map((membership) => (
<Link
key={membership.community?._id ?? membership.user._id}
to={`/admin/communities/${membership.community?._id}/legacy-import`}
className="btn btn-primary btn-sm px-4 text-xs"
>
{membership.community?.name ?? '관리 가능한 커뮤니티'}로 이동
</Link>
))}
</div>
)}
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link to="/" className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5">
← 목록으로
</Link>
<div className="mb-6 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
<div>
<h1 className="text-2xl font-black text-base-content">
Legacy 내전 백필
</h1>
<p className="mt-1 text-sm text-base-content/45">
커뮤니티 멤버 PUUID로 과거 `type=tourney` 매치를 찾아 내전 기록으로 import합니다.
</p>
</div>
<Link
to={`/admin/communities/${communityId}/legacy-matches`}
className="btn btn-ghost btn-sm px-4 text-xs"
>
Legacy 매치 정리
</Link>
</div>
<section className="border border-base-content/10 bg-base-100 p-4 mb-6">
<h2 className="text-sm font-bold mb-3">검색 윈도우</h2>
<div className="grid sm:grid-cols-[1fr_1fr_auto] gap-3 items-end">
<label className="text-xs text-base-content/45">
시작일
<input
type="datetime-local"
value={windowStart}
onChange={(event) => setWindowStart(event.target.value)}
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-xs"
/>
</label>
<label className="text-xs text-base-content/45">
종료일
<input
type="datetime-local"
value={windowEnd}
onChange={(event) => setWindowEnd(event.target.value)}
placeholder="비우면 지금"
className="mt-1 w-full border border-base-content/10 bg-transparent px-3 py-2 text-xs"
/>
</label>
<button
type="button"
className="btn btn-primary btn-sm px-5 text-xs"
disabled={startMutation.isPending || Boolean(runningJob)}
onClick={handleStart}
>
{runningJob
? '작업 진행 중'
: startMutation.isPending
? '시작 중...'
: '백필 시작'}
</button>
</div>
{message && (
<div className="mt-3 border border-primary/15 bg-primary/5 px-3 py-2 text-xs text-base-content/55">
{message}
</div>
)}
</section>
<section className="border border-base-content/10 bg-base-100 overflow-hidden mb-6">
<div className="px-4 py-3 border-b border-base-content/10">
<h2 className="text-sm font-bold">멤버별 윈도우</h2>
<p className="mt-1 text-[11px] text-base-content/35">
기본 시작일은 max(2024-05-01, 가입일), 비활성 멤버는 종료일이 마지막 업데이트 시각으로 잡힙니다.
</p>
</div>
<div className="overflow-x-auto">
<table className="w-full min-w-[900px] text-left">
<thead>
<tr className="bg-base-200/40 border-b border-base-content/10 text-[11px] uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2">멤버</th>
<th className="px-3 py-2">Riot ID</th>
<th className="px-3 py-2">상태</th>
<th className="px-3 py-2">시작</th>
<th className="px-3 py-2">종료</th>
</tr>
</thead>
<tbody>
{members.map((member) => (
<tr key={member.userId} className="border-b border-base-content/5">
<td className="px-3 py-2 text-sm font-bold">
{member.displayName}
</td>
<td className="px-3 py-2 text-xs text-base-content/45">
{member.gameName}#{member.tagLine}
</td>
<td className="px-3 py-2 text-xs">
{member.isActivated ? '활성' : '비활성'}
</td>
<td className="px-3 py-2">
<input
type="datetime-local"
value={overrides[member.userId]?.startTime ?? ''}
onChange={(event) =>
setOverrides((current) => ({
...current,
[member.userId]: {
...current[member.userId],
startTime: event.target.value,
endTime: current[member.userId]?.endTime ?? '',
},
}))
}
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
/>
</td>
<td className="px-3 py-2">
<input
type="datetime-local"
value={overrides[member.userId]?.endTime ?? ''}
onChange={(event) =>
setOverrides((current) => ({
...current,
[member.userId]: {
...current[member.userId],
startTime: current[member.userId]?.startTime ?? '',
endTime: event.target.value,
},
}))
}
className="border border-base-content/10 bg-transparent px-2 py-1 text-xs"
/>
</td>
</tr>
))}
{members.length === 0 && (
<tr>
<td colSpan={5} className="px-4 py-8 text-center text-sm text-base-content/35">
Riot 계정이 있는 멤버가 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
<section className="space-y-3">
<h2 className="text-sm font-bold">작업 이력</h2>
{(jobsQuery.data?.jobs ?? []).map((job) => (
<JobCard
key={job.jobId}
job={job}
cancelling={cancelMutation.isPending}
onCancel={(jobId) =>
cancelMutation.mutate(jobId, {
onSuccess: invalidate,
})
}
/>
))}
{(jobsQuery.data?.jobs ?? []).length === 0 && (
<div className="border border-base-content/10 bg-base-100 px-4 py-8 text-center text-sm text-base-content/35">
아직 실행한 백필 작업이 없습니다.
</div>
)}
</section>
</main>
);
}
@@ -0,0 +1,224 @@
import { useMemo, useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Link, useParams } from 'react-router';
import {
useBulkDeleteLegacyMatches,
useDeleteMatch,
useLegacyMatches,
useMe,
} from '../../api/hooks';
import type { LegacyMatchListItem } from '../../api/types';
import { DEFAULT_COMMUNITY_ID } from '../../config';
function formatDate(value: string) {
return new Intl.DateTimeFormat('ko-KR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
}).format(new Date(value));
}
function resultLabel(match: LegacyMatchListItem) {
if (!match.winnerSide) return '-';
return match.winnerSide === 'blue'
? `블루 ${match.blueScore}:${match.redScore}`
: `레드 ${match.redScore}:${match.blueScore}`;
}
export default function LegacyMatchesPage() {
const { cid } = useParams();
const communityId = cid ?? DEFAULT_COMMUNITY_ID;
const queryClient = useQueryClient();
const meQuery = useMe();
const [selected, setSelected] = useState<Record<string, boolean>>({});
const currentUser =
meQuery.data?.memberships.find(
(membership) => membership.community?._id === communityId,
)?.user ?? null;
const canManage = currentUser?.role === 'owner' || currentUser?.role === 'admin';
const matchesQuery = useLegacyMatches(communityId, canManage);
const deleteMutation = useDeleteMatch(communityId);
const bulkDeleteMutation = useBulkDeleteLegacyMatches(communityId);
const matches = matchesQuery.data?.pages.flatMap((page) => page.matches) ?? [];
const selectedIds = useMemo(
() => Object.entries(selected).filter(([, value]) => value).map(([id]) => id),
[selected],
);
async function invalidate() {
await Promise.all([
queryClient.invalidateQueries({ queryKey: ['legacy-matches', communityId] }),
queryClient.invalidateQueries({ queryKey: ['matches', communityId] }),
queryClient.invalidateQueries({
queryKey: ['community-internal-stats-matches', communityId],
}),
queryClient.invalidateQueries({
queryKey: ['community-internal-stats-leaderboard', communityId],
}),
]);
}
if (!communityId) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">커뮤니티 설정이 필요합니다</h1>
</main>
);
}
if (meQuery.isPending) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한 확인 중...</h1>
</main>
);
}
if (!canManage) {
return (
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
<h1 className="text-lg font-bold">권한이 필요합니다</h1>
<p className="mt-2 text-sm text-base-content/40">
Legacy 매치 정리는 owner/admin만 사용할 수 있습니다.
</p>
</main>
);
}
return (
<main className="max-w-6xl mx-auto px-4 sm:px-6 py-6">
<Link
to={`/admin/communities/${communityId}/legacy-import`}
className="inline-flex text-xs text-base-content/40 hover:text-base-content mb-5"
>
← Legacy 백필
</Link>
<div className="mb-6 flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3">
<div>
<h1 className="text-2xl font-black text-base-content">
Legacy 매치 정리
</h1>
<p className="mt-1 text-sm text-base-content/45">
백필로 들어온 매치를 확인하고 외부 토너먼트 기록을 삭제할 수 있습니다.
</p>
</div>
<button
type="button"
className="btn btn-ghost btn-sm px-4 text-xs text-red-400"
disabled={selectedIds.length === 0 || bulkDeleteMutation.isPending}
onClick={() => {
if (!window.confirm(`${selectedIds.length}개 매치를 삭제할까요?`)) return;
bulkDeleteMutation.mutate(selectedIds, {
onSuccess: async () => {
setSelected({});
await invalidate();
},
});
}}
>
선택 삭제 ({selectedIds.length})
</button>
</div>
<section className="border border-base-content/10 bg-base-100 overflow-hidden">
<div className="overflow-x-auto">
<table className="w-full min-w-[900px] text-left">
<thead>
<tr className="bg-base-200/40 border-b border-base-content/10 text-[11px] uppercase tracking-wider text-base-content/35">
<th className="px-3 py-2 w-8">
<input
type="checkbox"
checked={matches.length > 0 && selectedIds.length === matches.length}
onChange={(event) => {
const checked = event.target.checked;
setSelected(
Object.fromEntries(matches.map((match) => [match.matchId, checked])),
);
}}
/>
</th>
<th className="px-3 py-2">시간</th>
<th className="px-3 py-2">매치</th>
<th className="px-3 py-2">Riot matchId</th>
<th className="px-3 py-2">우리 멤버</th>
<th className="px-3 py-2">외부</th>
<th className="px-3 py-2">결과</th>
<th className="px-3 py-2 text-right">작업</th>
</tr>
</thead>
<tbody>
{matches.map((match) => (
<tr key={match.matchId} className="border-b border-base-content/5">
<td className="px-3 py-2">
<input
type="checkbox"
checked={Boolean(selected[match.matchId])}
onChange={(event) =>
setSelected((current) => ({
...current,
[match.matchId]: event.target.checked,
}))
}
/>
</td>
<td className="px-3 py-2 text-xs text-base-content/45">
{formatDate(match.scheduledAt)}
</td>
<td className="px-3 py-2">
<Link
to={`/communities/${communityId}/internal-stats/match/${match.matchId}`}
className="text-sm font-bold hover:text-primary"
>
{match.title}
</Link>
</td>
<td className="px-3 py-2 text-xs font-mono text-base-content/40">
{match.riotMatchId ?? '-'}
</td>
<td className="px-3 py-2 text-xs">{match.memberCount}명</td>
<td className="px-3 py-2 text-xs">{match.externalCount}명</td>
<td className="px-3 py-2 text-xs">{resultLabel(match)}</td>
<td className="px-3 py-2 text-right">
<button
type="button"
className="text-[11px] px-2 py-1 border border-red-500/20 text-red-400 hover:bg-red-500/10"
disabled={deleteMutation.isPending}
onClick={() => {
if (!window.confirm('이 매치를 삭제할까요?')) return;
deleteMutation.mutate(match.matchId, {
onSuccess: invalidate,
});
}}
>
삭제
</button>
</td>
</tr>
))}
{matches.length === 0 && (
<tr>
<td colSpan={8} className="px-4 py-10 text-center text-sm text-base-content/35">
Legacy import 매치가 없습니다.
</td>
</tr>
)}
</tbody>
</table>
</div>
</section>
{matchesQuery.hasNextPage && (
<button
type="button"
className="mt-3 w-full border border-base-content/15 bg-base-100 py-3 text-sm font-bold text-base-content/60 hover:text-primary hover:border-primary/30 disabled:opacity-40"
disabled={matchesQuery.isFetchingNextPage}
onClick={() => matchesQuery.fetchNextPage()}
>
{matchesQuery.isFetchingNextPage ? '불러오는 중...' : '+ 더 보기'}
</button>
)}
</main>
);
}
+31 -12
View File
@@ -2,11 +2,16 @@
## Context
현재 상태:
현재 상태 (이미 가동 중인 인프라):
- 내전(Internal Match) 데이터는 `Match.result.games[]` 에 저장되고, 각 게임은 `Match.result.riotMatchIds[]` 를 통해 `RiotMatch.raw`(Match-V5 원본) 와 연결됨. (`Tournament-Result-수집-플랜.md` 의 결과 수집 워커가 이 자리를 채움)
- 그러나 사용자가 "어떤 내전들이 있었고, 우리 커뮤니티 안에서 누가 어떻게 했는지" 를 한눈에 볼 페이지가 없음.
- 또한 `apps/web/src/pages/UserHistoryPage.tsx` 의 큐 탭(소협/칼바람/우르프/아레나) 에서 **내전을 별도로 볼 수 없음**. 내전은 queueId=0 (custom) 이라 일반 큐 필터에 잡히지 않고 일반 솔로/자유랭크와 섞여 무의미함.
- 내전(Internal Match) 데이터가 `Match.result.games[]` 에 저장되고 있음. 결과 수집 워커가 `match-v5 by-puuid?type=tourney` 폴링으로 `info.tournamentCode` 매칭해 자동으로 채움.
- 각 게임은 `Match.result.riotMatchIds[]` 를 통해 `RiotMatch.raw` (Match-V5 원본) 와 연결됨 — raw 는 영구 저장.
- `MatchHistoryModule` 의 aggregation·캐시 패턴(Garnet) 도 이미 사용 중.
해결할 문제:
- 사용자가 "어떤 내전들이 있었고, 우리 커뮤니티 안에서 누가 어떻게 했는지" 를 한눈에 볼 페이지가 없음.
- `apps/web/src/pages/UserHistoryPage.tsx` 의 큐 탭(소협/칼바람/우르프/아레나) 에서 **내전을 별도로 볼 수 없음**. 내전은 queueId=0 (custom) 이라 일반 큐 필터에 잡히지 않고 일반 솔로/자유랭크와 섞여 무의미함.
추가하려는 것:
@@ -228,14 +233,16 @@ interface InternalMatchDetailResponse {
### 캐시 키 / TTL
```
riot:communitystats:matches:<cid>:<seasonId>:<from?>:<to?>:<cursor?> # 1h
riot:communitystats:leaderboard:<cid>:<seasonId>:<from?>:<to?> # 1h
riot:communitystats:teamInsights:<cid>:<seasonId>:<from?>:<to?> # 1h
riot:communitystats:matchDetail:<matchId> # 24h (불변)
riot:userInternalStats:<userId>:<cid>:<seasonId>:<from?>:<to?> # 1h
riot:communitystats:matches:<cid>:<seasonId>:<from?>:<to?>:<cursor?> # 1h
riot:communitystats:leaderboard:<cid>:<seasonId>:<from?>:<to?> # 1h
riot:communitystats:teamInsights:<cid>:<seasonId>:<from?>:<to?> # 1h
riot:communitystats:matchDetail:<matchId> # 24h (불변)
riot:userInternalStats:<userId>:<cid>:<seasonId>:<from?>:<to?> # 1h
```
매치가 새로 finished 될 때 invalidate: `community-stats.service` 가 `match.service` 의 finished 전환 직후 cache prefix delete (`riot:communitystats:*:<cid>:*`). Garnet `scanIterator + del`.
invalidate 트리거: 결과 수집 워커가 매치를 `finished` 로 전환할 때 `CommunityStatsCacheService.invalidate(cid)` 호출 → `riot:communitystats:*:<cid>:*` + `riot:userInternalStats:*:<cid>:*` prefix scan delete (Garnet `scanIterator + del`).
> `CommunityStatsCacheService.invalidate(cid)` 는 단일 헬퍼로 export — 외부에서 매치를 새로 만들거나 삭제하는 다른 흐름이 생기면 같은 헬퍼 한 줄 호출.
### 시즌 / 기간 필터
@@ -342,8 +349,8 @@ queryKey 컨벤션 따름: `['community-stats', 'matches', cid, seasonId, from,
- (수정) `apps/api/src/modules/global/database/schema.ts` — `Match` 인덱스 보강: `{ communityId: 1, status: 1, scheduledAt: -1 }` (커뮤니티 finished 매치 정렬)
- (수정) `apps/api/src/app.module.ts` — `CommunityStatsModule` import
- (신규) `apps/api/src/modules/community-stats/*` (위 5 파일)
- (수정) `apps/api/src/modules/match/match.service.ts` — finished 전환 직후 cache invalidate 호출
- (신규) `apps/api/src/modules/community-stats/*` (위 5 파일) — `CommunityStatsCacheService.invalidate(cid)` 헬퍼 export
- (수정) `apps/api/src/modules/match/match.service.ts` — finished 전환 직후 invalidate 호출
- (수정) `apps/api/src/modules/match-history/match-history.service.ts` — `getRecentMatches` 등에 `queueGroup === 'internal'` 분기, 데이터 소스를 `Match.result.games` 로 전환
### 프런트
@@ -411,6 +418,17 @@ queryKey 컨벤션 따름: `['community-stats', 'matches', cid, seasonId, from,
- 운영자용 export (CSV/JSON 다운로드)
- 페어 통계 sortable 표 — UI 형태 (한 유저 선택 → 다른 유저 페어 / 모든 페어 매트릭스)
## 사용 가능한 인프라 (이미 가동 중)
본 plan 은 이미 동작 중인 다음 모듈/필드를 그대로 활용합니다 — 추가 셋업 불필요:
| 모듈 / 필드 | 본 plan 에서의 역할 |
|---|---|
| `Match.result.games[]` (결과 수집 워커가 채움) | **데이터 소스 1차 공급원**. status=finished 매치만 통계 대상. |
| `RiotMatch.raw` (영구 저장) | LCK 통계용 raw 필드 (GPM/KP/데미지/시야/farm) lookup 소스. API 호출 0회. |
| `MatchHistoryModule` 의 aggregation·Garnet 캐시 패턴 | `community-stats.service` / `community-stats-cache.service` 가 동일 패턴 재사용. |
| `useDdragonManifest` (web) | 챔피언 이름·아이콘 풀이. |
## Verification
### 백엔드
@@ -447,4 +465,5 @@ queryKey 컨벤션 따름: `['community-stats', 'matches', cid, seasonId, from,
- aggregation 응답 시간 p95 < 500ms (100 매치 기준)
- Garnet 캐시 hit ratio > 70%
- 매치가 새로 finished 전환된 후 다음 통계 조회가 fresh aggregation (cache invalidate 정상 동작)
- 매치 finished 전환 후 invalidate 정상 동작 (캐시 키 scan 로그)