This commit is contained in:
dahyeon committed 2026-05-02 02:59:33 -07:00
1 parent b152a5b0fa
commit 2379051196
32 files changed
+1682 -383

No files matched your search

@@ -40,6 +40,7 @@ export class AuctionController {
communityId,
captains: body.captains.map((c) => ({
side: c.side,
groupIndex: c.groupIndex ?? 1,
userId: new mongoose.Types.ObjectId(c.userId),
})),
initialPoints: body.initialPoints ?? 1000,
@@ -76,6 +77,7 @@ export class AuctionController {
return this.auctionService.placeBid({
matchId,
side: body.side,
groupIndex: body.groupIndex ?? 1,
amount: body.amount,
bidderUserId: this.resolveBidder(currentUser, body.bidderUserId),
});
@@ -30,6 +30,7 @@ interface JoinAuctionPayload {
interface BidPayload {
side: TeamSide;
groupIndex?: number;
amount: number;
bidderUserId?: string;
}
@@ -125,6 +126,7 @@ export class AuctionGateway
const auction = await this.auctionService.placeBid({
matchId: new mongoose.Types.ObjectId(matchId),
side: payload.side,
groupIndex: payload.groupIndex ?? 1,
amount: payload.amount,
bidderUserId,
});
+120 -28
View File
@@ -10,6 +10,7 @@ import {
AuctionDocument,
AuctionPlayerSnapshot,
AuctionTeam,
MatchParticipant,
MatchTeamMember,
Position,
TeamSide,
@@ -23,7 +24,11 @@ const AUCTION_MAX_TEAM_SIZE = 5;
interface StartAuctionParams {
matchId: mongoose.Types.ObjectId;
communityId: mongoose.Types.ObjectId;
captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[];
captains: {
side: TeamSide;
groupIndex: number;
userId: mongoose.Types.ObjectId;
}[];
initialPoints: number;
maxTimerSeconds: number;
}
@@ -31,6 +36,7 @@ interface StartAuctionParams {
interface PlaceBidParams {
matchId: mongoose.Types.ObjectId;
side: TeamSide;
groupIndex: number;
amount: number;
bidderUserId?: mongoose.Types.ObjectId;
}
@@ -66,30 +72,24 @@ export class AuctionService {
throw new BadRequestException('Auction already exists for this match.');
}
const activeParticipants = this.applyAuctionCut(match);
const desiredAuctionCount = activeParticipants.length;
if (desiredAuctionCount < 10) {
throw new BadRequestException('Not enough participants (need at least 10).');
}
const expectedCaptainCount = desiredAuctionCount / AUCTION_MAX_TEAM_SIZE;
const groupCount = expectedCaptainCount / 2;
if (params.captains.length !== expectedCaptainCount) {
throw new BadRequestException(
`Expected ${expectedCaptainCount} captains for ${desiredAuctionCount} participants.`,
);
}
this.assertCaptainAssignments(params.captains, activeParticipants, groupCount);
const captainUserIds = params.captains.map((c) => c.userId);
if (captainUserIds[0].equals(captainUserIds[1])) {
throw new BadRequestException('Captains must be different users.');
}
const captainParticipants = match.participants.filter((p) =>
captainUserIds.some((cid) => cid.equals(p.userId)),
);
if (captainParticipants.length !== 2) {
throw new BadRequestException(
'Both captains must be participants of the match.',
);
}
if (
match.participants.length >
params.captains.length * AUCTION_MAX_TEAM_SIZE
) {
throw new BadRequestException(
'Auction supports up to 5 members per team including captains.',
);
}
const basePlayerUsers = await UserModel.find({
_id: {
$in: match.participants
$in: activeParticipants
.filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId)))
.map((p) => p.userId),
},
@@ -130,7 +130,7 @@ export class AuctionService {
const nonCaptainPuuids = new Set<string>();
const order: AuctionPlayerSnapshot[] = [];
for (const participant of match.participants) {
for (const participant of activeParticipants) {
if (captainUserIds.some((cid) => cid.equals(participant.userId))) {
continue;
}
@@ -163,6 +163,7 @@ export class AuctionService {
phase: 'presenting',
teams: params.captains.map((c) => ({
side: c.side,
groupIndex: c.groupIndex,
captainUserId: c.userId,
points: params.initialPoints,
members: [],
@@ -204,6 +205,7 @@ export class AuctionService {
auction.phase = 'bidding';
auction.currentBid = 0;
auction.currentBidder = undefined;
auction.currentBidderGroupIndex = undefined;
auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds);
await auction.save();
return auction;
@@ -214,8 +216,8 @@ export class AuctionService {
if (auction.phase !== 'bidding') {
throw new BadRequestException('Auction is not in bidding phase.');
}
const team = auction.teams.find((t) => t.side === params.side);
if (!team) throw new BadRequestException('Unknown team side.');
const team = this.findAuctionTeam(auction, params.side, params.groupIndex);
if (!team) throw new BadRequestException('Unknown team.');
if (params.amount <= auction.currentBid) {
throw new BadRequestException('Bid must exceed current bid.');
}
@@ -227,11 +229,13 @@ export class AuctionService {
auction.currentBid = params.amount;
auction.currentBidder = params.side;
auction.currentBidderGroupIndex = params.groupIndex;
auction.currentDeadline = this.createDeadline(
this.resolveBidExtensionSeconds(auction),
);
auction.bids.push({
side: params.side,
groupIndex: params.groupIndex,
amount: params.amount,
bidderUserId: team.captainUserId,
timestamp: new Date(),
@@ -248,7 +252,11 @@ export class AuctionService {
if (!auction.currentBidder || auction.currentBid <= 0) {
throw new BadRequestException('No bid to mark sold.');
}
const team = auction.teams.find((t) => t.side === auction.currentBidder);
const team = this.findAuctionTeam(
auction,
auction.currentBidder,
auction.currentBidderGroupIndex ?? 1,
);
if (!team) throw new BadRequestException('Winning team not found.');
this.assertTeamHasSlot(team);
@@ -284,6 +292,7 @@ export class AuctionService {
auction.phase = 'presenting';
auction.currentBid = 0;
auction.currentBidder = undefined;
auction.currentBidderGroupIndex = undefined;
}
auction.currentDeadline = undefined;
await auction.save();
@@ -323,6 +332,9 @@ export class AuctionService {
match.status = 'recruiting';
match.teams = [];
match.tournamentCodeIds = [];
match.participants.forEach((participant) => {
participant.excluded = false;
});
match.teamBuiltAt = undefined;
match.result = undefined;
match.resultPollState = undefined;
@@ -337,6 +349,79 @@ export class AuctionService {
}
}
private applyAuctionCut(match: {
participants: MatchParticipant[];
}): MatchParticipant[] {
const ordered = [...match.participants].sort(
(left, right) => left.joinedAt.getTime() - right.joinedAt.getTime(),
);
const desiredAuctionCount = Math.floor(ordered.length / 10) * 10;
const activeIds = new Set(
ordered
.slice(0, desiredAuctionCount)
.map((participant) => participant.userId.toString()),
);
match.participants.forEach((participant) => {
participant.excluded = !activeIds.has(participant.userId.toString());
});
return ordered.slice(0, desiredAuctionCount);
}
private assertCaptainAssignments(
captains: StartAuctionParams['captains'],
activeParticipants: Array<{ userId: mongoose.Types.ObjectId }>,
groupCount: number,
): void {
const activeUserIds = new Set(
activeParticipants.map((participant) => participant.userId.toString()),
);
const captainUserIds = new Set<string>();
const teamKeys = new Set<string>();
const requiredKeys = new Set<string>();
for (let groupIndex = 1; groupIndex <= groupCount; groupIndex += 1) {
requiredKeys.add(`blue:${groupIndex}`);
requiredKeys.add(`red:${groupIndex}`);
}
for (const captain of captains) {
const userId = captain.userId.toString();
if (!activeUserIds.has(userId)) {
throw new BadRequestException(
'All captains must be active participants of the match.',
);
}
if (captainUserIds.has(userId)) {
throw new BadRequestException('Captains must be different users.');
}
captainUserIds.add(userId);
if (captain.groupIndex < 1 || captain.groupIndex > groupCount) {
throw new BadRequestException('Captain groupIndex is out of range.');
}
const key = `${captain.side}:${captain.groupIndex}`;
if (teamKeys.has(key)) {
throw new BadRequestException('Duplicate captain team assignment.');
}
teamKeys.add(key);
}
for (const key of requiredKeys) {
if (!teamKeys.has(key)) {
throw new BadRequestException('Each group needs one blue and one red captain.');
}
}
}
private findAuctionTeam(
auction: AuctionDocument,
side: TeamSide,
groupIndex: number,
): AuctionTeam | undefined {
return auction.teams.find(
(team) => team.side === side && (team.groupIndex ?? 1) === groupIndex,
);
}
private createDeadline(secondsFromNow: number): Date {
return new Date(Date.now() + secondsFromNow * 1000);
}
@@ -399,7 +484,8 @@ export class AuctionService {
return {
side: team.side,
name: this.resolveTeamName(team.side),
groupIndex: team.groupIndex ?? 1,
name: this.resolveTeamName(team.side, team.groupIndex ?? 1, auction.teams),
captainUserId: team.captainUserId,
members,
};
@@ -411,8 +497,14 @@ export class AuctionService {
await this.tournamentResultService.scheduleInitialPoll(match);
}
private resolveTeamName(side: TeamSide): string {
return side === 'blue' ? '블루팀' : '레드팀';
private resolveTeamName(
side: TeamSide,
groupIndex: number,
teams: AuctionTeam[],
): string {
const groupCount = new Set(teams.map((team) => team.groupIndex ?? 1)).size;
const sideLabel = side === 'blue' ? '블루팀' : '레드팀';
return groupCount <= 1 ? sideLabel : `${groupIndex}조 ${sideLabel}`;
}
}
@@ -17,6 +17,11 @@ class CaptainAssignmentDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsOptional()
@IsInt()
@Min(1)
groupIndex?: number;
@IsMongoId()
userId!: string;
}
@@ -24,7 +29,7 @@ class CaptainAssignmentDto {
export class StartAuctionDto {
@IsArray()
@ArrayMinSize(2)
@ArrayMaxSize(2)
@ArrayMaxSize(16)
@ValidateNested({ each: true })
@Type(() => CaptainAssignmentDto)
captains!: CaptainAssignmentDto[];
@@ -44,6 +49,11 @@ export class PlaceBidDto {
@IsEnum(TEAM_SIDES)
side!: TeamSide;
@IsOptional()
@IsInt()
@Min(1)
groupIndex?: number;
@IsInt()
@Min(1)
amount!: number;
+63 -1
View File
@@ -32,6 +32,13 @@ export const MATCH_STATUSES: MatchStatus[] = [
export type TeamSide = 'blue' | 'red';
export const TEAM_SIDES: TeamSide[] = ['blue', 'red'];
export type MatchGameMode = 'pair' | 'bracket' | 'round-robin';
export const MATCH_GAME_MODES: MatchGameMode[] = [
'pair',
'bracket',
'round-robin',
];
export type CommunityRole = 'owner' | 'admin' | 'member';
export const COMMUNITY_ROLES: CommunityRole[] = ['owner', 'admin', 'member'];
@@ -323,6 +330,7 @@ export interface MatchParticipant {
tier?: TierInfo;
preferredPositions: PositionPreference[];
joinedAt: Date;
excluded?: boolean;
}
export interface MatchTeamMember {
@@ -333,6 +341,7 @@ export interface MatchTeamMember {
export interface MatchTeam {
side: TeamSide;
groupIndex: number;
name: string;
captainUserId?: mongoose.Types.ObjectId;
members: MatchTeamMember[];
@@ -352,11 +361,21 @@ export interface MatchGameResult {
gameNumber: number;
riotMatchId: string;
winnerSide: TeamSide;
blueGroupIndex: number;
redGroupIndex: number;
gameCreation: number;
gameDuration: number;
participants: MatchGameResultParticipant[];
}
export interface MatchSeriesResult {
blueGroupIndex: number;
redGroupIndex: number;
blueScore: number;
redScore: number;
winnerSide?: TeamSide;
}
export interface MatchResult {
winnerSide?: TeamSide;
blueScore: number;
@@ -364,6 +383,7 @@ export interface MatchResult {
mvpUserId?: mongoose.Types.ObjectId;
riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들
games: MatchGameResult[];
seriesResults?: MatchSeriesResult[];
}
export interface MatchResultPollState {
@@ -389,6 +409,7 @@ export interface Match extends MongooseTimestamps {
scheduledAt: Date;
maxParticipants: number;
gameCount: number;
gameMode: MatchGameMode;
tournamentCodeIds: mongoose.Types.ObjectId[];
teamBuiltAt?: Date;
hostUserId?: mongoose.Types.ObjectId;
@@ -469,6 +490,7 @@ export interface AuctionTeamMember {
export interface AuctionTeam {
side: TeamSide;
groupIndex: number;
captainUserId: mongoose.Types.ObjectId;
points: number;
members: AuctionTeamMember[];
@@ -476,6 +498,7 @@ export interface AuctionTeam {
export interface AuctionBid {
side: TeamSide;
groupIndex?: number;
amount: number;
bidderUserId: mongoose.Types.ObjectId;
timestamp: Date;
@@ -490,6 +513,7 @@ export interface Auction extends MongooseTimestamps {
bids: AuctionBid[];
currentBid: number;
currentBidder?: TeamSide;
currentBidderGroupIndex?: number;
maxTimerSeconds: number;
currentDeadline?: Date;
initialPoints: number;
@@ -880,6 +904,7 @@ const MatchParticipantSubSchema = new Schema<MatchParticipant>(
default: [],
},
joinedAt: { type: Date, required: true, default: Date.now },
excluded: { type: Boolean, required: true, default: false },
},
{ _id: false },
);
@@ -896,6 +921,7 @@ const MatchTeamMemberSubSchema = new Schema<MatchTeamMember>(
const MatchTeamSubSchema = new Schema<MatchTeam>(
{
side: { type: String, enum: TEAM_SIDES, required: true },
groupIndex: { type: Number, required: true, default: 1, min: 1 },
name: { type: String, required: true },
captainUserId: { type: Schema.Types.ObjectId, ref: 'user' },
members: { type: [MatchTeamMemberSubSchema], required: true, default: [] },
@@ -922,6 +948,8 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
gameNumber: { type: Number, required: true },
riotMatchId: { type: String, required: true },
winnerSide: { type: String, enum: TEAM_SIDES, required: true },
blueGroupIndex: { type: Number, required: true, default: 1, min: 1 },
redGroupIndex: { type: Number, required: true, default: 1, min: 1 },
gameCreation: { type: Number, required: true },
gameDuration: { type: Number, required: true },
participants: {
@@ -933,6 +961,17 @@ const MatchGameResultSubSchema = new Schema<MatchGameResult>(
{ _id: false },
);
const MatchSeriesResultSubSchema = new Schema<MatchSeriesResult>(
{
blueGroupIndex: { type: Number, required: true, default: 1, min: 1 },
redGroupIndex: { type: Number, required: true, default: 1, min: 1 },
blueScore: { type: Number, required: true, default: 0 },
redScore: { type: Number, required: true, default: 0 },
winnerSide: { type: String, enum: TEAM_SIDES, required: false },
},
{ _id: false },
);
const MatchResultSubSchema = new Schema<MatchResult>(
{
winnerSide: { type: String, enum: TEAM_SIDES, required: false },
@@ -941,6 +980,11 @@ const MatchResultSubSchema = new Schema<MatchResult>(
mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' },
riotMatchIds: { type: [String], required: true, default: [] },
games: { type: [MatchGameResultSubSchema], required: true, default: [] },
seriesResults: {
type: [MatchSeriesResultSubSchema],
required: true,
default: [],
},
},
{ _id: false },
);
@@ -1001,8 +1045,23 @@ export const MatchSchema = new Schema<Match>(
default: 'recruiting',
},
scheduledAt: { type: Date, required: true },
maxParticipants: { type: Number, required: true, default: 10 },
maxParticipants: {
type: Number,
required: true,
default: 10,
min: 10,
validate: {
validator: (value: number) => Number.isInteger(value) && value % 10 === 0,
message: 'maxParticipants must be a multiple of 10.',
},
},
gameCount: { type: Number, required: true, default: 3 },
gameMode: {
type: String,
enum: MATCH_GAME_MODES,
required: true,
default: 'pair',
},
tournamentCodeIds: {
type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }],
required: true,
@@ -1156,6 +1215,7 @@ const AuctionTeamMemberSubSchema = new Schema<AuctionTeamMember>(
const AuctionTeamSubSchema = new Schema<AuctionTeam>(
{
side: { type: String, enum: TEAM_SIDES, required: true },
groupIndex: { type: Number, required: true, default: 1, min: 1 },
captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
points: { type: Number, required: true, default: 0 },
members: {
@@ -1170,6 +1230,7 @@ const AuctionTeamSubSchema = new Schema<AuctionTeam>(
const AuctionBidSubSchema = new Schema<AuctionBid>(
{
side: { type: String, enum: TEAM_SIDES, required: true },
groupIndex: { type: Number, required: true, default: 1, min: 1 },
amount: { type: Number, required: true },
bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true },
timestamp: { type: Date, required: true, default: Date.now },
@@ -1201,6 +1262,7 @@ export const AuctionSchema = new Schema<Auction>(
bids: { type: [AuctionBidSubSchema], required: true, default: [] },
currentBid: { type: Number, required: true, default: 0 },
currentBidder: { type: String, enum: TEAM_SIDES, required: false },
currentBidderGroupIndex: { type: Number, required: false },
maxTimerSeconds: { type: Number, required: true, default: 30 },
currentDeadline: { type: Date, required: false },
initialPoints: { type: Number, required: true, default: 1000 },
@@ -2,7 +2,22 @@ import { Injectable, Logger } from '@nestjs/common';
import { InfisicalSDK } from '@infisical/sdk';
import { ConfigService } from '@nestjs/config';
type SecretMap = Record<string, string | boolean | undefined>;
type SecretMap = Record<string, string | undefined>;
const DEFAULT_INFISICAL_SITE_URL = 'https://secret-manager.dahyeon.us/';
const IMDS_TOKEN_TTL_SECONDS = 60;
const IMDS_REQUEST_TIMEOUT_MS = 1500;
const FALLBACK_IMDS_BASE_URLS = [
'http://169.254.169.254',
'http://host.docker.internal:8675',
];
interface InfisicalBootstrapConfig {
siteUrl: string;
clientId: string;
clientSecret: string;
projectId: string;
}
@Injectable()
export class SecretService {
@@ -10,57 +25,8 @@ export class SecretService {
private secrets: SecretMap | null = null; // null = 아직 로드 전
private loading?: Promise<void>; // 진행 중인 로드(중복 호출 방지)
private infisicalClient: InfisicalSDK;
private readonly siteUrl: string;
private readonly clientSecret: string;
private readonly clientId: string;
private readonly projectId: string;
private readonly PROCESS_ENVS = [
'COSMOSDB_ENDPOINT',
'COSMOSDB_KEY',
'NATS_ENDPOINT',
'NATS_TOKEN',
'NATS_URL',
'DAKAO_INBOUND_SUBJECT',
'DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT',
'DAKAO_REPLY_SUBJECT_PREFIX',
'DAKAO_COMMAND_SOURCE',
'DAKAO_BOT_USER_ID',
'DAKAO_INSTANCE_ID',
'JWT_CLAIM_AUDIENCE',
'MICROSOFT_ENTRAID_TENANT_ID',
'MICROSOFT_ENTRAID_ALLOWED_ALGS',
'AUTH_DEV_HEADER_ENABLED',
// 필요시 추가
] as const;
constructor(private readonly config: ConfigService) {
this.siteUrl =
this.config.get<string>('INFISICAL_SITE_URL') ??
'https://secret-manager.dahyeon.us/';
this.clientSecret = this.config.get<string>(
'INFISICAL_CLIENT_SECRET',
) as string;
this.clientId = this.config.get<string>('INFISICAL_CLIENT_ID') as string;
this.projectId = this.config.get<string>('INFISICAL_PROJECT_ID') as string;
// console.log(this.siteUrl, this.clientSecret, this.clientId, this.projectId)
const missing = [
!this.siteUrl && 'INFISICAL_SITE_URL',
!this.clientId && 'INFISICAL_CLIENT_ID',
!this.clientSecret && 'INFISICAL_CLIENT_SECRET',
!this.projectId && 'INFISICAL_PROJECT_ID',
].filter(Boolean);
if (missing.length > 0) {
throw new Error(
`Missing required Infisical configuration: ${missing.join(', ')}`,
);
}
this.infisicalClient = new InfisicalSDK({ siteUrl: this.siteUrl });
}
constructor(private readonly config: ConfigService) {}
/** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */
private async fetchSecrets(): Promise<void> {
@@ -68,20 +34,24 @@ export class SecretService {
if (this.loading) return this.loading; // 로드 중이면 그거 기다리기
this.loading = (async () => {
await this.infisicalClient.auth().universalAuth.login({
clientId: this.clientId,
clientSecret: this.clientSecret,
const bootstrapConfig = await this.resolveInfisicalBootstrapConfig();
const infisicalClient = new InfisicalSDK({
siteUrl: bootstrapConfig.siteUrl,
});
// console.log(this.infisicalClient)
const res = await this.infisicalClient.secrets().listSecrets({
await infisicalClient.auth().universalAuth.login({
clientId: bootstrapConfig.clientId,
clientSecret: bootstrapConfig.clientSecret,
});
const res = await infisicalClient.secrets().listSecrets({
environment:
process.env.NODE_ENV === 'prod'
? 'prod'
: process.env.NODE_ENV === 'test'
? 'staging'
: 'dev',
projectId: this.projectId,
projectId: bootstrapConfig.projectId,
});
// 임시 객체에 채운 뒤 한 번에 교체(일관성 보장)
@@ -90,11 +60,10 @@ export class SecretService {
map[s.secretKey] = s.secretValue;
}
// 필요한 값은 process.env에 반영
for (const k of this.PROCESS_ENVS) {
const v = map[k as string];
// 앱 생명주기에서 필요한 env는 모두 SecretService가 process.env에 반영한다.
for (const [k, v] of Object.entries(map)) {
if (typeof v === 'string' && v.length > 0) {
process.env[k as string] = v;
process.env[k] = v;
}
}
@@ -111,6 +80,128 @@ export class SecretService {
}
}
private async resolveInfisicalBootstrapConfig(): Promise<InfisicalBootstrapConfig> {
const [clientId, clientSecret, projectId] = await Promise.all([
this.resolveBootstrapValue('INFISICAL_CLIENT_ID'),
this.resolveBootstrapValue('INFISICAL_CLIENT_SECRET'),
this.resolveBootstrapValue('INFISICAL_PROJECT_ID'),
]);
const siteUrl =
(await this.resolveBootstrapValue('INFISICAL_SITE_URL', false)) ??
DEFAULT_INFISICAL_SITE_URL;
const missing = [
!siteUrl && 'INFISICAL_SITE_URL',
!clientId && 'INFISICAL_CLIENT_ID',
!clientSecret && 'INFISICAL_CLIENT_SECRET',
!projectId && 'INFISICAL_PROJECT_ID',
].filter(Boolean);
if (missing.length > 0) {
throw new Error(
`Missing required Infisical bootstrap configuration: ${missing.join(', ')}`,
);
}
if (!clientId || !clientSecret || !projectId) {
throw new Error('Missing required Infisical bootstrap configuration.');
}
return {
siteUrl,
clientId,
clientSecret,
projectId,
};
}
private async resolveBootstrapValue(
key: string,
required = true,
): Promise<string | undefined> {
const configured = this.config.get<string>(key)?.trim();
if (configured) return configured;
const fromImds = await this.getImdsSecret(key);
if (fromImds) {
process.env[key] = fromImds;
return fromImds;
}
if (required) {
throw new Error(`Missing required bootstrap secret: ${key}`);
}
return undefined;
}
private async getImdsSecret(key: string): Promise<string | undefined> {
let lastError: Error | undefined;
for (const baseUrl of this.resolveImdsBaseUrls()) {
try {
const token = await this.issueImdsToken(baseUrl);
const secret = await this.fetchImdsText(
`${baseUrl.replace(/\/$/u, '')}/latest/meta-data/secrets/${encodeURIComponent(key)}`,
{
'X-aws-ec2-metadata-token': token,
},
);
return secret.trim() || undefined;
} catch (error) {
lastError = error instanceof Error ? error : new Error(String(error));
}
}
if (lastError) {
this.logger.debug(
`IMDS secret lookup failed for ${key}: ${lastError.message}`,
);
}
return undefined;
}
private resolveImdsBaseUrls(): string[] {
return [
this.config.get<string>('IMDS_BASE_URL'),
this.config.get<string>('MACHINE_METADATA_BASE_URL'),
...FALLBACK_IMDS_BASE_URLS,
]
.map((value) => value?.trim())
.filter((value): value is string => Boolean(value));
}
private async issueImdsToken(baseUrl: string): Promise<string> {
return this.fetchImdsText(
`${baseUrl.replace(/\/$/u, '')}/latest/api/token`,
{
'X-aws-ec2-metadata-token-ttl-seconds': String(IMDS_TOKEN_TTL_SECONDS),
},
'PUT',
);
}
private async fetchImdsText(
url: string,
headers: Record<string, string>,
method = 'GET',
): Promise<string> {
const controller = new AbortController();
const timeout = setTimeout(
() => controller.abort(),
IMDS_REQUEST_TIMEOUT_MS,
);
try {
const response = await fetch(url, {
method,
headers,
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`IMDS ${method} ${url} failed with ${response.status}`);
}
return response.text();
} finally {
clearTimeout(timeout);
}
}
/** lazy get: 필요할 때 처음 한번만 로드 */
public async get<T = string>(key: string, fallback?: T): Promise<T> {
if (!this.secrets) {
@@ -412,6 +412,15 @@ export class LegacyImportService {
redScore: winnerSide === 'red' ? 1 : 0,
riotMatchIds: [riotMatchId],
games: [gameResult],
seriesResults: [
{
blueGroupIndex: 1,
redGroupIndex: 1,
blueScore: winnerSide === 'blue' ? 1 : 0,
redScore: winnerSide === 'red' ? 1 : 0,
winnerSide,
},
],
};
await MatchModel.updateOne(
@@ -490,6 +499,7 @@ export class LegacyImportService {
scheduledAt: new Date(detail.info.gameCreation),
maxParticipants: 10,
gameCount: 1,
gameMode: 'pair',
tournamentCodeIds: [],
teamBuiltAt: new Date(detail.info.gameCreation),
hostUserId: new mongoose.Types.ObjectId(job.triggeredBy),
@@ -501,6 +511,15 @@ export class LegacyImportService {
redScore: winnerSide === 'red' ? 1 : 0,
riotMatchIds: [riotMatchId],
games: [gameResult],
seriesResults: [
{
blueGroupIndex: 1,
redGroupIndex: 1,
blueScore: winnerSide === 'blue' ? 1 : 0,
redScore: winnerSide === 'red' ? 1 : 0,
winnerSide,
},
],
},
legacyImported: true,
legacyImportSource: {
@@ -108,6 +108,7 @@ export function buildTeams(
.filter((member): member is NonNullable<typeof member> => Boolean(member));
return {
side,
groupIndex: 1,
name: side === 'blue' ? '블루팀' : '레드팀',
members,
};
@@ -147,6 +148,8 @@ export function buildGameResult(
gameNumber,
riotMatchId: detail.metadata.matchId,
winnerSide,
blueGroupIndex: 1,
redGroupIndex: 1,
gameCreation: detail.info.gameCreation,
gameDuration: detail.info.gameDuration,
participants,
@@ -2,6 +2,7 @@ import { Type } from 'class-transformer';
import {
ArrayMaxSize,
ArrayMinSize,
registerDecorator,
IsArray,
IsDate,
IsEnum,
@@ -12,9 +13,40 @@ import {
Min,
MinLength,
ValidateNested,
ValidationArguments,
ValidationOptions,
} from 'class-validator';
import { POSITIONS } from '../../global/database/schema';
import type { Position } from '../../global/database/schema';
import { MATCH_GAME_MODES, POSITIONS } from '../../global/database/schema';
import type { MatchGameMode, Position } from '../../global/database/schema';
function IsMultipleOf(
multiple: number,
validationOptions?: ValidationOptions,
): PropertyDecorator {
return (object, propertyName) => {
registerDecorator({
name: 'isMultipleOf',
target: object.constructor,
propertyName: String(propertyName),
constraints: [multiple],
options: validationOptions,
validator: {
validate(value: unknown, args: ValidationArguments) {
const [divisor] = args.constraints as [number];
return (
typeof value === 'number' &&
Number.isInteger(value) &&
value % divisor === 0
);
},
defaultMessage(args: ValidationArguments) {
const [divisor] = args.constraints as [number];
return `${args.property} must be a multiple of ${divisor}.`;
},
},
});
};
}
export class PositionPreferenceDto {
@IsEnum(POSITIONS)
@@ -56,7 +88,8 @@ export class CreateMatchDto {
@IsOptional()
@IsInt()
@Min(2)
@Min(10)
@IsMultipleOf(10)
maxParticipants?: number;
@IsOptional()
@@ -64,6 +97,10 @@ export class CreateMatchDto {
@Min(1)
gameCount?: number;
@IsOptional()
@IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -106,7 +143,8 @@ export class UpdateMatchDto {
@IsOptional()
@IsInt()
@Min(2)
@Min(10)
@IsMultipleOf(10)
maxParticipants?: number;
@IsOptional()
@@ -114,6 +152,10 @@ export class UpdateMatchDto {
@Min(1)
gameCount?: number;
@IsOptional()
@IsEnum(MATCH_GAME_MODES)
gameMode?: MatchGameMode;
@IsOptional()
@IsArray()
@IsString({ each: true })
@@ -54,6 +54,7 @@ export class MatchController {
scheduledAt: body.scheduledAt,
maxParticipants: body.maxParticipants ?? 10,
gameCount: body.gameCount,
gameMode: body.gameMode ?? 'pair',
prizes: body.prizes ?? [],
notices: body.notices ?? [],
schedule: body.schedule ?? [],
@@ -98,10 +98,30 @@ export class MatchService {
obj.result.games = [...obj.result.games].sort(
(left, right) => left.gameNumber - right.gameNumber,
);
if (!obj.result.seriesResults?.length) {
obj.result.seriesResults = [
{
blueGroupIndex: 1,
redGroupIndex: 1,
blueScore: obj.result.blueScore ?? 0,
redScore: obj.result.redScore ?? 0,
winnerSide: obj.result.winnerSide,
},
];
}
}
return {
...obj,
gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT,
gameMode: match.gameMode ?? 'pair',
participants: (obj.participants ?? []).map((participant) => ({
...participant,
excluded: participant.excluded ?? false,
})),
teams: (obj.teams ?? []).map((team) => ({
...team,
groupIndex: team.groupIndex ?? 1,
})),
tournamentCodes: await this.tournamentCodeService.buildSlots(match),
};
}
@@ -114,6 +134,14 @@ export class MatchService {
throw new BadRequestException('Match does not belong to this community.');
}
const previousStatus = match.status;
if (
previousStatus !== 'recruiting' &&
('maxParticipants' in params.patch || 'gameMode' in params.patch)
) {
throw new BadRequestException(
'maxParticipants and gameMode can only be changed while recruiting.',
);
}
match.set(params.patch);
if (
previousStatus !== 'recruiting' &&
@@ -183,6 +211,7 @@ export class MatchService {
tier: selectedTier,
preferredPositions: params.preferredPositions,
joinedAt: new Date(),
excluded: false,
});
await match.save();
return match;
@@ -220,7 +220,8 @@ export class TournamentCodeService {
if (!match) throw new NotFoundException('Match not found.');
match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const need = match.gameCount - match.tournamentCodeIds.length;
const requiredSlots = this.resolveRequiredSlots(match);
const need = requiredSlots - match.tournamentCodeIds.length;
if (need <= 0) return match;
const reservedIds: mongoose.Types.ObjectId[] = [];
@@ -311,7 +312,7 @@ export class TournamentCodeService {
const matches = await MatchModel.find(filter).exec();
let touched = 0;
for (const match of matches) {
if ((match.tournamentCodeIds?.length ?? 0) >= (match.gameCount || 0)) {
if ((match.tournamentCodeIds?.length ?? 0) >= this.resolveRequiredSlots(match)) {
continue;
}
const before = match.tournamentCodeIds?.length ?? 0;
@@ -325,7 +326,7 @@ export class TournamentCodeService {
public async buildSlots(match: MatchDocument): Promise<TournamentCodeSlotView[]> {
const TournamentCodeModel =
await this.connectionService.getModel('tournamentCode');
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const gameCount = this.resolveRequiredSlots(match);
const ids = match.tournamentCodeIds ?? [];
const codes =
ids.length > 0
@@ -341,8 +342,10 @@ export class TournamentCodeService {
const gameNumber = index + 1;
const code = byGameNumber.get(gameNumber);
if (!code) {
const seriesRef = this.resolveSeriesRefForGameNumber(match, gameNumber);
return {
gameNumber,
...seriesRef,
code: null,
expiresAt: null,
state: 'pending',
@@ -351,6 +354,7 @@ export class TournamentCodeService {
}
return {
gameNumber,
...this.resolveSeriesRefForGameNumber(match, gameNumber),
code: code.code,
expiresAt: code.expiresAt.toISOString(),
state: code.state,
@@ -362,4 +366,26 @@ export class TournamentCodeService {
private normalizeCode(code: string | undefined): string {
return (code ?? '').trim().toUpperCase();
}
private resolveRequiredSlots(match: MatchDocument): number {
const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const teamGroups = new Set(
(match.teams ?? []).map((team) => team.groupIndex ?? 1),
);
const activeParticipantCount = (match.participants ?? []).filter(
(participant) => !participant.excluded,
).length;
const participantGroups = Math.floor(activeParticipantCount / 10);
const groups = Math.max(1, teamGroups.size, participantGroups);
return groups * gameCount;
}
private resolveSeriesRefForGameNumber(
match: MatchDocument,
gameNumber: number,
): { blueGroupIndex: number; redGroupIndex: number } {
const perSeries = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT;
const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex };
}
}
@@ -24,6 +24,8 @@ export interface BulkUploadTournamentCodesResponse {
export interface TournamentCodeSlotView {
gameNumber: number;
blueGroupIndex: number;
redGroupIndex: number;
code: string | null;
expiresAt: string | null;
state: TournamentCodeState | 'pending';
@@ -39,11 +39,18 @@ export function collectTeamPuuids(
match: MatchDocument,
side: TeamSide,
lookup: MatchPuuidLookup,
groupIndex = 1,
): string[] {
const team = match.teams.find((item) => item.side === side);
const team = match.teams.find(
(item) => item.side === side && (item.groupIndex ?? 1) === groupIndex,
);
if (!team) return [];
return team.members
.map((member) => lookup.puuidByUserId.get(member.userId.toString()))
const userIds = [
...(team.captainUserId ? [team.captainUserId] : []),
...team.members.map((member) => member.userId),
];
return userIds
.map((userId) => lookup.puuidByUserId.get(userId.toString()))
.filter((puuid): puuid is string => Boolean(puuid));
}
@@ -52,10 +59,19 @@ export function computeGameResult(params: {
detail: RiotMatchDto;
gameNumber: number;
lookup: MatchPuuidLookup;
blueGroupIndex?: number;
redGroupIndex?: number;
}): MatchGameResult | null {
const { match, detail, gameNumber, lookup } = params;
const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup);
const ourRedPuuids = collectTeamPuuids(match, 'red', lookup);
const {
match,
detail,
gameNumber,
lookup,
blueGroupIndex = 1,
redGroupIndex = 1,
} = params;
const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup, blueGroupIndex);
const ourRedPuuids = collectTeamPuuids(match, 'red', lookup, redGroupIndex);
const team100Puuids = detail.info.participants
.filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID)
.map((participant) => participant.puuid);
@@ -106,6 +122,8 @@ export function computeGameResult(params: {
gameNumber,
riotMatchId: detail.metadata.matchId,
winnerSide,
blueGroupIndex,
redGroupIndex,
gameCreation: detail.info.gameCreation,
gameDuration: detail.info.gameDuration,
participants,
@@ -210,6 +210,7 @@ export class TournamentResultService {
detail,
gameNumber: code.gameNumber,
lookup,
...this.resolveSeriesRefForGameNumber(match, code.gameNumber),
});
if (!gameResult) {
this.logger.warn(
@@ -235,7 +236,7 @@ export class TournamentResultService {
match: MatchDocument,
codes: TournamentCodeDocument[],
): Promise<boolean> {
if (codes.length < match.gameCount) return false;
if (codes.length < this.resolveRequiredGameSlots(match)) return false;
if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) {
return false;
}
@@ -399,9 +400,71 @@ export class TournamentResultService {
mvpUserId: match.result?.mvpUserId,
riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))],
games,
seriesResults: this.buildSeriesResults(games),
};
}
private buildSeriesResults(
games: MatchGameResult[],
): NonNullable<MatchDocument['result']>['seriesResults'] {
const bySeries = new Map<
string,
{
blueGroupIndex: number;
redGroupIndex: number;
blueScore: number;
redScore: number;
winnerSide?: 'blue' | 'red';
}
>();
for (const game of games) {
const blueGroupIndex = game.blueGroupIndex ?? 1;
const redGroupIndex = game.redGroupIndex ?? 1;
const key = `${blueGroupIndex}:${redGroupIndex}`;
const current =
bySeries.get(key) ??
{
blueGroupIndex,
redGroupIndex,
blueScore: 0,
redScore: 0,
};
if (game.winnerSide === 'blue') current.blueScore += 1;
if (game.winnerSide === 'red') current.redScore += 1;
current.winnerSide =
current.blueScore > current.redScore
? 'blue'
: current.redScore > current.blueScore
? 'red'
: undefined;
bySeries.set(key, current);
}
return [...bySeries.values()].sort(
(left, right) =>
left.blueGroupIndex - right.blueGroupIndex ||
left.redGroupIndex - right.redGroupIndex,
);
}
private resolveSeriesRefForGameNumber(
match: MatchDocument,
gameNumber: number,
): { blueGroupIndex: number; redGroupIndex: number } {
const perSeries = match.gameCount || 1;
const groupIndex = Math.max(1, Math.ceil(gameNumber / perSeries));
return { blueGroupIndex: groupIndex, redGroupIndex: groupIndex };
}
private resolveRequiredGameSlots(match: MatchDocument): number {
const groups = Math.max(
1,
new Set(match.teams.map((team) => team.groupIndex ?? 1)).size,
);
return groups * (match.gameCount || 1);
}
private async updatePollState(
match: MatchDocument,
outcome: 'matched' | 'not-found' | 'failed',