diff --git a/apps/api/src/modules/common/parse-object-id.pipe.ts b/apps/api/src/modules/common/parse-object-id.pipe.ts new file mode 100644 index 00000000..e9e046f6 --- /dev/null +++ b/apps/api/src/modules/common/parse-object-id.pipe.ts @@ -0,0 +1,24 @@ +import { + ArgumentMetadata, + BadRequestException, + Injectable, + PipeTransform, +} from '@nestjs/common'; +import mongoose from 'mongoose'; + +@Injectable() +export class ParseObjectIdPipe + implements PipeTransform +{ + public transform( + value: string, + metadata: ArgumentMetadata, + ): mongoose.Types.ObjectId { + if (!mongoose.isValidObjectId(value)) { + throw new BadRequestException( + `Invalid ObjectId for ${metadata.data ?? 'param'}.`, + ); + } + return new mongoose.Types.ObjectId(value); + } +} diff --git a/apps/api/src/modules/global/database/connection.service.spec.ts b/apps/api/src/modules/global/database/connection.service.spec.ts new file mode 100644 index 00000000..ae75d66b --- /dev/null +++ b/apps/api/src/modules/global/database/connection.service.spec.ts @@ -0,0 +1,14 @@ +import { resolveMongoDbName } from './connection.service'; + +describe('resolveMongoDbName', () => { + it('uses production database only for prod', () => { + expect(resolveMongoDbName('prod')).toBe('lolympus'); + }); + + it('uses isolated databases for non-production environments', () => { + expect(resolveMongoDbName('dev')).toBe('lolympus-dev'); + expect(resolveMongoDbName('test')).toBe('lolympus-test'); + expect(resolveMongoDbName('')).toBe('lolympus-dev'); + expect(resolveMongoDbName('local')).toBe('lolympus-dev'); + }); +}); diff --git a/apps/api/src/modules/global/database/connection.service.ts b/apps/api/src/modules/global/database/connection.service.ts new file mode 100644 index 00000000..2b51a437 --- /dev/null +++ b/apps/api/src/modules/global/database/connection.service.ts @@ -0,0 +1,100 @@ +import { Injectable, Scope, OnModuleInit } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { SecretService } from '../secret/secret.service'; +import { tournamentModelDefinitions, TournamentModelTypes } from './schema'; + +export function resolveMongoDbName(nodeEnv = process.env.NODE_ENV): string { + if (nodeEnv === 'prod') return 'lolympus'; + if (nodeEnv === 'test') return 'lolympus-test'; + return 'lolympus-dev'; +} + +@Injectable({ scope: Scope.DEFAULT }) +export class ConnectionService implements OnModuleInit { + private connection: mongoose.Connection | null = null; + constructor(private readonly secretService: SecretService) {} + + private tournamentModels: Map> | null = null; + + public async getConnection(): Promise { + if (this.connection !== null && this.connection.readyState === 1) { + return this.connection; + } + + const connectionString = await this.secretService.get( + 'MONGODB_CONNECTION_STRING', + ); + const dbName = resolveMongoDbName(); + const defaultConnection = await mongoose + .createConnection(connectionString, { + dbName, + minPoolSize: 10, + maxPoolSize: 20, + }) + .asPromise(); + this.connection = defaultConnection; + console.log(`Default Connection이 새로 생성됨. dbName=${dbName}`); + + return this.connection; + } + + public async getModel( + modelKey: K, + ): Promise> { + if (this.tournamentModels) + return this.tournamentModels.get(modelKey) as mongoose.Model< + TournamentModelTypes[K] + >; + + const models = new Map>(); + const connection = await this.getConnection(); + + tournamentModelDefinitions.forEach((modelDefinition) => { + // 이미 생성된 경우 컴파일 스킵. + if ( + Object.prototype.hasOwnProperty.call( + connection.models, + modelDefinition.name, + ) + ) { + models.set( + modelDefinition.name as K, + connection.models[modelDefinition.name], + ); + return; + } else { + models.set( + modelDefinition.name as K, + connection.model( + modelDefinition.name, + modelDefinition.schema, + modelDefinition.schemaName, + ), + ); + } + }); + + this.tournamentModels = models; + return models.get(modelKey) as mongoose.Model; + } + + public async createSession( + options?: mongoose.ClientSessionOptions, + ): Promise { + try { + const connection = await this.getConnection(); + const session = await connection.startSession(options); + return session as unknown as mongoose.ClientSession; + } catch (error) { + console.log(error); + } + } + + public async onModuleInit() { + await this.getConnection().catch(console.error); + } + + public async onModuleDestroy() { + this.connection?.close(); + } +} diff --git a/apps/api/src/modules/global/database/database.module.ts b/apps/api/src/modules/global/database/database.module.ts new file mode 100644 index 00000000..a4b5e918 --- /dev/null +++ b/apps/api/src/modules/global/database/database.module.ts @@ -0,0 +1,9 @@ +import { DynamicModule, Module } from '@nestjs/common'; +import { ConnectionService } from './connection.service'; + +@Module({ + imports: [], + providers: [ConnectionService], + exports: [ConnectionService], +}) +export class DatabaseModule {} diff --git a/apps/api/src/modules/global/database/schema.ts b/apps/api/src/modules/global/database/schema.ts new file mode 100644 index 00000000..bf7ef38b --- /dev/null +++ b/apps/api/src/modules/global/database/schema.ts @@ -0,0 +1,1244 @@ +import mongoose, { Schema, HydratedDocument } from 'mongoose'; +import type { + RiotPlatformRoute, + RiotRegionalRoute, +} from '../../riot/riot.types'; +import { ModelDefinition } from './types'; + +export type Position = 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; +export const POSITIONS: Position[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP']; + +export type RiotLane = 'TOP' | 'JUNGLE' | 'MIDDLE' | 'BOTTOM' | 'UTILITY'; +export const RIOT_LANES: RiotLane[] = [ + 'TOP', + 'JUNGLE', + 'MIDDLE', + 'BOTTOM', + 'UTILITY', +]; + +export type MatchStatus = + | 'recruiting' + | 'team-built' + | 'in-progress' + | 'finished'; +export const MATCH_STATUSES: MatchStatus[] = [ + 'recruiting', + 'team-built', + 'in-progress', + 'finished', +]; + +export type TeamSide = 'blue' | 'red'; +export const TEAM_SIDES: TeamSide[] = ['blue', 'red']; + +export type CommunityRole = 'owner' | 'admin' | 'member'; +export const COMMUNITY_ROLES: CommunityRole[] = ['owner', 'admin', 'member']; + +export type TournamentCodeState = + | 'available' + | 'reserved' + | 'used' + | 'expired' + | 'released'; +export const TOURNAMENT_CODE_STATES: TournamentCodeState[] = [ + 'available', + 'reserved', + 'used', + 'expired', + 'released', +]; +export type TournamentMapType = 'SUMMONERS_RIFT'; +export const TOURNAMENT_MAP_TYPES: TournamentMapType[] = ['SUMMONERS_RIFT']; +export type TournamentSpectatorType = 'NONE' | 'LOBBYONLY' | 'ALL'; +export const TOURNAMENT_SPECTATOR_TYPES: TournamentSpectatorType[] = [ + 'NONE', + 'LOBBYONLY', + 'ALL', +]; + +export type MatchResultPollOutcome = 'matched' | 'not-found' | 'failed'; +export type MatchResultPollStateValue = 'polling' | 'complete' | 'expired' | 'failed'; +export const MATCH_RESULT_POLL_STATES: MatchResultPollStateValue[] = [ + 'polling', + 'complete', + 'expired', + '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 = 최우선, 숫자가 작을수록 높은 우선순위 +} + +export type AuctionPhase = + | 'waiting' + | 'presenting' + | 'bidding' + | 'sold' + | 'complete'; +export const AUCTION_PHASES: AuctionPhase[] = [ + 'waiting', + 'presenting', + 'bidding', + 'sold', + 'complete', +]; + +export interface MongooseTimestamps { + createdAt: Date; + updatedAt: Date; +} + +// ===== Identity ===== +export interface Identity extends MongooseTimestamps { + entraOid: string; + tenantId?: string; + email?: string; + displayName?: string; + lastSignInAt?: Date; +} + +// ===== Tier ===== +export interface TierInfo { + leagueId?: string; + queueType: string; // RANKED_SOLO_5x5, RANKED_FLEX_SR 등 + tier: string; // IRON, BRONZE, ..., CHALLENGER + rank: string; // I | II | III | IV + puuid?: string; + leaguePoints: number; + wins: number; + losses: number; + veteran?: boolean; + inactive?: boolean; + freshBlood?: boolean; + hotStreak?: boolean; + miniSeries?: Record; + fetchedAt: Date; // Riot API로부터 조회된 시각 +} + +export interface TierHistoryEntry { + queueType: string; + tier: string; + rank?: string; + leaguePoints?: number; + wins?: number; + losses?: number; + recordedAt: Date; + season?: string; // e.g., 'S13', 'S14' + peakTier?: string; + peakRank?: string; +} + +// ===== RiotAccount (User 하위에 임베딩) ===== +/** + * 챔피언 단위 집계 기록. 필드 추가가 잦을 것으로 예상되어 Mixed로 저장. + * key: championId (string), value: championId별 누적/평균 지표 자유형 JSON + */ +export type ChampionRecordMap = Record>; + +export interface ChampionMasteryEntry { + puuid: string; + championId: number; + championLevel: number; + championPoints: number; + lastPlayTime?: number; + championPointsSinceLastLevel?: number; + championPointsUntilNextLevel?: number; + markRequiredForNextLevel?: number; + tokensEarned?: number; + championSeasonMilestone?: number; + milestoneGrades?: string[]; + nextSeasonMilestone?: Record; +} + +export interface RiotLaneStats { + games: number; + wins: number; + losses: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + avgCs: number; + avgCsPerMin: number; + mostPlayedChampionIds: number[]; +} + +export interface RiotRecentStatsSummary { + overall: RiotLaneStats; + byLane: Partial>; +} + +export function createEmptyRiotLaneStats(): RiotLaneStats { + return { + games: 0, + wins: 0, + losses: 0, + avgKills: 0, + avgDeaths: 0, + avgAssists: 0, + avgCs: 0, + avgCsPerMin: 0, + mostPlayedChampionIds: [], + }; +} + +export function createEmptyRiotRecentStatsSummary(): RiotRecentStatsSummary { + return { + overall: createEmptyRiotLaneStats(), + byLane: {}, + }; +} + +export interface RiotAccount extends MongooseTimestamps { + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + revisionDate: number; + summonerLevel: number; + isPrimary: boolean; + + // 현재 티어들(솔랭/자랭 각각) + tiers: TierInfo[]; + // 과거 티어 기록 + tierHistory: TierHistoryEntry[]; + + // Riot matchId 참조 (원본은 RiotMatch 컬렉션에 저장) + matchIds: string[]; + matchIdsFetchedAt?: Date; + matchIdsByQueueFetchedAt?: Map; + lastRefreshRequestedAt?: Date; + + // 최근 경기 요약 + recentStatsSummary?: RiotRecentStatsSummary; + recentStatsFetchedAt?: Date; + + // 챔피언 숙련도 + championMasteries: ChampionMasteryEntry[]; + championMasteriesFetchedAt?: Date; + + // 챔피언별 기록 (JSON, 필드 추가 자유로움) + championRecords: ChampionRecordMap; + championRecordsFetchedAt?: Date; +} + +// ===== User ===== +export interface User extends MongooseTimestamps { + communityId: mongoose.Types.ObjectId; + identityId?: mongoose.Types.ObjectId; + role: CommunityRole; + kakaoTalkId?: string; + kakaoTalkNickname?: string; + discordId?: string; + discordNickname?: string; + riotAccounts: RiotAccount[]; + preferredPositions: PositionPreference[]; + isActivated: boolean; +} + +export interface Community extends MongooseTimestamps { + name: string; + description: string; + ownerUserId: mongoose.Types.ObjectId; + dakaoProjectId?: mongoose.Types.ObjectId; + riotPlatform?: RiotPlatformRoute; + riotRegion?: RiotRegionalRoute; + seasonStartedAt?: Date; + seasons?: CommunitySeason[]; + matchGameCount?: number; +} + +export interface CommunitySeason { + id: string; + label: string; + startedAt: Date; + endedAt?: Date; +} + +export type CommunityDocument = HydratedDocument; +export type IdentityDocument = HydratedDocument; +export type UserDocument = HydratedDocument; + +// ===== RiotMatch (Riot 원본 매치 아카이브) ===== +export interface RiotMatch extends MongooseTimestamps { + matchId: string; // Riot matchId (예: KR_7123456789) + gameCreation: number; + gameDuration: number; + gameVersion?: string; + queueId?: number; + participantPuuids: string[]; + raw: Record; // Riot API Match-V5 원본 응답 전체 + fetchedAt: Date; +} + +export type RiotMatchDocument = HydratedDocument; + +// ===== TournamentCode (운영자가 미리 업로드한 토너먼트 코드 풀) ===== +export interface TournamentCode extends MongooseTimestamps { + code: string; + region: RiotPlatformRoute; + mapType: TournamentMapType; + teamSize: number; + spectatorType: TournamentSpectatorType; + metadata?: Record; + expiresAt: Date; + state: TournamentCodeState; + matchId?: mongoose.Types.ObjectId; + gameNumber?: number; + reservedAt?: Date; + usedAt?: Date; + releasedAt?: Date; + riotMatchId?: string; + uploadedBy: mongoose.Types.ObjectId; + uploadedAt: Date; + source?: string; + notes?: string; +} + +export type TournamentCodeDocument = HydratedDocument; + +// ===== Match (내전) ===== +export interface MatchParticipant { + userId: mongoose.Types.ObjectId; + // 표시용 스냅샷 (대표 RiotAccount 기준) + puuid?: string; + gameName?: string; + tagLine?: string; + profileIconId?: number; + tier?: TierInfo; + preferredPositions: PositionPreference[]; + joinedAt: Date; +} + +export interface MatchTeamMember { + userId: mongoose.Types.ObjectId; + assignedPosition: Position; + cost?: number; // 경매로 영입된 경우의 입찰가 +} + +export interface MatchTeam { + side: TeamSide; + name: string; + captainUserId?: mongoose.Types.ObjectId; + members: MatchTeamMember[]; +} + +export interface MatchGameResultParticipant { + userId: mongoose.Types.ObjectId; + side: TeamSide; + championId: number; + kills: number; + deaths: number; + assists: number; + win: boolean; +} + +export interface MatchGameResult { + gameNumber: number; + riotMatchId: string; + winnerSide: TeamSide; + gameCreation: number; + gameDuration: number; + participants: MatchGameResultParticipant[]; +} + +export interface MatchResult { + winnerSide?: TeamSide; + blueScore: number; + redScore: number; + mvpUserId?: mongoose.Types.ObjectId; + riotMatchIds: string[]; // 내전에서 플레이된 Riot matchId들 + games: MatchGameResult[]; +} + +export interface MatchResultPollState { + startedAt: Date; + lastPolledAt?: Date; + lastPollOutcome?: MatchResultPollOutcome; + matchedCount: number; + expandedToAllPuuids: boolean; + state: MatchResultPollStateValue; +} + +export interface MatchScheduleItem { + time: string; + label: string; +} + +export interface Match extends MongooseTimestamps { + communityId: mongoose.Types.ObjectId; + title: string; + description: string; + mapId: number; // Riot Match-V5 mapId (11=소환사의 협곡, 12=ARAM 등) + status: MatchStatus; + scheduledAt: Date; + maxParticipants: number; + gameCount: number; + tournamentCodeIds: mongoose.Types.ObjectId[]; + teamBuiltAt?: Date; + hostUserId?: mongoose.Types.ObjectId; + participants: MatchParticipant[]; + 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[]; +} + +export type MatchDocument = HydratedDocument; + +// ===== 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; + +// ===== Auction (경매) ===== +export interface AuctionPlayerSnapshot { + userId: mongoose.Types.ObjectId; + // 표시용 스냅샷(대표 RiotAccount 기준) — RiotAccount에서 복사 + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + preferredPositions: PositionPreference[]; + tiers: TierInfo[]; + masteries: ChampionMasteryEntry[]; + recentStatsSummary?: RiotRecentStatsSummary; +} + +export interface AuctionTeamMember { + userId: mongoose.Types.ObjectId; + assignedPosition: Position; + cost: number; +} + +export interface AuctionTeam { + side: TeamSide; + captainUserId: mongoose.Types.ObjectId; + points: number; + members: AuctionTeamMember[]; +} + +export interface AuctionBid { + side: TeamSide; + amount: number; + bidderUserId: mongoose.Types.ObjectId; + timestamp: Date; +} + +export interface Auction extends MongooseTimestamps { + matchId: mongoose.Types.ObjectId; + phase: AuctionPhase; + teams: AuctionTeam[]; + order: AuctionPlayerSnapshot[]; + currentIndex: number; + bids: AuctionBid[]; + currentBid: number; + currentBidder?: TeamSide; + maxTimerSeconds: number; + currentDeadline?: Date; + initialPoints: number; + startedAt?: Date; + completedAt?: Date; +} + +export type AuctionDocument = HydratedDocument; + +// ===== Sub-schemas ===== +const PositionPreferenceSubSchema = new Schema( + { + position: { type: String, enum: POSITIONS, required: true }, + priority: { type: Number, required: true, min: 1 }, + }, + { _id: false }, +); + +const TierInfoSubSchema = new Schema( + { + leagueId: { type: String }, + queueType: { type: String, required: true }, + tier: { type: String, required: true }, + rank: { type: String, required: true, default: '' }, + puuid: { type: String }, + leaguePoints: { type: Number, required: true, default: 0 }, + wins: { type: Number, required: true, default: 0 }, + losses: { type: Number, required: true, default: 0 }, + veteran: { type: Boolean }, + inactive: { type: Boolean }, + freshBlood: { type: Boolean }, + hotStreak: { type: Boolean }, + miniSeries: { type: Schema.Types.Mixed }, + fetchedAt: { type: Date, required: true, default: Date.now }, + }, + { _id: false }, +); + +const TierHistoryEntrySubSchema = new Schema( + { + queueType: { type: String, required: true }, + tier: { type: String, required: true }, + rank: { type: String }, + leaguePoints: { type: Number }, + wins: { type: Number }, + losses: { type: Number }, + recordedAt: { type: Date, required: true }, + season: { type: String }, + peakTier: { type: String }, + peakRank: { type: String }, + }, + { _id: false }, +); + +const ChampionMasteryEntrySubSchema = new Schema( + { + puuid: { type: String, required: true }, + championId: { type: Number, required: true }, + championLevel: { type: Number, required: true, default: 0 }, + championPoints: { type: Number, required: true, default: 0 }, + lastPlayTime: { type: Number }, + championPointsSinceLastLevel: { type: Number }, + championPointsUntilNextLevel: { type: Number }, + markRequiredForNextLevel: { type: Number }, + tokensEarned: { type: Number }, + championSeasonMilestone: { type: Number }, + milestoneGrades: { type: [String] }, + nextSeasonMilestone: { type: Schema.Types.Mixed }, + }, + { _id: false }, +); + +const RiotLaneStatsSubSchema = new Schema( + { + games: { type: Number, required: true, default: 0 }, + wins: { type: Number, required: true, default: 0 }, + losses: { type: Number, required: true, default: 0 }, + avgKills: { type: Number, required: true, default: 0 }, + avgDeaths: { type: Number, required: true, default: 0 }, + avgAssists: { type: Number, required: true, default: 0 }, + avgCs: { type: Number, required: true, default: 0 }, + avgCsPerMin: { type: Number, required: true, default: 0 }, + mostPlayedChampionIds: { type: [Number], required: true, default: [] }, + }, + { _id: false }, +); + +const RiotRecentStatsByLaneSubSchema = new Schema< + Partial> +>( + { + TOP: { type: RiotLaneStatsSubSchema, required: false }, + JUNGLE: { type: RiotLaneStatsSubSchema, required: false }, + MIDDLE: { type: RiotLaneStatsSubSchema, required: false }, + BOTTOM: { type: RiotLaneStatsSubSchema, required: false }, + UTILITY: { type: RiotLaneStatsSubSchema, required: false }, + }, + { _id: false }, +); + +const RiotRecentStatsSummarySubSchema = new Schema( + { + overall: { + type: RiotLaneStatsSubSchema, + required: true, + default: createEmptyRiotLaneStats, + }, + byLane: { + type: RiotRecentStatsByLaneSubSchema, + required: true, + default: () => ({}), + }, + }, + { _id: false }, +); + +const RiotAccountSubSchema = new Schema( + { + puuid: { type: String, required: true }, + gameName: { type: String, required: true }, + tagLine: { type: String, required: true }, + profileIconId: { type: Number, required: true, default: 0 }, + revisionDate: { type: Number, required: true, default: 0 }, + summonerLevel: { type: Number, required: true, default: 0 }, + isPrimary: { type: Boolean, required: true, default: false }, + + tiers: { type: [TierInfoSubSchema], required: true, default: [] }, + tierHistory: { + type: [TierHistoryEntrySubSchema], + required: true, + default: [], + }, + + matchIds: { type: [String], required: true, default: [] }, + matchIdsFetchedAt: { type: Date }, + matchIdsByQueueFetchedAt: { type: Map, of: Date }, + lastRefreshRequestedAt: { type: Date }, + + recentStatsSummary: { type: RiotRecentStatsSummarySubSchema }, + recentStatsFetchedAt: { type: Date }, + + championMasteries: { + type: [ChampionMasteryEntrySubSchema], + required: true, + default: [], + }, + championMasteriesFetchedAt: { type: Date }, + + championRecords: { + type: Schema.Types.Mixed, + required: true, + default: () => ({}), + }, + championRecordsFetchedAt: { type: Date }, + }, + { + _id: false, + timestamps: true, + }, +); + +export const IdentitySchema = new Schema( + { + entraOid: { type: String, required: true }, + tenantId: { type: String }, + email: { type: String }, + displayName: { type: String }, + lastSignInAt: { type: Date }, + }, + { + timestamps: true, + collection: 'identity', + }, +); + +IdentitySchema.index({ entraOid: 1 }, { unique: true }); +IdentitySchema.index({ email: 1 }); + +export const CommunitySchema = new Schema( + { + name: { type: String, required: true }, + description: { type: String, required: true, default: '' }, + ownerUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + dakaoProjectId: { type: Schema.Types.ObjectId }, + riotPlatform: { type: String }, + riotRegion: { type: String }, + seasonStartedAt: { type: Date }, + matchGameCount: { type: Number, required: false, default: 3 }, + seasons: { + type: [ + new Schema( + { + id: { type: String, required: true }, + label: { type: String, required: true }, + startedAt: { type: Date, required: true }, + endedAt: { type: Date }, + }, + { _id: false }, + ), + ], + required: false, + }, + }, + { + timestamps: true, + collection: 'community', + }, +); + +CommunitySchema.index({ name: 1 }, { unique: true }); +CommunitySchema.index({ ownerUserId: 1 }); +CommunitySchema.index({ dakaoProjectId: 1 }, { unique: true, sparse: true }); + +export const UserSchema = new Schema( + { + communityId: { + type: Schema.Types.ObjectId, + ref: 'community', + required: true, + }, + identityId: { type: Schema.Types.ObjectId, ref: 'identity' }, + role: { + type: String, + enum: COMMUNITY_ROLES, + required: true, + default: 'member', + }, + kakaoTalkId: { type: String }, + kakaoTalkNickname: { type: String }, + discordId: { type: String }, + discordNickname: { type: String }, + riotAccounts: { + type: [RiotAccountSubSchema], + required: true, + default: [], + validate: [ + { + validator: function (accounts: RiotAccount[]) { + const puuids = accounts.map((a) => a.puuid); + return puuids.length === new Set(puuids).size; + }, + message: 'Duplicate Riot puuid within a user is not allowed.', + }, + { + validator: function (accounts: RiotAccount[]) { + if (accounts.length === 0) return true; + const primaryCount = accounts.filter((a) => a.isPrimary).length; + return primaryCount === 1; + }, + message: + 'Exactly one Riot account must be marked as primary when accounts exist.', + }, + ], + }, + preferredPositions: { + type: [PositionPreferenceSubSchema], + required: true, + default: [], + }, + isActivated: { type: Boolean, required: true, default: true }, + }, + { + timestamps: true, + collection: 'user', + }, +); + +UserSchema.index({ communityId: 1 }); +UserSchema.index({ communityId: 1, role: 1 }); +UserSchema.index( + { communityId: 1, identityId: 1 }, + { + unique: true, + partialFilterExpression: { identityId: { $type: 'objectId' } }, + }, +); +UserSchema.index( + { identityId: 1 }, + { partialFilterExpression: { identityId: { $type: 'objectId' } } }, +); +UserSchema.index( + { communityId: 1, kakaoTalkId: 1 }, + { + unique: true, + partialFilterExpression: { kakaoTalkId: { $type: 'string' } }, + }, +); +UserSchema.index( + { communityId: 1, discordId: 1 }, + { + unique: true, + partialFilterExpression: { discordId: { $type: 'string' } }, + }, +); +UserSchema.index( + { communityId: 1, 'riotAccounts.puuid': 1 }, + { + unique: true, + partialFilterExpression: { 'riotAccounts.puuid': { $type: 'string' } }, + }, +); + +export const RiotMatchSchema = new Schema( + { + matchId: { type: String, required: true, unique: true }, + gameCreation: { type: Number, required: true, default: 0 }, + gameDuration: { type: Number, required: true, default: 0 }, + gameVersion: { type: String }, + queueId: { type: Number }, + participantPuuids: { type: [String], required: true, default: [] }, + raw: { type: Schema.Types.Mixed, required: true, default: () => ({}) }, + fetchedAt: { type: Date, required: true, default: Date.now }, + }, + { + timestamps: true, + collection: 'riot_match', + }, +); + +RiotMatchSchema.index({ participantPuuids: 1, gameCreation: -1 }); +RiotMatchSchema.index({ participantPuuids: 1, queueId: 1, gameCreation: -1 }); +RiotMatchSchema.index({ 'raw.info.tournamentCode': 1 }, { sparse: true }); + +export const TournamentCodeSchema = new Schema( + { + code: { + type: String, + required: true, + trim: true, + uppercase: true, + }, + region: { type: String, required: true, default: 'kr' }, + mapType: { + type: String, + enum: TOURNAMENT_MAP_TYPES, + required: true, + default: 'SUMMONERS_RIFT', + }, + teamSize: { type: Number, required: true, default: 5 }, + spectatorType: { + type: String, + enum: TOURNAMENT_SPECTATOR_TYPES, + required: true, + default: 'ALL', + }, + metadata: { type: Schema.Types.Mixed }, + expiresAt: { type: Date, required: true }, + state: { + type: String, + enum: TOURNAMENT_CODE_STATES, + required: true, + default: 'available', + }, + matchId: { type: Schema.Types.ObjectId, ref: 'match' }, + gameNumber: { type: Number }, + reservedAt: { type: Date }, + usedAt: { type: Date }, + releasedAt: { type: Date }, + riotMatchId: { type: String }, + uploadedBy: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + uploadedAt: { type: Date, required: true, default: Date.now }, + source: { type: String }, + notes: { type: String }, + }, + { + timestamps: true, + collection: 'tournament_code', + }, +); + +TournamentCodeSchema.index({ code: 1 }, { unique: true }); +TournamentCodeSchema.index({ state: 1, expiresAt: 1 }); +TournamentCodeSchema.index({ matchId: 1, gameNumber: 1 }); +TournamentCodeSchema.index({ state: 1, uploadedAt: -1 }); +TournamentCodeSchema.index({ riotMatchId: 1 }, { sparse: true }); + +const MatchParticipantSubSchema = new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + puuid: { type: String }, + gameName: { type: String }, + tagLine: { type: String }, + profileIconId: { type: Number }, + tier: { type: TierInfoSubSchema }, + preferredPositions: { + type: [PositionPreferenceSubSchema], + required: true, + default: [], + }, + joinedAt: { type: Date, required: true, default: Date.now }, + }, + { _id: false }, +); + +const MatchTeamMemberSubSchema = new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + assignedPosition: { type: String, enum: POSITIONS, required: true }, + cost: { type: Number, required: false }, + }, + { _id: false }, +); + +const MatchTeamSubSchema = new Schema( + { + side: { type: String, enum: TEAM_SIDES, required: true }, + name: { type: String, required: true }, + captainUserId: { type: Schema.Types.ObjectId, ref: 'user' }, + members: { type: [MatchTeamMemberSubSchema], required: true, default: [] }, + }, + { _id: false }, +); + +const MatchGameResultParticipantSubSchema = + new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + side: { type: String, enum: TEAM_SIDES, required: true }, + championId: { type: Number, required: true }, + kills: { type: Number, required: true, default: 0 }, + deaths: { type: Number, required: true, default: 0 }, + assists: { type: Number, required: true, default: 0 }, + win: { type: Boolean, required: true, default: false }, + }, + { _id: false }, + ); + +const MatchGameResultSubSchema = new Schema( + { + gameNumber: { type: Number, required: true }, + riotMatchId: { type: String, required: true }, + winnerSide: { type: String, enum: TEAM_SIDES, required: true }, + gameCreation: { type: Number, required: true }, + gameDuration: { type: Number, required: true }, + participants: { + type: [MatchGameResultParticipantSubSchema], + required: true, + default: [], + }, + }, + { _id: false }, +); + +const MatchResultSubSchema = new Schema( + { + winnerSide: { type: String, enum: TEAM_SIDES, required: false }, + blueScore: { type: Number, required: true, default: 0 }, + redScore: { type: Number, required: true, default: 0 }, + mvpUserId: { type: Schema.Types.ObjectId, ref: 'user' }, + riotMatchIds: { type: [String], required: true, default: [] }, + games: { type: [MatchGameResultSubSchema], required: true, default: [] }, + }, + { _id: false }, +); + +const MatchResultPollStateSubSchema = new Schema( + { + startedAt: { type: Date, required: true }, + lastPolledAt: { type: Date }, + lastPollOutcome: { + type: String, + enum: ['matched', 'not-found', 'failed'], + required: false, + }, + matchedCount: { type: Number, required: true, default: 0 }, + expandedToAllPuuids: { type: Boolean, required: true, default: false }, + state: { + type: String, + enum: MATCH_RESULT_POLL_STATES, + required: true, + default: 'polling', + }, + }, + { _id: false }, +); + +const MatchScheduleItemSubSchema = new Schema( + { + time: { type: String, required: true }, + label: { type: String, required: true }, + }, + { _id: false }, +); + +const MatchLegacyImportSourceSubSchema = new Schema>( + { + 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( + { + communityId: { + type: Schema.Types.ObjectId, + ref: 'community', + required: true, + }, + title: { type: String, required: true }, + description: { type: String, required: true, default: '' }, + mapId: { type: Number, required: true, default: 11 }, + status: { + type: String, + enum: MATCH_STATUSES, + required: true, + default: 'recruiting', + }, + scheduledAt: { type: Date, required: true }, + maxParticipants: { type: Number, required: true, default: 10 }, + gameCount: { type: Number, required: true, default: 3 }, + tournamentCodeIds: { + type: [{ type: Schema.Types.ObjectId, ref: 'tournamentCode' }], + required: true, + default: [], + }, + teamBuiltAt: { type: Date }, + hostUserId: { type: Schema.Types.ObjectId, ref: 'user' }, + participants: { + type: [MatchParticipantSubSchema], + required: true, + default: [], + validate: { + validator: function (parts: MatchParticipant[]) { + const ids = parts.map((p) => p.userId.toString()); + return ids.length === new Set(ids).size; + }, + message: 'Duplicate participants are not allowed.', + }, + }, + teams: { type: [MatchTeamSubSchema], required: true, default: [] }, + result: { type: MatchResultSubSchema, required: false }, + resultPollState: { + 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: { + type: [MatchScheduleItemSubSchema], + required: true, + default: [], + }, + }, + { + timestamps: true, + collection: '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( + { + 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( + { + 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( + { + 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( + { + userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + puuid: { type: String, required: true }, + gameName: { type: String, required: true }, + tagLine: { type: String, required: true }, + profileIconId: { type: Number, required: true, default: 0 }, + preferredPositions: { + type: [PositionPreferenceSubSchema], + required: true, + default: [], + }, + tiers: { type: [TierInfoSubSchema], required: true, default: [] }, + masteries: { + type: [ChampionMasteryEntrySubSchema], + required: true, + default: [], + }, + recentStatsSummary: { type: RiotRecentStatsSummarySubSchema }, + }, + { _id: false }, +); + +const AuctionTeamMemberSubSchema = new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + assignedPosition: { type: String, enum: POSITIONS, required: true }, + cost: { type: Number, required: true, default: 0 }, + }, + { _id: false }, +); + +const AuctionTeamSubSchema = new Schema( + { + side: { type: String, enum: TEAM_SIDES, required: true }, + captainUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + points: { type: Number, required: true, default: 0 }, + members: { + type: [AuctionTeamMemberSubSchema], + required: true, + default: [], + }, + }, + { _id: false }, +); + +const AuctionBidSubSchema = new Schema( + { + side: { type: String, enum: TEAM_SIDES, required: true }, + amount: { type: Number, required: true }, + bidderUserId: { type: Schema.Types.ObjectId, ref: 'user', required: true }, + timestamp: { type: Date, required: true, default: Date.now }, + }, + { _id: false }, +); + +export const AuctionSchema = new Schema( + { + matchId: { + type: Schema.Types.ObjectId, + ref: 'match', + required: true, + unique: true, + }, + phase: { + type: String, + enum: AUCTION_PHASES, + required: true, + default: 'waiting', + }, + teams: { type: [AuctionTeamSubSchema], required: true, default: [] }, + order: { + type: [AuctionPlayerSnapshotSubSchema], + required: true, + default: [], + }, + currentIndex: { type: Number, required: true, default: 0 }, + bids: { type: [AuctionBidSubSchema], required: true, default: [] }, + currentBid: { type: Number, required: true, default: 0 }, + currentBidder: { type: String, enum: TEAM_SIDES, required: false }, + maxTimerSeconds: { type: Number, required: true, default: 30 }, + currentDeadline: { type: Date, required: false }, + initialPoints: { type: Number, required: true, default: 1000 }, + startedAt: { type: Date, required: false }, + completedAt: { type: Date, required: false }, + }, + { + timestamps: true, + collection: 'auction', + }, +); + +export const tournamentModelDefinitions: ModelDefinition[] = [ + { name: 'identity', schema: IdentitySchema, schemaName: 'identity' }, + { name: 'community', schema: CommunitySchema, schemaName: 'community' }, + { name: 'user', schema: UserSchema, schemaName: 'user' }, + { name: 'riotMatch', schema: RiotMatchSchema, schemaName: 'riotMatch' }, + { + name: 'tournamentCode', + schema: TournamentCodeSchema, + schemaName: 'tournamentCode', + }, + { + name: 'legacyImportJob', + schema: LegacyImportJobSchema, + schemaName: 'legacyImportJob', + }, + { name: 'match', schema: MatchSchema, schemaName: 'match' }, + { name: 'auction', schema: AuctionSchema, schemaName: 'auction' }, +]; + +export interface TournamentModelTypes { + identity: Identity; + community: Community; + user: User; + riotMatch: RiotMatch; + tournamentCode: TournamentCode; + legacyImportJob: LegacyImportJob; + match: Match; + auction: Auction; +} diff --git a/apps/api/src/modules/global/database/types.d.ts b/apps/api/src/modules/global/database/types.d.ts new file mode 100644 index 00000000..748932f3 --- /dev/null +++ b/apps/api/src/modules/global/database/types.d.ts @@ -0,0 +1,5 @@ +export interface ModelDefinition { + name: string; + schema: mongoose.Schema; + schemaName?: string; +} diff --git a/apps/api/src/modules/global/garnet/garnet.constants.ts b/apps/api/src/modules/global/garnet/garnet.constants.ts new file mode 100644 index 00000000..842616cb --- /dev/null +++ b/apps/api/src/modules/global/garnet/garnet.constants.ts @@ -0,0 +1 @@ +export const GARNET_CLIENT = Symbol('GARNET_CLIENT'); diff --git a/apps/api/src/modules/global/garnet/garnet.module.ts b/apps/api/src/modules/global/garnet/garnet.module.ts new file mode 100644 index 00000000..8bc9ec66 --- /dev/null +++ b/apps/api/src/modules/global/garnet/garnet.module.ts @@ -0,0 +1,57 @@ +import { Logger, Module } from '@nestjs/common'; +import { createClient } from 'redis'; +import { SecretModule } from '../secret/secret.module'; +import { SecretService } from '../secret/secret.service'; +import { GARNET_CLIENT } from './garnet.constants'; +import { GarnetService, type GarnetRedisClient } from './garnet.service'; + +function normalizeGarnetUrl(endpoint: string): string { + const trimmed = endpoint.trim(); + if (!trimmed) { + throw new Error('GARNET_ENDPOINT cannot be empty'); + } + if (/^redis(s)?:\/\//iu.test(trimmed)) { + return trimmed; + } + return `redis://${trimmed}`; +} + +@Module({ + imports: [SecretModule], + providers: [ + { + provide: GARNET_CLIENT, + inject: [SecretService], + useFactory: async ( + secretService: SecretService, + ): Promise => { + await secretService.ready(); + + const [endpoint, username, password] = await Promise.all([ + secretService.get('GARNET_ENDPOINT'), + secretService.get('GARNET_USERID'), + secretService.get('GARNET_PASSWORD'), + ]); + + const logger = new Logger('GarnetClient'); + const client = createClient({ + url: normalizeGarnetUrl(endpoint), + username, + password, + }); + + client.on('error', (error) => { + logger.error(`Garnet client error: ${error?.message ?? error}`); + }); + + await client.connect(); + logger.log('Garnet connected'); + + return client; + }, + }, + GarnetService, + ], + exports: [GarnetService, GARNET_CLIENT], +}) +export class GarnetModule {} diff --git a/apps/api/src/modules/global/garnet/garnet.service.ts b/apps/api/src/modules/global/garnet/garnet.service.ts new file mode 100644 index 00000000..c79b30d9 --- /dev/null +++ b/apps/api/src/modules/global/garnet/garnet.service.ts @@ -0,0 +1,213 @@ +import { + Inject, + Injectable, + Logger, + OnModuleDestroy, +} from '@nestjs/common'; +import type { createClient } from 'redis'; +import { GARNET_CLIENT } from './garnet.constants'; + +export type GarnetRedisClient = ReturnType; + +export interface StreamEntry { + deliveriesCounter?: number; + id: string; + message: Record; + millisElapsedFromDelivery?: number; +} + +export interface StreamReadResult { + messages: StreamEntry[]; + name: string; +} + +interface RawStreamMessage { + deliveriesCounter?: number; + id: string; + message: unknown; + millisElapsedFromDelivery?: number; +} + +interface RawStreamReadResult { + messages: RawStreamMessage[]; + name: string; +} + +function normalizeStreamFields(fields: unknown): Record { + if (fields instanceof Map) { + return Object.fromEntries( + [...fields.entries()].map(([key, value]) => [String(key), String(value)]), + ); + } + + if (typeof fields === 'object' && fields !== null) { + return Object.fromEntries( + Object.entries(fields as Record).map(([key, value]) => [ + key, + String(value), + ]), + ); + } + + return {}; +} + +@Injectable() +export class GarnetService implements OnModuleDestroy { + private readonly logger = new Logger(GarnetService.name); + + constructor( + @Inject(GARNET_CLIENT) private readonly client: GarnetRedisClient, + ) {} + + async onModuleDestroy() { + try { + await this.client.quit(); + } catch { + this.client.destroy(); + } + } + + public raw(): GarnetRedisClient { + return this.client; + } + + public async getJson(key: string): Promise { + const raw = await this.client.get(key); + if (!raw) return null; + try { + return JSON.parse(raw) as T; + } catch (err) { + this.logger.warn( + `Failed to JSON.parse cached value for key="${key}": ${ + (err as Error)?.message ?? err + }`, + ); + return null; + } + } + + public async setJson( + key: string, + value: unknown, + ttlSeconds?: number, + ): Promise { + const serialized = JSON.stringify(value); + if (ttlSeconds && ttlSeconds > 0) { + await this.client.set(key, serialized, { EX: ttlSeconds }); + return; + } + await this.client.set(key, serialized); + } + + public async getString(key: string): Promise { + return this.client.get(key); + } + + public async setString( + key: string, + value: string, + ttlSeconds?: number, + ): Promise { + if (ttlSeconds && ttlSeconds > 0) { + await this.client.set(key, value, { EX: ttlSeconds }); + return; + } + await this.client.set(key, value); + } + + public async setStringIfAbsent( + key: string, + value: string, + ttlSeconds?: number, + ): Promise { + const options: { EX?: number; NX: true } = { NX: true }; + if (ttlSeconds && ttlSeconds > 0) options.EX = ttlSeconds; + const result = await this.client.set(key, value, options); + return result === 'OK'; + } + + public async delete(key: string): Promise { + return this.client.del(key); + } + + public async appendStream( + key: string, + fields: Record, + options?: { maxLen?: number }, + ): Promise { + const trimOptions = + options?.maxLen && options.maxLen > 0 + ? { + TRIM: { + strategy: 'MAXLEN' as const, + strategyModifier: '~' as const, + threshold: options.maxLen, + }, + } + : undefined; + + return this.client.xAdd(key, '*', fields, trimOptions); + } + + public async createConsumerGroup( + key: string, + group: string, + startId = '$', + ): Promise { + await this.client.xGroupCreate(key, group, startId, { MKSTREAM: true }); + } + + public async readGroup( + key: string, + group: string, + consumer: string, + startId: string, + options?: { blockMs?: number; count?: number }, + ): Promise { + const readOptions: { BLOCK?: number; COUNT?: number } = {}; + if (options?.blockMs !== undefined) readOptions.BLOCK = options.blockMs; + if (options?.count !== undefined) readOptions.COUNT = options.count; + + const reply = await this.client.xReadGroup( + group, + consumer, + { key, id: startId }, + readOptions, + ); + + if (!reply) return null; + + return (reply as RawStreamReadResult[]).map((stream) => ({ + name: String(stream.name), + messages: stream.messages.map((message) => ({ + deliveriesCounter: + typeof message.deliveriesCounter === 'number' + ? message.deliveriesCounter + : undefined, + id: String(message.id), + message: normalizeStreamFields(message.message), + millisElapsedFromDelivery: + typeof message.millisElapsedFromDelivery === 'number' + ? message.millisElapsedFromDelivery + : undefined, + })), + })); + } + + public async acknowledgeStream( + key: string, + group: string, + ids: string | string[], + ): Promise { + return this.client.xAck(key, group, ids); + } + + public async streamLength(key: string): Promise { + return this.client.xLen(key); + } + + public async publish(channel: string, message: string): Promise { + return this.client.publish(channel, message); + } +} diff --git a/apps/api/src/modules/global/global.module.ts b/apps/api/src/modules/global/global.module.ts new file mode 100644 index 00000000..ba3ea479 --- /dev/null +++ b/apps/api/src/modules/global/global.module.ts @@ -0,0 +1,13 @@ +import { Module, Global } from '@nestjs/common'; +import { SecretModule } from './secret/secret.module'; +import { NatsModule } from './nats/nats.module'; +import { DatabaseModule } from './database/database.module'; +import { GarnetModule } from './garnet/garnet.module'; + +@Global() +@Module({ + imports: [SecretModule, NatsModule, DatabaseModule, GarnetModule], + providers: [], + exports: [SecretModule, NatsModule, DatabaseModule, GarnetModule], +}) +export class GlobalModule {} diff --git a/apps/api/src/modules/global/nats/nats.constants.ts b/apps/api/src/modules/global/nats/nats.constants.ts new file mode 100644 index 00000000..dd4fc9b9 --- /dev/null +++ b/apps/api/src/modules/global/nats/nats.constants.ts @@ -0,0 +1 @@ +export const NATS_CLIENT = Symbol('NATS_CLIENT'); diff --git a/apps/api/src/modules/global/nats/nats.module.ts b/apps/api/src/modules/global/nats/nats.module.ts new file mode 100644 index 00000000..79d5a32b --- /dev/null +++ b/apps/api/src/modules/global/nats/nats.module.ts @@ -0,0 +1,45 @@ +import { Module } from '@nestjs/common'; +import fs from 'fs/promises'; +import { connect } from 'nats'; +import type { NatsConnection } from 'nats'; +import { SecretModule } from '../secret/secret.module'; +import { SecretService } from '../secret/secret.service'; +import { NATS_CLIENT } from './nats.constants'; +import { NatsService } from './nats.service'; + +@Module({ + imports: [SecretModule], + providers: [ + { + provide: NATS_CLIENT, + inject: [SecretService], + useFactory: async ( + secretService: SecretService, + ): Promise => { + await secretService.ready(); + + const [endpoint, user, password, serviceName] = await Promise.all([ + secretService.get('NATS_ENDPOINT'), + secretService.get('NATS_USER'), + secretService.get('NATS_PASS'), + secretService.get('SERVICE_NAME'), + ]); + + return connect({ + name: serviceName, + servers: [endpoint], + maxReconnectAttempts: -1, + reconnectTimeWait: 500, + reconnect: true, + pingInterval: 20000, + timeout: 5000, + user, + pass: password, + }); + }, + }, + NatsService, + ], + exports: [NatsService, NATS_CLIENT], +}) +export class NatsModule {} diff --git a/apps/api/src/modules/global/nats/nats.service.ts b/apps/api/src/modules/global/nats/nats.service.ts new file mode 100644 index 00000000..eb456d00 --- /dev/null +++ b/apps/api/src/modules/global/nats/nats.service.ts @@ -0,0 +1,117 @@ +import { + Inject, + Injectable, + Logger, + OnModuleDestroy, +} from '@nestjs/common'; +import { StringCodec } from 'nats'; +import type { Msg, NatsConnection, Subscription } from 'nats'; +import { NATS_CLIENT } from './nats.constants'; + +export type NatsMessageHandler = ( + data: T, + msg: Msg, +) => Promise | void; + +@Injectable() +export class NatsService implements OnModuleDestroy { + private readonly logger = new Logger(NatsService.name); + private readonly stringCodec = StringCodec(); + private readonly subscriptions = new Set(); + + constructor( + @Inject(NATS_CLIENT) private readonly natsClient: NatsConnection, + ) {} + + async onModuleDestroy() { + for (const sub of this.subscriptions) { + try { + sub.unsubscribe(); + } catch { + // ignore + } + } + this.subscriptions.clear(); + + try { + const closed = this.natsClient.closed(); + await this.natsClient.drain(); + const err = await closed; + if (err) this.logger.error(`NATS closed with error: ${err}`); + } catch { + try { + await this.natsClient.close(); + } catch { + // ignore + } + } + } + + public async publish(subject: string, data: T): Promise { + this.natsClient.publish( + subject, + this.stringCodec.encode(JSON.stringify(data)), + ); + await this.natsClient.flush(); + } + + public subscribe( + subject: string, + handler: NatsMessageHandler, + options?: { queue?: string }, + ): Subscription { + const sub = this.natsClient.subscribe(subject, { + queue: options?.queue, + }); + this.subscriptions.add(sub); + void this.consumeSubscription(sub, handler); + return sub; + } + + private async consumeSubscription( + sub: Subscription, + handler: NatsMessageHandler, + ): Promise { + try { + for await (const msg of sub) { + await this.dispatch(msg, handler); + } + } catch (err) { + this.logger.error( + `NATS subscription on subject="${sub.getSubject()}" terminated: ${ + (err as Error)?.message ?? err + }`, + ); + } finally { + this.subscriptions.delete(sub); + } + } + + private async dispatch( + msg: Msg, + handler: NatsMessageHandler, + ): Promise { + let data: T; + try { + const decoded = this.stringCodec.decode(msg.data); + data = JSON.parse(decoded) as T; + } catch (err) { + this.logger.warn( + `Failed to decode NATS message on subject="${msg.subject}": ${ + (err as Error)?.message ?? err + }`, + ); + return; + } + + try { + await handler(data, msg); + } catch (err) { + this.logger.error( + `Handler error on subject="${msg.subject}": ${ + (err as Error)?.stack ?? err + }`, + ); + } + } +} diff --git a/apps/api/src/modules/global/secret/secret.module.ts b/apps/api/src/modules/global/secret/secret.module.ts new file mode 100644 index 00000000..3412bc84 --- /dev/null +++ b/apps/api/src/modules/global/secret/secret.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { SecretService } from './secret.service'; + +@Module({ + imports: [], + providers: [SecretService], + exports: [SecretService], +}) +export class SecretModule {} diff --git a/apps/api/src/modules/global/secret/secret.service.ts b/apps/api/src/modules/global/secret/secret.service.ts new file mode 100644 index 00000000..bfa6c3c7 --- /dev/null +++ b/apps/api/src/modules/global/secret/secret.service.ts @@ -0,0 +1,152 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { InfisicalSDK } from '@infisical/sdk'; +import { ConfigService } from '@nestjs/config'; + +type SecretMap = Record; + +@Injectable() +export class SecretService { + private logger = new Logger(SecretService.name); + + private secrets: SecretMap | null = null; // null = 아직 로드 전 + private loading?: Promise; // 진행 중인 로드(중복 호출 방지) + 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('INFISICAL_SITE_URL') ?? + 'https://secret-manager.dahyeon.us/'; + this.clientSecret = this.config.get( + 'INFISICAL_CLIENT_SECRET', + ) as string; + this.clientId = this.config.get('INFISICAL_CLIENT_ID') as string; + this.projectId = this.config.get('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 }); + } + + /** 한 번만 로그인/페치. 동시에 여러 번 호출돼도 같은 Promise를 공유 */ + private async fetchSecrets(): Promise { + if (this.secrets) return; // 이미 로드됨 + if (this.loading) return this.loading; // 로드 중이면 그거 기다리기 + + this.loading = (async () => { + await this.infisicalClient.auth().universalAuth.login({ + clientId: this.clientId, + clientSecret: this.clientSecret, + }); + // console.log(this.infisicalClient) + + const res = await this.infisicalClient.secrets().listSecrets({ + environment: + process.env.NODE_ENV === 'prod' + ? 'prod' + : process.env.NODE_ENV === 'test' + ? 'staging' + : 'dev', + projectId: this.projectId, + }); + + // 임시 객체에 채운 뒤 한 번에 교체(일관성 보장) + const map: SecretMap = {}; + for (const s of res.secrets) { + map[s.secretKey] = s.secretValue; + } + + // 필요한 값은 process.env에 반영 + for (const k of this.PROCESS_ENVS) { + const v = map[k as string]; + if (typeof v === 'string' && v.length > 0) { + process.env[k as string] = v; + } + } + + this.secrets = map; + this.logger.log( + `Fetched ${Object.keys(map).length} secrets from Infisical`, + ); + })(); + + try { + await this.loading; + } finally { + this.loading = undefined; // 실패/성공 모두 끝나면 해제(실패 시 재시도 가능) + } + } + + /** lazy get: 필요할 때 처음 한번만 로드 */ + public async get(key: string, fallback?: T): Promise { + if (!this.secrets) { + await this.fetchSecrets(); + } + // console.log('Secrets loaded:', this.secrets); + const val = this.secrets![key]; + if (val === undefined) { + const cfg = this.config.get(key); + if (cfg !== undefined) return cfg; + if (fallback !== undefined) return fallback; + throw new Error(`Secret not found for key="${key}"`); + } + return val as T; + } + + /** 필요 시: 동기 접근(초기화 안됐으면 에러). constructor 등에서 강제 사용 금지 */ + public getSync(key: string, fallback?: T): T { + if (!this.secrets) { + const cfg = this.config.get(key); + if (cfg !== undefined) return cfg; + if (fallback !== undefined) return fallback; + throw new Error(`SecretService not initialized yet (key="${key}")`); + } + const val = this.secrets[key]; + if (val === undefined) { + const cfg = this.config.get(key); + if (cfg !== undefined) return cfg; + if (fallback !== undefined) return fallback; + throw new Error(`Secret not found for key="${key}"`); + } + return val as T; + } + + /** 선택: 사전에 강제로 로드하고 싶을 때 호출 */ + public async ready(): Promise { + await this.fetchSecrets(); + } +}