From 1fd08997561c1d0cd0065df9969aacdbdf4bb2cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=EB=8B=A4=ED=98=84=20=28Dahyeon=20Park=29?= Date: Fri, 1 May 2026 17:44:48 +0900 Subject: [PATCH] feat(api): implement tournament support backend --- apps/api/.gitignore | 56 + apps/api/.prettierrc | 4 + apps/api/docker-entrypoint.js | 72 + apps/api/eslint.config.mjs | 35 + apps/api/nest-cli.json | 8 + apps/api/package.json | 88 ++ apps/api/src/app.controller.spec.ts | 22 + apps/api/src/app.controller.ts | 14 + apps/api/src/app.module.ts | 42 + apps/api/src/app.service.ts | 8 + apps/api/src/main.ts | 34 + .../src/modules/auction/auction.controller.ts | 140 ++ .../src/modules/auction/auction.gateway.ts | 354 +++++ .../api/src/modules/auction/auction.module.ts | 15 + .../modules/auction/auction.service.spec.ts | 262 ++++ .../src/modules/auction/auction.service.ts | 436 ++++++ .../src/modules/auction/dto/auction.dto.ts | 60 + .../auth/allow-public-access.decorator.ts | 7 + apps/api/src/modules/auth/auth-request.ts | 16 + apps/api/src/modules/auth/auth.middleware.ts | 18 + apps/api/src/modules/auth/auth.module.ts | 33 + apps/api/src/modules/auth/auth.service.ts | 62 + .../auth/current-identity.decorator.ts | 11 + .../modules/auth/current-user.decorator.ts | 11 + .../modules/auth/identity-resolver.guard.ts | 38 + apps/api/src/modules/auth/identity.service.ts | 39 + apps/api/src/modules/auth/jwt.guard.ts | 91 ++ apps/api/src/modules/auth/jwt.service.ts | 100 ++ apps/api/src/modules/auth/permissions.ts | 35 + apps/api/src/modules/auth/roles.decorator.ts | 7 + apps/api/src/modules/auth/roles.guard.ts | 36 + .../modules/auth/user-resolver.guard.spec.ts | 55 + .../src/modules/auth/user-resolver.guard.ts | 33 + .../modules/common/parse-object-id.pipe.ts | 24 + .../community-stats-cache.service.ts | 59 + .../community-stats.controller.ts | 115 ++ .../community-stats/community-stats.module.ts | 11 + .../community-stats.service.ts | 1072 ++++++++++++++ .../community-stats/community-stats.types.ts | 196 +++ .../modules/community/community.controller.ts | 107 ++ .../src/modules/community/community.module.ts | 10 + .../modules/community/community.service.ts | 196 +++ .../community/dto/create-community.dto.ts | 47 + .../community/dto/transfer-ownership.dto.ts | 6 + .../modules/dakao/dakao-user.service.spec.ts | 90 ++ .../src/modules/dakao/dakao-user.service.ts | 393 ++++++ apps/api/src/modules/dakao/dakao.module.ts | 33 + apps/api/src/modules/dakao/dakao.options.ts | 13 + .../src/modules/dakao/dakao.publisher.spec.ts | 73 + apps/api/src/modules/dakao/dakao.publisher.ts | 154 ++ .../api/src/modules/dakao/dakao.subscriber.ts | 212 +++ apps/api/src/modules/dakao/dakao.types.ts | 102 ++ .../handlers/account-register.handler.spec.ts | 49 + .../handlers/account-register.handler.ts | 81 ++ .../dakao/handlers/match-join.handler.spec.ts | 138 ++ .../dakao/handlers/match-join.handler.ts | 128 ++ .../dakao/handlers/match-list.handler.ts | 63 + .../src/modules/dakao/idempotency.cache.ts | 35 + .../dakao/parsers/command.parser.spec.ts | 95 ++ .../modules/dakao/parsers/command.parser.ts | 147 ++ .../dakao/parsers/position.parser.spec.ts | 41 + .../modules/dakao/parsers/position.parser.ts | 87 ++ apps/api/src/modules/dakao/riot-id.util.ts | 14 + .../database/connection.service.spec.ts | 14 + .../global/database/connection.service.ts | 100 ++ .../global/database/database.module.ts | 9 + .../api/src/modules/global/database/schema.ts | 1244 +++++++++++++++++ .../src/modules/global/database/types.d.ts | 5 + .../modules/global/garnet/garnet.constants.ts | 1 + .../modules/global/garnet/garnet.module.ts | 57 + .../modules/global/garnet/garnet.service.ts | 213 +++ apps/api/src/modules/global/global.module.ts | 13 + .../src/modules/global/nats/nats.constants.ts | 1 + .../src/modules/global/nats/nats.module.ts | 45 + .../src/modules/global/nats/nats.service.ts | 117 ++ .../modules/global/secret/secret.module.ts | 9 + .../modules/global/secret/secret.service.ts | 152 ++ .../legacy-import/legacy-import.controller.ts | 150 ++ .../legacy-import/legacy-import.module.ts | 13 + .../legacy-import/legacy-import.service.ts | 775 ++++++++++ .../legacy-import/legacy-import.types.ts | 75 + .../legacy-import/match-builder.util.ts | 189 +++ .../match-history/match-history.controller.ts | 123 ++ .../match-history/match-history.module.ts | 12 + .../match-history/match-history.service.ts | 753 ++++++++++ .../match-history/match-history.types.ts | 146 ++ .../src/modules/match/dto/create-match.dto.ts | 145 ++ .../api/src/modules/match/match.controller.ts | 169 +++ apps/api/src/modules/match/match.module.ts | 13 + apps/api/src/modules/match/match.service.ts | 213 +++ .../riot-job-queue.controller.ts | 24 + .../riot-job-queue/riot-job-queue.module.ts | 16 + .../riot-job-queue/riot-job-queue.service.ts | 482 +++++++ .../riot-job-queue/riot-job-queue.types.ts | 88 ++ .../riot-job-queue/riot-job-worker.service.ts | 227 +++ .../riot-job-queue/riot-refresh.gateway.ts | 78 ++ .../riot-account-enrichment.service.spec.ts | 494 +++++++ .../riot/riot-account-enrichment.service.ts | 437 ++++++ .../src/modules/riot/riot-account.service.ts | 128 ++ .../riot/riot-champion-mastery.service.ts | 129 ++ .../modules/riot/riot-ddragon.controller.ts | 19 + .../src/modules/riot/riot-ddragon.service.ts | 142 ++ .../src/modules/riot/riot-league.service.ts | 79 ++ .../modules/riot/riot-match.service.spec.ts | 109 ++ .../src/modules/riot/riot-match.service.ts | 630 +++++++++ .../src/modules/riot/riot-queue.constants.ts | 88 ++ .../modules/riot/riot-rate-limiter.service.ts | 107 ++ .../riot/riot-recent-matches.service.ts | 153 ++ .../riot/riot-recent-stats.service.spec.ts | 304 ++++ .../modules/riot/riot-recent-stats.service.ts | 172 +++ .../src/modules/riot/riot-summoner.service.ts | 60 + .../riot/riot-webhook.controller.spec.ts | 60 + .../modules/riot/riot-webhook.controller.ts | 49 + .../src/modules/riot/riot.client.service.ts | 177 +++ apps/api/src/modules/riot/riot.module.ts | 47 + apps/api/src/modules/riot/riot.types.ts | 251 ++++ .../tournament-code.constants.ts | 4 + .../tournament-code.controller.ts | 105 ++ .../tournament-code/tournament-code.module.ts | 11 + .../tournament-code.scheduler.ts | 57 + .../tournament-code.service.ts | 365 +++++ .../tournament-code/tournament-code.types.ts | 31 + .../team-mapping.util.spec.ts | 144 ++ .../tournament-result/team-mapping.util.ts | 118 ++ .../tournament-result.controller.ts | 39 + .../tournament-result.module.ts | 14 + .../tournament-result.service.ts | 464 ++++++ .../tournament-result.types.ts | 30 + .../src/modules/user/dto/me-response.dto.ts | 22 + .../user/dto/refresh-riot-account.dto.ts | 13 + apps/api/src/modules/user/user.controller.ts | 120 ++ apps/api/src/modules/user/user.module.ts | 9 + apps/api/src/seed-dakao-participant.ts | 241 ++++ apps/api/src/seed.ts | 1087 ++++++++++++++ apps/api/start.ps1 | 68 + apps/api/test/app.e2e-spec.ts | 29 + apps/api/test/jest-e2e.json | 9 + apps/api/tsconfig.build.json | 4 + apps/api/tsconfig.json | 25 + 139 files changed, 18348 insertions(+) create mode 100644 apps/api/.gitignore create mode 100644 apps/api/.prettierrc create mode 100644 apps/api/docker-entrypoint.js create mode 100644 apps/api/eslint.config.mjs create mode 100644 apps/api/nest-cli.json create mode 100644 apps/api/package.json create mode 100644 apps/api/src/app.controller.spec.ts create mode 100644 apps/api/src/app.controller.ts create mode 100644 apps/api/src/app.module.ts create mode 100644 apps/api/src/app.service.ts create mode 100644 apps/api/src/main.ts create mode 100644 apps/api/src/modules/auction/auction.controller.ts create mode 100644 apps/api/src/modules/auction/auction.gateway.ts create mode 100644 apps/api/src/modules/auction/auction.module.ts create mode 100644 apps/api/src/modules/auction/auction.service.spec.ts create mode 100644 apps/api/src/modules/auction/auction.service.ts create mode 100644 apps/api/src/modules/auction/dto/auction.dto.ts create mode 100644 apps/api/src/modules/auth/allow-public-access.decorator.ts create mode 100644 apps/api/src/modules/auth/auth-request.ts create mode 100644 apps/api/src/modules/auth/auth.middleware.ts create mode 100644 apps/api/src/modules/auth/auth.module.ts create mode 100644 apps/api/src/modules/auth/auth.service.ts create mode 100644 apps/api/src/modules/auth/current-identity.decorator.ts create mode 100644 apps/api/src/modules/auth/current-user.decorator.ts create mode 100644 apps/api/src/modules/auth/identity-resolver.guard.ts create mode 100644 apps/api/src/modules/auth/identity.service.ts create mode 100644 apps/api/src/modules/auth/jwt.guard.ts create mode 100644 apps/api/src/modules/auth/jwt.service.ts create mode 100644 apps/api/src/modules/auth/permissions.ts create mode 100644 apps/api/src/modules/auth/roles.decorator.ts create mode 100644 apps/api/src/modules/auth/roles.guard.ts create mode 100644 apps/api/src/modules/auth/user-resolver.guard.spec.ts create mode 100644 apps/api/src/modules/auth/user-resolver.guard.ts create mode 100644 apps/api/src/modules/common/parse-object-id.pipe.ts create mode 100644 apps/api/src/modules/community-stats/community-stats-cache.service.ts create mode 100644 apps/api/src/modules/community-stats/community-stats.controller.ts create mode 100644 apps/api/src/modules/community-stats/community-stats.module.ts create mode 100644 apps/api/src/modules/community-stats/community-stats.service.ts create mode 100644 apps/api/src/modules/community-stats/community-stats.types.ts create mode 100644 apps/api/src/modules/community/community.controller.ts create mode 100644 apps/api/src/modules/community/community.module.ts create mode 100644 apps/api/src/modules/community/community.service.ts create mode 100644 apps/api/src/modules/community/dto/create-community.dto.ts create mode 100644 apps/api/src/modules/community/dto/transfer-ownership.dto.ts create mode 100644 apps/api/src/modules/dakao/dakao-user.service.spec.ts create mode 100644 apps/api/src/modules/dakao/dakao-user.service.ts create mode 100644 apps/api/src/modules/dakao/dakao.module.ts create mode 100644 apps/api/src/modules/dakao/dakao.options.ts create mode 100644 apps/api/src/modules/dakao/dakao.publisher.spec.ts create mode 100644 apps/api/src/modules/dakao/dakao.publisher.ts create mode 100644 apps/api/src/modules/dakao/dakao.subscriber.ts create mode 100644 apps/api/src/modules/dakao/dakao.types.ts create mode 100644 apps/api/src/modules/dakao/handlers/account-register.handler.spec.ts create mode 100644 apps/api/src/modules/dakao/handlers/account-register.handler.ts create mode 100644 apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts create mode 100644 apps/api/src/modules/dakao/handlers/match-join.handler.ts create mode 100644 apps/api/src/modules/dakao/handlers/match-list.handler.ts create mode 100644 apps/api/src/modules/dakao/idempotency.cache.ts create mode 100644 apps/api/src/modules/dakao/parsers/command.parser.spec.ts create mode 100644 apps/api/src/modules/dakao/parsers/command.parser.ts create mode 100644 apps/api/src/modules/dakao/parsers/position.parser.spec.ts create mode 100644 apps/api/src/modules/dakao/parsers/position.parser.ts create mode 100644 apps/api/src/modules/dakao/riot-id.util.ts create mode 100644 apps/api/src/modules/global/database/connection.service.spec.ts create mode 100644 apps/api/src/modules/global/database/connection.service.ts create mode 100644 apps/api/src/modules/global/database/database.module.ts create mode 100644 apps/api/src/modules/global/database/schema.ts create mode 100644 apps/api/src/modules/global/database/types.d.ts create mode 100644 apps/api/src/modules/global/garnet/garnet.constants.ts create mode 100644 apps/api/src/modules/global/garnet/garnet.module.ts create mode 100644 apps/api/src/modules/global/garnet/garnet.service.ts create mode 100644 apps/api/src/modules/global/global.module.ts create mode 100644 apps/api/src/modules/global/nats/nats.constants.ts create mode 100644 apps/api/src/modules/global/nats/nats.module.ts create mode 100644 apps/api/src/modules/global/nats/nats.service.ts create mode 100644 apps/api/src/modules/global/secret/secret.module.ts create mode 100644 apps/api/src/modules/global/secret/secret.service.ts create mode 100644 apps/api/src/modules/legacy-import/legacy-import.controller.ts create mode 100644 apps/api/src/modules/legacy-import/legacy-import.module.ts create mode 100644 apps/api/src/modules/legacy-import/legacy-import.service.ts create mode 100644 apps/api/src/modules/legacy-import/legacy-import.types.ts create mode 100644 apps/api/src/modules/legacy-import/match-builder.util.ts create mode 100644 apps/api/src/modules/match-history/match-history.controller.ts create mode 100644 apps/api/src/modules/match-history/match-history.module.ts create mode 100644 apps/api/src/modules/match-history/match-history.service.ts create mode 100644 apps/api/src/modules/match-history/match-history.types.ts create mode 100644 apps/api/src/modules/match/dto/create-match.dto.ts create mode 100644 apps/api/src/modules/match/match.controller.ts create mode 100644 apps/api/src/modules/match/match.module.ts create mode 100644 apps/api/src/modules/match/match.service.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts create mode 100644 apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts create mode 100644 apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts create mode 100644 apps/api/src/modules/riot/riot-account-enrichment.service.ts create mode 100644 apps/api/src/modules/riot/riot-account.service.ts create mode 100644 apps/api/src/modules/riot/riot-champion-mastery.service.ts create mode 100644 apps/api/src/modules/riot/riot-ddragon.controller.ts create mode 100644 apps/api/src/modules/riot/riot-ddragon.service.ts create mode 100644 apps/api/src/modules/riot/riot-league.service.ts create mode 100644 apps/api/src/modules/riot/riot-match.service.spec.ts create mode 100644 apps/api/src/modules/riot/riot-match.service.ts create mode 100644 apps/api/src/modules/riot/riot-queue.constants.ts create mode 100644 apps/api/src/modules/riot/riot-rate-limiter.service.ts create mode 100644 apps/api/src/modules/riot/riot-recent-matches.service.ts create mode 100644 apps/api/src/modules/riot/riot-recent-stats.service.spec.ts create mode 100644 apps/api/src/modules/riot/riot-recent-stats.service.ts create mode 100644 apps/api/src/modules/riot/riot-summoner.service.ts create mode 100644 apps/api/src/modules/riot/riot-webhook.controller.spec.ts create mode 100644 apps/api/src/modules/riot/riot-webhook.controller.ts create mode 100644 apps/api/src/modules/riot/riot.client.service.ts create mode 100644 apps/api/src/modules/riot/riot.module.ts create mode 100644 apps/api/src/modules/riot/riot.types.ts create mode 100644 apps/api/src/modules/tournament-code/tournament-code.constants.ts create mode 100644 apps/api/src/modules/tournament-code/tournament-code.controller.ts create mode 100644 apps/api/src/modules/tournament-code/tournament-code.module.ts create mode 100644 apps/api/src/modules/tournament-code/tournament-code.scheduler.ts create mode 100644 apps/api/src/modules/tournament-code/tournament-code.service.ts create mode 100644 apps/api/src/modules/tournament-code/tournament-code.types.ts create mode 100644 apps/api/src/modules/tournament-result/team-mapping.util.spec.ts create mode 100644 apps/api/src/modules/tournament-result/team-mapping.util.ts create mode 100644 apps/api/src/modules/tournament-result/tournament-result.controller.ts create mode 100644 apps/api/src/modules/tournament-result/tournament-result.module.ts create mode 100644 apps/api/src/modules/tournament-result/tournament-result.service.ts create mode 100644 apps/api/src/modules/tournament-result/tournament-result.types.ts create mode 100644 apps/api/src/modules/user/dto/me-response.dto.ts create mode 100644 apps/api/src/modules/user/dto/refresh-riot-account.dto.ts create mode 100644 apps/api/src/modules/user/user.controller.ts create mode 100644 apps/api/src/modules/user/user.module.ts create mode 100644 apps/api/src/seed-dakao-participant.ts create mode 100644 apps/api/src/seed.ts create mode 100644 apps/api/start.ps1 create mode 100644 apps/api/test/app.e2e-spec.ts create mode 100644 apps/api/test/jest-e2e.json create mode 100644 apps/api/tsconfig.build.json create mode 100644 apps/api/tsconfig.json diff --git a/apps/api/.gitignore b/apps/api/.gitignore new file mode 100644 index 00000000..4b56acfb --- /dev/null +++ b/apps/api/.gitignore @@ -0,0 +1,56 @@ +# compiled output +/dist +/node_modules +/build + +# Logs +logs +*.log +npm-debug.log* +pnpm-debug.log* +yarn-debug.log* +yarn-error.log* +lerna-debug.log* + +# OS +.DS_Store + +# Tests +/coverage +/.nyc_output + +# IDEs and editors +/.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# dotenv environment variable files +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# temp directory +.temp +.tmp + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Diagnostic reports (https://nodejs.org/api/report.html) +report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json diff --git a/apps/api/.prettierrc b/apps/api/.prettierrc new file mode 100644 index 00000000..a20502b7 --- /dev/null +++ b/apps/api/.prettierrc @@ -0,0 +1,4 @@ +{ + "singleQuote": true, + "trailingComma": "all" +} diff --git a/apps/api/docker-entrypoint.js b/apps/api/docker-entrypoint.js new file mode 100644 index 00000000..267e7b42 --- /dev/null +++ b/apps/api/docker-entrypoint.js @@ -0,0 +1,72 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); + +const MACHINE_ENV_PATHS = [ + process.env.MachineEnvFile, + process.env.MACHINE_ENV_FILE, + '/source/global-env-vars.txt', + process.env.HOME + ? path.join(process.env.HOME, 'source/global-env-vars.txt') + : '', +].filter(Boolean); + +const PROJECT_ENV_PATHS = [ + 'project.env', + '/app/project.env', + 'apps/project.env', +]; + +function stripQuotes(value) { + const trimmed = value.trim(); + if ( + (trimmed.startsWith('"') && trimmed.endsWith('"')) || + (trimmed.startsWith("'") && trimmed.endsWith("'")) + ) { + return trimmed.slice(1, -1); + } + return trimmed; +} + +function loadEnvFile(filePath, options = {}) { + const { override = false } = options; + const content = fs.readFileSync(filePath, 'utf8'); + for (const line of content.split(/\r?\n/u)) { + if (!line.trim() || /^\s*#/u.test(line)) continue; + + const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/u); + if (!match) continue; + + if (!override && process.env[match[1]] !== undefined) continue; + process.env[match[1]] = stripQuotes(match[2]); + } +} + +const machineEnvFile = MACHINE_ENV_PATHS.find((candidate) => + fs.existsSync(candidate), +); +if (machineEnvFile) { + loadEnvFile(machineEnvFile, { override: true }); +} + +for (const projectEnvFile of PROJECT_ENV_PATHS) { + if (fs.existsSync(projectEnvFile)) { + loadEnvFile(projectEnvFile); + } +} + +const missing = [ + 'INFISICAL_CLIENT_ID', + 'INFISICAL_CLIENT_SECRET', + 'INFISICAL_PROJECT_ID', +].filter((key) => !process.env[key]); + +if (missing.length > 0) { + console.error( + `Missing required environment variables: ${missing.join(', ')}`, + ); + process.exit(1); +} + +require('./dist/main.js'); diff --git a/apps/api/eslint.config.mjs b/apps/api/eslint.config.mjs new file mode 100644 index 00000000..4e9f8271 --- /dev/null +++ b/apps/api/eslint.config.mjs @@ -0,0 +1,35 @@ +// @ts-check +import eslint from '@eslint/js'; +import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended'; +import globals from 'globals'; +import tseslint from 'typescript-eslint'; + +export default tseslint.config( + { + ignores: ['eslint.config.mjs'], + }, + eslint.configs.recommended, + ...tseslint.configs.recommendedTypeChecked, + eslintPluginPrettierRecommended, + { + languageOptions: { + globals: { + ...globals.node, + ...globals.jest, + }, + sourceType: 'commonjs', + parserOptions: { + projectService: true, + tsconfigRootDir: import.meta.dirname, + }, + }, + }, + { + rules: { + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-floating-promises': 'warn', + '@typescript-eslint/no-unsafe-argument': 'warn', + "prettier/prettier": ["error", { endOfLine: "auto" }], + }, + }, +); diff --git a/apps/api/nest-cli.json b/apps/api/nest-cli.json new file mode 100644 index 00000000..f9aa683b --- /dev/null +++ b/apps/api/nest-cli.json @@ -0,0 +1,8 @@ +{ + "$schema": "https://json.schemastore.org/nest-cli", + "collection": "@nestjs/schematics", + "sourceRoot": "src", + "compilerOptions": { + "deleteOutDir": true + } +} diff --git a/apps/api/package.json b/apps/api/package.json new file mode 100644 index 00000000..a45ff898 --- /dev/null +++ b/apps/api/package.json @@ -0,0 +1,88 @@ +{ + "name": "api", + "version": "0.0.1", + "description": "", + "author": "", + "private": true, + "license": "UNLICENSED", + "scripts": { + "build": "nest build", + "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", + "seed:dev": "ts-node src/seed.ts", + "seed:dakao-participant": "ts-node src/seed-dakao-participant.ts", + "start:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); \"./start.ps1\"\"", + "start:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); \"./start.ps1\"\"", + "start:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); \"./start.ps1\"\"", + "pm2:dev": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'dev'); ./start.ps1 -UsePm2\"", + "pm2:test": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'test'); ./start.ps1 -UsePm2\"", + "pm2:prod": "pwsh -Command \"[System.Environment]::SetEnvironmentVariable('NODE_ENV', 'prod'); ./start.ps1 -UsePm2\"", + "start:debug": "nest start --debug --watch", + "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", + "test": "jest", + "test:watch": "jest --watch", + "test:cov": "jest --coverage", + "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", + "test:e2e": "jest --config ./test/jest-e2e.json" + }, + "dependencies": { + "@nestjs/common": "^11.0.1", + "@nestjs/config": "^4.0.4", + "@nestjs/core": "^11.0.1", + "@nestjs/platform-express": "^11.0.1", + "@nestjs/platform-socket.io": "^11.1.19", + "@nestjs/swagger": "^11.2.7", + "@nestjs/websockets": "^11.1.19", + "class-transformer": "^0.5.1", + "class-validator": "^0.15.1", + "jose": "^6.2.2", + "mongoose": "^9.4.1", + "nats": "^2.29.3", + "redis": "^5.12.1", + "reflect-metadata": "^0.2.2", + "rxjs": "^7.8.1", + "socket.io": "^4.8.3", + "temporal-polyfill": "^0.3.2" + }, + "devDependencies": { + "@eslint/eslintrc": "^3.2.0", + "@eslint/js": "^9.18.0", + "@nestjs/cli": "^11.0.0", + "@nestjs/schematics": "^11.0.0", + "@nestjs/testing": "^11.0.1", + "@types/express": "^5.0.0", + "@types/jest": "^30.0.0", + "@types/node": "^24.0.0", + "@types/supertest": "^7.0.0", + "eslint": "^9.18.0", + "eslint-config-prettier": "^10.0.1", + "eslint-plugin-prettier": "^5.2.2", + "globals": "^17.0.0", + "jest": "^30.0.0", + "prettier": "^3.4.2", + "source-map-support": "^0.5.21", + "supertest": "^7.0.0", + "ts-jest": "^29.2.5", + "ts-loader": "^9.5.2", + "ts-node": "^10.9.2", + "tsconfig-paths": "^4.2.0", + "typescript": "^5.7.3", + "typescript-eslint": "^8.20.0" + }, + "jest": { + "moduleFileExtensions": [ + "js", + "json", + "ts" + ], + "rootDir": "src", + "testRegex": ".*\\.spec\\.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + }, + "collectCoverageFrom": [ + "**/*.(t|j)s" + ], + "coverageDirectory": "../coverage", + "testEnvironment": "node" + } +} diff --git a/apps/api/src/app.controller.spec.ts b/apps/api/src/app.controller.spec.ts new file mode 100644 index 00000000..d22f3890 --- /dev/null +++ b/apps/api/src/app.controller.spec.ts @@ -0,0 +1,22 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { AppController } from './app.controller'; +import { AppService } from './app.service'; + +describe('AppController', () => { + let appController: AppController; + + beforeEach(async () => { + const app: TestingModule = await Test.createTestingModule({ + controllers: [AppController], + providers: [AppService], + }).compile(); + + appController = app.get(AppController); + }); + + describe('root', () => { + it('should return "Hello World!"', () => { + expect(appController.getHello()).toBe('Hello World!'); + }); + }); +}); diff --git a/apps/api/src/app.controller.ts b/apps/api/src/app.controller.ts new file mode 100644 index 00000000..64b83aaf --- /dev/null +++ b/apps/api/src/app.controller.ts @@ -0,0 +1,14 @@ +import { Controller, Get } from '@nestjs/common'; +import { AllowPublicAccess } from './modules/auth/allow-public-access.decorator'; +import { AppService } from './app.service'; + +@Controller() +export class AppController { + constructor(private readonly appService: AppService) {} + + @Get() + @AllowPublicAccess() + getHello(): string { + return this.appService.getHello(); + } +} diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts new file mode 100644 index 00000000..b51b0165 --- /dev/null +++ b/apps/api/src/app.module.ts @@ -0,0 +1,42 @@ +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { AppController } from './app.controller'; +import { AppService } from './app.service'; +import { AuctionModule } from './modules/auction/auction.module'; +import { AuthModule } from './modules/auth/auth.module'; +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'; +import { TournamentCodeModule } from './modules/tournament-code/tournament-code.module'; +import { TournamentResultModule } from './modules/tournament-result/tournament-result.module'; +import { UserModule } from './modules/user/user.module'; + +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + envFilePath: ['../project.env', 'project.env'], + }), + GlobalModule, + AuthModule, + RiotModule, + CommunityModule, + CommunityStatsModule, + MatchModule, + MatchHistoryModule, + LegacyImportModule, + TournamentCodeModule, + TournamentResultModule, + AuctionModule, + UserModule, + DakaoModule, + ], + controllers: [AppController], + providers: [AppService], +}) +export class AppModule {} diff --git a/apps/api/src/app.service.ts b/apps/api/src/app.service.ts new file mode 100644 index 00000000..927d7cca --- /dev/null +++ b/apps/api/src/app.service.ts @@ -0,0 +1,8 @@ +import { Injectable } from '@nestjs/common'; + +@Injectable() +export class AppService { + getHello(): string { + return 'Hello World!'; + } +} diff --git a/apps/api/src/main.ts b/apps/api/src/main.ts new file mode 100644 index 00000000..9efa99fa --- /dev/null +++ b/apps/api/src/main.ts @@ -0,0 +1,34 @@ +import { ValidationPipe } from '@nestjs/common'; +import { NestFactory } from '@nestjs/core'; +import { AppModule } from './app.module'; + +async function bootstrap() { + const app = await NestFactory.create(AppModule, { + rawBody: true, + }); + + const isDev = process.env.NODE_ENV === 'dev'; + const webOrigins = process.env.WEB_ORIGIN?.split(',').map((origin) => + origin.trim(), + ) ?? [ + 'http://localhost:5173', + 'http://126.dahyeon.us:5173', + 'https://lolympus.dahyeon.us', + ]; + + app.enableCors({ + origin: isDev ? true : webOrigins, + credentials: true, + allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], + }); + app.useGlobalPipes( + new ValidationPipe({ + whitelist: true, + forbidNonWhitelisted: true, + transform: true, + transformOptions: { enableImplicitConversion: false }, + }), + ); + await app.listen(isDev ? 3000 : 10712); +} +bootstrap(); diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts new file mode 100644 index 00000000..49efe3ee --- /dev/null +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -0,0 +1,140 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + Param, + Post, + UseGuards, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +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 { AuctionService } from './auction.service'; +import { PlaceBidDto, SoldDto, StartAuctionDto } from './dto/auction.dto'; + +@Controller('communities/:communityId/matches/:matchId/auction') +export class AuctionController { + constructor(private readonly auctionService: AuctionService) {} + + @Post() + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async startAuction( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: StartAuctionDto, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.auctionService.start({ + matchId, + communityId, + captains: body.captains.map((c) => ({ + side: c.side, + userId: new mongoose.Types.ObjectId(c.userId), + })), + initialPoints: body.initialPoints ?? 1000, + maxTimerSeconds: body.maxTimerSeconds ?? 30, + }); + } + + @Get() + @AllowPublicAccess() + public async getAuction( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + return this.auctionService.getByMatchId(matchId); + } + + // 공개 — 팀장 2명만 쓸 엔드포인트(트러스트 기반, 10명 동시 관전). + @Post('open-bidding') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async openBidding( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + return this.auctionService.openBidding(matchId); + } + + @Post('bids') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async placeBid( + @CurrentUser() currentUser: UserDocument | undefined, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: PlaceBidDto, + ) { + return this.auctionService.placeBid({ + matchId, + side: body.side, + amount: body.amount, + bidderUserId: this.resolveBidder(currentUser, body.bidderUserId), + }); + } + + @Post('sold') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async markSold( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: SoldDto, + ) { + return this.auctionService.markSold({ + matchId, + assignedPosition: body.assignedPosition, + }); + } + + @Post('next') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public async next( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + return this.auctionService.next(matchId); + } + + @Delete() + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + @HttpCode(HttpStatus.NO_CONTENT) + public async resetAuction( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.auctionService.reset({ matchId, communityId }); + } + + private resolveBidder( + currentUser: UserDocument | undefined, + bodyBidder?: string, + ): mongoose.Types.ObjectId | undefined { + if (currentUser) return currentUser._id; + if (!bodyBidder) return undefined; + if (!mongoose.isValidObjectId(bodyBidder)) { + throw new BadRequestException('Invalid bidderUserId.'); + } + return new mongoose.Types.ObjectId(bodyBidder); + } + + private assertSameCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + } +} diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts new file mode 100644 index 00000000..c0c94a26 --- /dev/null +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -0,0 +1,354 @@ +import { Logger } from '@nestjs/common'; +import { + ConnectedSocket, + MessageBody, + OnGatewayConnection, + OnGatewayDisconnect, + SubscribeMessage, + WebSocketGateway, + WebSocketServer, +} from '@nestjs/websockets'; +import mongoose from 'mongoose'; +import type { JWTPayload } from 'jose'; +import { Namespace, Socket } from 'socket.io'; +import { AuthService } from '../auth/auth.service'; +import { IdentityService } from '../auth/identity.service'; +import { JwtService } from '../auth/jwt.service'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + AuctionDocument, + IdentityDocument, + Position, + TeamSide, + UserDocument, +} from '../global/database/schema'; +import { AuctionService } from './auction.service'; + +interface JoinAuctionPayload { + matchId: string; +} + +interface BidPayload { + side: TeamSide; + amount: number; + bidderUserId?: string; +} + +interface SoldPayload { + assignedPosition?: Position; +} + +@WebSocketGateway({ + namespace: '/auction', + cors: { + origin: true, + credentials: true, + allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], + }, +}) +export class AuctionGateway + implements OnGatewayConnection, OnGatewayDisconnect +{ + @WebSocketServer() + private server!: Namespace; + + private readonly logger = new Logger(AuctionGateway.name); + private readonly roomTimers = new Map(); + + constructor( + private readonly auctionService: AuctionService, + private readonly authService: AuthService, + private readonly jwtService: JwtService, + private readonly identityService: IdentityService, + private readonly connectionService: ConnectionService, + ) {} + + public async handleConnection(socket: Socket) { + try { + await this.authenticateSocket(socket); + this.logger.debug(`Auction client connected: ${socket.id}`); + } catch (err) { + this.logger.warn( + `Auction client authentication failed: ${ + err instanceof Error ? err.message : err + }`, + ); + socket.disconnect(true); + } + } + + public handleDisconnect(socket: Socket) { + const matchId = this.getSocketMatchId(socket); + if (!matchId) return; + this.maybeClearRoomTimer(matchId); + } + + @SubscribeMessage('join') + public async handleJoin( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: JoinAuctionPayload, + ) { + if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) { + this.emitError(socket, 'Invalid matchId.'); + return; + } + + await socket.join(payload.matchId); + socket.data.matchId = payload.matchId; + + try { + await this.resolveSocketUserForMatch(socket, payload.matchId); + const auction = await this.auctionService.getByMatchId( + new mongoose.Types.ObjectId(payload.matchId), + ); + this.broadcastState(payload.matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('bid') + public async handleBid( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: BidPayload, + ) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + const bidderUserId = this.resolveBidderUserId(socket, payload?.bidderUserId); + if (payload?.bidderUserId && !bidderUserId) { + this.emitError(socket, 'Invalid bidderUserId.'); + return; + } + + try { + const auction = await this.auctionService.placeBid({ + matchId: new mongoose.Types.ObjectId(matchId), + side: payload.side, + amount: payload.amount, + bidderUserId, + }); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('open-bidding') + public async handleOpenBidding(@ConnectedSocket() socket: Socket) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.openBidding( + new mongoose.Types.ObjectId(matchId), + ); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('sold') + public async handleSold( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: SoldPayload, + ) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.markSold({ + matchId: new mongoose.Types.ObjectId(matchId), + assignedPosition: payload?.assignedPosition, + }); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + @SubscribeMessage('next') + public async handleNext(@ConnectedSocket() socket: Socket) { + const matchId = this.requireJoinedMatchId(socket); + if (!matchId) return; + + try { + const auction = await this.auctionService.next( + new mongoose.Types.ObjectId(matchId), + ); + this.broadcastState(matchId, auction); + } catch (error) { + this.emitKnownError(socket, error); + } + } + + private requireJoinedMatchId(socket: Socket): string | null { + const matchId = this.getSocketMatchId(socket); + if (!matchId) { + this.emitError(socket, 'Join a match room before sending events.'); + return null; + } + return matchId; + } + + private getSocketMatchId(socket: Socket): string | undefined { + return typeof socket.data.matchId === 'string' + ? socket.data.matchId + : undefined; + } + + private resolveBidderUserId( + socket: Socket, + payloadBidderUserId?: string, + ): mongoose.Types.ObjectId | undefined { + const candidate = + payloadBidderUserId ?? + (socket.data.user as UserDocument | undefined)?._id.toString() ?? + this.readHandshakeUserId(socket); + if (!candidate || !mongoose.isValidObjectId(candidate)) { + return undefined; + } + return new mongoose.Types.ObjectId(candidate); + } + + private readHandshakeUserId(socket: Socket): string | undefined { + const authUserId = socket.handshake.auth['x-auth-user-id']; + if (typeof authUserId === 'string') return authUserId; + + const header = socket.handshake.headers['x-auth-user-id']; + return Array.isArray(header) ? header[0] : header; + } + + private async authenticateSocket(socket: Socket): Promise { + const fallback = await this.authService.resolveDevUserById( + this.readHandshakeUserId(socket), + ); + if (fallback) { + socket.data.user = fallback.user; + socket.data.identity = fallback.identity; + return; + } + + const token = this.readHandshakeToken(socket); + if (!token) { + // 임시 운영용: 경매 진행 중에는 로그인 없이도 관전/팀장 모드 선택/입찰을 허용한다. + return; + } + + const { payload } = await this.jwtService.verify( + token, + 'MICROSOFT_ENTRAID', + ); + socket.data.identity = await this.identityService.findOrCreateByOid({ + entraOid: this.requireStringClaim(payload, 'oid'), + tenantId: this.stringClaim(payload.tid), + email: + this.stringClaim(payload.preferred_username) ?? + this.stringClaim(payload.email), + displayName: this.stringClaim(payload.name), + }); + } + + private readHandshakeToken(socket: Socket): string | undefined { + const authToken = socket.handshake.auth.token; + if (typeof authToken === 'string' && authToken.trim()) { + return authToken.trim().replace(/^Bearer\s+/i, ''); + } + + const header = socket.handshake.headers.authorization; + const authorization = Array.isArray(header) ? header[0] : header; + if (authorization?.startsWith('Bearer ')) { + return authorization.slice('Bearer '.length).trim(); + } + return undefined; + } + + private async resolveSocketUserForMatch( + socket: Socket, + matchId: string, + ): Promise { + if (socket.data.user || !socket.data.identity) return; + + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(matchId).select({ + communityId: 1, + }); + if (!match) return; + + const UserModel = await this.connectionService.getModel('user'); + socket.data.user = await UserModel.findOne({ + communityId: match.communityId, + identityId: (socket.data.identity as IdentityDocument)._id, + }).exec(); + } + + private requireStringClaim(payload: JWTPayload, key: string): string { + const value = payload[key]; + if (typeof value !== 'string' || value.length === 0) { + throw new Error(`Token is missing ${key} claim.`); + } + return value; + } + + private stringClaim(value: unknown): string | undefined { + return typeof value === 'string' && value.length > 0 ? value : undefined; + } + + private broadcastState(matchId: string, auction: AuctionDocument) { + this.server.to(matchId).emit('state', this.serializeAuction(auction)); + this.syncRoomTimer(matchId, auction); + } + + private syncRoomTimer(matchId: string, auction: AuctionDocument) { + this.clearRoomTimer(matchId); + if (!auction.currentDeadline) return; + + const deadline = auction.currentDeadline; + const deadlineIso = deadline.toISOString(); + this.server.to(matchId).emit('tick', { + deadline: deadlineIso, + serverTime: new Date().toISOString(), + }); + + const timer = setInterval(() => { + this.server.to(matchId).emit('tick', { + deadline: deadlineIso, + serverTime: new Date().toISOString(), + }); + + if (Date.now() >= deadline.getTime()) { + this.clearRoomTimer(matchId); + } + }, 1000); + + this.roomTimers.set(matchId, timer); + } + + private maybeClearRoomTimer(matchId: string) { + const room = this.server.adapter.rooms.get(matchId); + if (room && room.size > 0) return; + this.clearRoomTimer(matchId); + } + + private clearRoomTimer(matchId: string) { + const timer = this.roomTimers.get(matchId); + if (!timer) return; + clearInterval(timer); + this.roomTimers.delete(matchId); + } + + private emitKnownError(socket: Socket, error: unknown) { + const message = + error instanceof Error ? error.message : 'Unexpected auction gateway error.'; + this.emitError(socket, message); + } + + private emitError(socket: Socket, message: string) { + socket.emit('error', { message }); + } + + private serializeAuction(auction: AuctionDocument) { + return JSON.parse(JSON.stringify(auction)); + } +} diff --git a/apps/api/src/modules/auction/auction.module.ts b/apps/api/src/modules/auction/auction.module.ts new file mode 100644 index 00000000..fbbb1ccd --- /dev/null +++ b/apps/api/src/modules/auction/auction.module.ts @@ -0,0 +1,15 @@ +import { Module } from '@nestjs/common'; +import { RiotModule } from '../riot/riot.module'; +import { TournamentCodeModule } from '../tournament-code/tournament-code.module'; +import { TournamentResultModule } from '../tournament-result/tournament-result.module'; +import { AuctionGateway } from './auction.gateway'; +import { AuctionController } from './auction.controller'; +import { AuctionService } from './auction.service'; + +@Module({ + imports: [RiotModule, TournamentCodeModule, TournamentResultModule], + controllers: [AuctionController], + providers: [AuctionService, AuctionGateway], + exports: [AuctionService], +}) +export class AuctionModule {} diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts new file mode 100644 index 00000000..bf1be579 --- /dev/null +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -0,0 +1,262 @@ +import mongoose from 'mongoose'; +import { AuctionService } from './auction.service'; + +describe('AuctionService', () => { + function createService(models: Record) { + const connectionService = { + getModel: jest.fn((name: string) => models[name]), + createSession: jest.fn(), + }; + const enrichmentService = { + enrichRiotAccount: jest.fn(), + }; + const tournamentCodeService = { + reserveForMatch: jest.fn().mockResolvedValue(undefined), + releaseFromMatch: jest.fn().mockResolvedValue(undefined), + }; + const tournamentResultService = { + scheduleInitialPoll: jest.fn().mockResolvedValue(null), + }; + + return { + service: new AuctionService( + connectionService as never, + enrichmentService as never, + tournamentCodeService as never, + tournamentResultService as never, + ), + connectionService, + tournamentCodeService, + tournamentResultService, + }; + } + + function createFullTeam(side: 'blue' | 'red') { + return { + side, + captainUserId: new mongoose.Types.ObjectId(), + points: 100, + members: Array.from({ length: 4 }, () => ({ + userId: new mongoose.Types.ObjectId(), + assignedPosition: 'MID', + cost: 10, + })), + }; + } + + it('rejects bids when the team already has 5 members including captain', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + phase: 'bidding', + teams: [createFullTeam('blue'), createFullTeam('red')], + currentBid: 10, + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await expect( + service.placeBid({ + matchId, + side: 'blue', + amount: 20, + }), + ).rejects.toThrow('Team already has maximum members.'); + expect(auction.save).not.toHaveBeenCalled(); + }); + + it('rejects sold confirmation when the winning team is already full', async () => { + const matchId = new mongoose.Types.ObjectId(); + const auction = { + phase: 'bidding', + currentBidder: 'blue', + currentBid: 20, + currentIndex: 0, + order: [ + { + userId: new mongoose.Types.ObjectId(), + preferredPositions: [{ position: 'ADC', priority: 1 }], + }, + ], + teams: [createFullTeam('blue'), createFullTeam('red')], + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + }); + + await expect(service.markSold({ matchId })).rejects.toThrow( + 'Team already has maximum members.', + ); + expect(auction.save).not.toHaveBeenCalled(); + }); + + it('syncs completed auction teams into the match document', async () => { + const matchId = new mongoose.Types.ObjectId(); + const blueCaptainId = new mongoose.Types.ObjectId(); + const redCaptainId = new mongoose.Types.ObjectId(); + const blueMemberId = new mongoose.Types.ObjectId(); + const redMemberId = new mongoose.Types.ObjectId(); + + const auction = { + matchId, + phase: 'sold', + currentIndex: 1, + order: [{ userId: blueMemberId }, { userId: redMemberId }], + teams: [ + { + side: 'blue', + captainUserId: blueCaptainId, + points: 970, + members: [ + { + userId: blueMemberId, + assignedPosition: 'ADC', + cost: 30, + }, + ], + }, + { + side: 'red', + captainUserId: redCaptainId, + points: 940, + members: [ + { + userId: redMemberId, + assignedPosition: 'JGL', + cost: 60, + }, + ], + }, + ], + save: jest.fn().mockResolvedValue(undefined), + }; + const match = { + participants: [ + { + userId: blueCaptainId, + preferredPositions: [{ position: 'TOP', priority: 1 }], + }, + { + userId: redCaptainId, + preferredPositions: [{ position: 'MID', priority: 1 }], + }, + { + userId: blueMemberId, + preferredPositions: [{ position: 'ADC', priority: 1 }], + }, + { + userId: redMemberId, + preferredPositions: [{ position: 'JGL', priority: 1 }], + }, + ], + status: 'team-built', + teams: [], + save: jest.fn().mockResolvedValue(undefined), + }; + const { service } = createService({ + auction: { + findOne: jest.fn().mockResolvedValue(auction), + }, + match: { + findById: jest.fn().mockResolvedValue(match), + }, + }); + + await service.next(matchId); + + expect(auction.phase).toBe('complete'); + expect(auction.completedAt).toBeInstanceOf(Date); + expect(auction.save).toHaveBeenCalledTimes(1); + expect(match.save).toHaveBeenCalledTimes(1); + expect(match.teams).toEqual([ + { + side: 'blue', + name: '블루팀', + captainUserId: blueCaptainId, + members: [ + { + userId: blueCaptainId, + assignedPosition: 'TOP', + cost: 0, + }, + { + userId: blueMemberId, + assignedPosition: 'ADC', + cost: 30, + }, + ], + }, + { + side: 'red', + name: '레드팀', + captainUserId: redCaptainId, + members: [ + { + userId: redCaptainId, + assignedPosition: 'MID', + cost: 0, + }, + { + userId: redMemberId, + assignedPosition: 'JGL', + cost: 60, + }, + ], + }, + ]); + }); + + it('clears match teams when resetting an auction', async () => { + const matchId = new mongoose.Types.ObjectId(); + const communityId = new mongoose.Types.ObjectId(); + const session = { + startTransaction: jest.fn(), + commitTransaction: jest.fn().mockResolvedValue(undefined), + abortTransaction: jest.fn().mockResolvedValue(undefined), + endSession: jest.fn().mockResolvedValue(undefined), + }; + const auction = { + deleteOne: jest.fn().mockResolvedValue(undefined), + }; + const match = { + communityId, + status: 'team-built', + teams: [ + { + side: 'blue', + name: '블루팀', + members: [], + }, + ], + save: jest.fn().mockResolvedValue(undefined), + }; + const auctionFindOneQuery = { + session: jest.fn().mockResolvedValue(auction), + }; + const matchFindByIdQuery = { + session: jest.fn().mockResolvedValue(match), + }; + const { service, connectionService } = createService({ + auction: { + findOne: jest.fn().mockReturnValue(auctionFindOneQuery), + }, + match: { + findById: jest.fn().mockReturnValue(matchFindByIdQuery), + }, + }); + connectionService.createSession.mockResolvedValue(session); + + await service.reset({ matchId, communityId }); + + expect(match.status).toBe('recruiting'); + expect(match.teams).toEqual([]); + expect(match.save).toHaveBeenCalledWith({ session }); + expect(session.commitTransaction).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/src/modules/auction/auction.service.ts b/apps/api/src/modules/auction/auction.service.ts new file mode 100644 index 00000000..b940e7b9 --- /dev/null +++ b/apps/api/src/modules/auction/auction.service.ts @@ -0,0 +1,436 @@ +import { + BadRequestException, + Injectable, + InternalServerErrorException, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + AuctionDocument, + AuctionPlayerSnapshot, + AuctionTeam, + MatchTeamMember, + Position, + TeamSide, +} from '../global/database/schema'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import { TournamentCodeService } from '../tournament-code/tournament-code.service'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; + +const AUCTION_MAX_TEAM_SIZE = 5; + +interface StartAuctionParams { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + captains: { side: TeamSide; userId: mongoose.Types.ObjectId }[]; + initialPoints: number; + maxTimerSeconds: number; +} + +interface PlaceBidParams { + matchId: mongoose.Types.ObjectId; + side: TeamSide; + amount: number; + bidderUserId?: mongoose.Types.ObjectId; +} + +interface MarkSoldParams { + matchId: mongoose.Types.ObjectId; + assignedPosition?: Position; +} + +@Injectable() +export class AuctionService { + constructor( + private readonly connectionService: ConnectionService, + private readonly enrichmentService: RiotAccountEnrichmentService, + private readonly tournamentCodeService: TournamentCodeService, + private readonly tournamentResultService: TournamentResultService, + ) {} + + public async start(params: StartAuctionParams): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const UserModel = await this.connectionService.getModel('user'); + const AuctionModel = await this.connectionService.getModel('auction'); + const CommunityModel = await this.connectionService.getModel('community'); + + const match = await MatchModel.findById(params.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + + const existing = await AuctionModel.findOne({ matchId: params.matchId }); + if (existing) { + throw new BadRequestException('Auction already exists for this match.'); + } + + 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 + .filter((p) => !captainUserIds.some((cid) => cid.equals(p.userId))) + .map((p) => p.userId), + }, + }); + const community = await CommunityModel.findById(match.communityId) + .select({ riotPlatform: 1, riotRegion: 1 }) + .lean() + .exec(); + const platform = community?.riotPlatform ?? 'kr'; + const region = community?.riotRegion ?? 'asia'; + + const enrichTargets = basePlayerUsers + .map((user) => ({ + userId: user._id, + puuid: (user.riotAccounts.find((account) => account.isPrimary) ?? user.riotAccounts[0]) + ?.puuid, + })) + .filter((target): target is { userId: mongoose.Types.ObjectId; puuid: string } => + typeof target.puuid === 'string' && target.puuid.length > 0, + ); + + await runWithConcurrency(enrichTargets, 3, async (target) => { + await this.enrichmentService.enrichRiotAccount({ + userId: target.userId, + puuid: target.puuid, + options: { + force: false, + platform, + region, + }, + }); + }); + + const playerUsers = await UserModel.find({ + _id: { $in: basePlayerUsers.map((user) => user._id) }, + }); + const userById = new Map(playerUsers.map((u) => [u._id.toString(), u])); + + const nonCaptainPuuids = new Set(); + const order: AuctionPlayerSnapshot[] = []; + for (const participant of match.participants) { + if (captainUserIds.some((cid) => cid.equals(participant.userId))) { + continue; + } + const user = userById.get(participant.userId.toString()); + if (!user) continue; + const primary = + user.riotAccounts.find((a) => a.isPrimary) ?? user.riotAccounts[0]; + if (!primary) { + throw new BadRequestException( + `Participant ${user._id.toString()} has no Riot account.`, + ); + } + if (nonCaptainPuuids.has(primary.puuid)) continue; + nonCaptainPuuids.add(primary.puuid); + order.push({ + userId: user._id, + puuid: primary.puuid, + gameName: primary.gameName, + tagLine: primary.tagLine, + profileIconId: primary.profileIconId, + preferredPositions: participant.preferredPositions, + tiers: primary.tiers, + masteries: primary.championMasteries, + recentStatsSummary: primary.recentStatsSummary, + }); + } + + const auction = await AuctionModel.create({ + matchId: params.matchId, + phase: 'presenting', + teams: params.captains.map((c) => ({ + side: c.side, + captainUserId: c.userId, + points: params.initialPoints, + members: [], + })), + order, + currentIndex: 0, + bids: [], + currentBid: 0, + maxTimerSeconds: params.maxTimerSeconds, + initialPoints: params.initialPoints, + startedAt: new Date(), + }); + + match.status = 'team-built'; + match.teamBuiltAt = match.teamBuiltAt ?? new Date(); + await match.save(); + await this.tournamentCodeService.reserveForMatch(match); + await this.tournamentResultService.scheduleInitialPoll(match); + + return auction; + } + + public async getByMatchId( + matchId: mongoose.Types.ObjectId, + ): Promise { + const AuctionModel = await this.connectionService.getModel('auction'); + const auction = await AuctionModel.findOne({ matchId }); + if (!auction) throw new NotFoundException('Auction not found.'); + return auction; + } + + public async openBidding( + matchId: mongoose.Types.ObjectId, + ): Promise { + const auction = await this.getByMatchId(matchId); + if (auction.phase !== 'presenting') { + throw new BadRequestException('Auction is not in presenting phase.'); + } + auction.phase = 'bidding'; + auction.currentBid = 0; + auction.currentBidder = undefined; + auction.currentDeadline = this.createDeadline(auction.maxTimerSeconds); + await auction.save(); + return auction; + } + + public async placeBid(params: PlaceBidParams): Promise { + const auction = await this.getByMatchId(params.matchId); + 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.'); + if (params.amount <= auction.currentBid) { + throw new BadRequestException('Bid must exceed current bid.'); + } + if (params.amount > team.points) { + throw new BadRequestException('Bid exceeds team points.'); + } + this.assertTeamHasSlot(team); + // 임시 운영용: 클라이언트에서 선택한 팀장 모드를 신뢰하고 실제 로그인 사용자 검증은 건너뛴다. + + auction.currentBid = params.amount; + auction.currentBidder = params.side; + auction.currentDeadline = this.createDeadline( + this.resolveBidExtensionSeconds(auction), + ); + auction.bids.push({ + side: params.side, + amount: params.amount, + bidderUserId: team.captainUserId, + timestamp: new Date(), + }); + await auction.save(); + return auction; + } + + public async markSold(params: MarkSoldParams): Promise { + const auction = await this.getByMatchId(params.matchId); + if (auction.phase !== 'bidding') { + throw new BadRequestException('Auction is not in bidding phase.'); + } + if (!auction.currentBidder || auction.currentBid <= 0) { + throw new BadRequestException('No bid to mark sold.'); + } + const team = auction.teams.find((t) => t.side === auction.currentBidder); + if (!team) throw new BadRequestException('Winning team not found.'); + this.assertTeamHasSlot(team); + + const current = auction.order[auction.currentIndex]; + if (!current) throw new BadRequestException('No current player.'); + + const preferredPrimary = current.preferredPositions[0]?.position; + team.members.push({ + userId: current.userId, + assignedPosition: params.assignedPosition ?? preferredPrimary ?? 'MID', + cost: auction.currentBid, + }); + team.points -= auction.currentBid; + auction.phase = 'sold'; + auction.currentDeadline = undefined; + await auction.save(); + return auction; + } + + public async next( + matchId: mongoose.Types.ObjectId, + ): Promise { + const auction = await this.getByMatchId(matchId); + if (auction.phase !== 'sold' && auction.phase !== 'presenting') { + throw new BadRequestException('Cannot advance from current phase.'); + } + const nextIndex = auction.currentIndex + 1; + if (nextIndex >= auction.order.length) { + auction.phase = 'complete'; + auction.completedAt = new Date(); + } else { + auction.currentIndex = nextIndex; + auction.phase = 'presenting'; + auction.currentBid = 0; + auction.currentBidder = undefined; + } + auction.currentDeadline = undefined; + await auction.save(); + if (auction.phase === 'complete') { + await this.syncMatchTeamsFromAuction(auction); + } + return auction; + } + + public async reset(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }): Promise { + const AuctionModel = await this.connectionService.getModel('auction'); + const MatchModel = await this.connectionService.getModel('match'); + + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + try { + session.startTransaction(); + const auction = await AuctionModel.findOne({ + matchId: params.matchId, + }).session(session); + if (!auction) throw new NotFoundException('Auction not found.'); + + const match = await MatchModel.findById(params.matchId).session(session); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Community mismatch.'); + } + + await auction.deleteOne({ session }); + if (match.status === 'team-built') { + await this.tournamentCodeService.releaseFromMatch(match); + match.status = 'recruiting'; + match.teams = []; + match.tournamentCodeIds = []; + match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; + await match.save({ session }); + } + await session.commitTransaction(); + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + private createDeadline(secondsFromNow: number): Date { + return new Date(Date.now() + secondsFromNow * 1000); + } + + private resolveBidExtensionSeconds(auction: AuctionDocument): number { + if (!auction.currentDeadline) { + return auction.maxTimerSeconds; + } + + const remainingSeconds = Math.ceil( + (auction.currentDeadline.getTime() - Date.now()) / 1000, + ); + return Math.max(5, remainingSeconds); + } + + private assertTeamHasSlot(team: AuctionTeam): void { + if (this.countTeamMembersIncludingCaptain(team) >= AUCTION_MAX_TEAM_SIZE) { + throw new BadRequestException('Team already has maximum members.'); + } + } + + private countTeamMembersIncludingCaptain(team: AuctionTeam): number { + const userIds = new Set([team.captainUserId.toString()]); + for (const member of team.members) { + userIds.add(member.userId.toString()); + } + return userIds.size; + } + + private async syncMatchTeamsFromAuction( + auction: AuctionDocument, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(auction.matchId); + if (!match) throw new NotFoundException('Match not found.'); + + const participantByUserId = new Map( + match.participants.map((participant) => [ + participant.userId.toString(), + participant, + ]), + ); + + match.teams = auction.teams.map((team) => { + const captain = participantByUserId.get(team.captainUserId.toString()); + const members: MatchTeamMember[] = [ + { + userId: team.captainUserId, + assignedPosition: captain?.preferredPositions[0]?.position ?? 'MID', + cost: 0, + }, + ...team.members + .filter((member) => !member.userId.equals(team.captainUserId)) + .map((member) => ({ + userId: member.userId, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + ]; + + return { + side: team.side, + name: this.resolveTeamName(team.side), + captainUserId: team.captainUserId, + members, + }; + }); + match.status = 'team-built'; + match.teamBuiltAt = match.teamBuiltAt ?? new Date(); + await match.save(); + await this.tournamentCodeService.reserveForMatch(match); + await this.tournamentResultService.scheduleInitialPoll(match); + } + + private resolveTeamName(side: TeamSide): string { + return side === 'blue' ? '블루팀' : '레드팀'; + } +} + +async function runWithConcurrency( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + if (items.length === 0) return; + + const queue = [...items]; + const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => { + while (queue.length > 0) { + const item = queue.shift(); + if (item === undefined) return; + await worker(item); + } + }); + + await Promise.allSettled(runners); +} diff --git a/apps/api/src/modules/auction/dto/auction.dto.ts b/apps/api/src/modules/auction/dto/auction.dto.ts new file mode 100644 index 00000000..9fee333d --- /dev/null +++ b/apps/api/src/modules/auction/dto/auction.dto.ts @@ -0,0 +1,60 @@ +import { Type } from 'class-transformer'; +import { + ArrayMaxSize, + ArrayMinSize, + IsArray, + IsEnum, + IsInt, + IsMongoId, + IsOptional, + Min, + ValidateNested, +} from 'class-validator'; +import { TEAM_SIDES } from '../../global/database/schema'; +import type { TeamSide } from '../../global/database/schema'; + +class CaptainAssignmentDto { + @IsEnum(TEAM_SIDES) + side!: TeamSide; + + @IsMongoId() + userId!: string; +} + +export class StartAuctionDto { + @IsArray() + @ArrayMinSize(2) + @ArrayMaxSize(2) + @ValidateNested({ each: true }) + @Type(() => CaptainAssignmentDto) + captains!: CaptainAssignmentDto[]; + + @IsOptional() + @IsInt() + @Min(1) + initialPoints?: number; + + @IsOptional() + @IsInt() + @Min(5) + maxTimerSeconds?: number; +} + +export class PlaceBidDto { + @IsEnum(TEAM_SIDES) + side!: TeamSide; + + @IsInt() + @Min(1) + amount!: number; + + @IsOptional() + @IsMongoId() + bidderUserId?: string; +} + +export class SoldDto { + @IsOptional() + @IsEnum(['TOP', 'JGL', 'MID', 'ADC', 'SUP']) + assignedPosition?: 'TOP' | 'JGL' | 'MID' | 'ADC' | 'SUP'; +} diff --git a/apps/api/src/modules/auth/allow-public-access.decorator.ts b/apps/api/src/modules/auth/allow-public-access.decorator.ts new file mode 100644 index 00000000..230f3604 --- /dev/null +++ b/apps/api/src/modules/auth/allow-public-access.decorator.ts @@ -0,0 +1,7 @@ +import { SetMetadata } from '@nestjs/common'; + +export const METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED = + 'lolympus:allow_public_access'; + +export const AllowPublicAccess = () => + SetMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, true); diff --git a/apps/api/src/modules/auth/auth-request.ts b/apps/api/src/modules/auth/auth-request.ts new file mode 100644 index 00000000..678677d9 --- /dev/null +++ b/apps/api/src/modules/auth/auth-request.ts @@ -0,0 +1,16 @@ +import type { JWTHeaderParameters, JWTPayload } from 'jose'; +import type { + IdentityDocument, + UserDocument, +} from '../global/database/schema'; +import type { IdentityProviderName } from './jwt.service'; + +declare module 'express' { + interface Request { + tokenPayload?: JWTPayload; + tokenHeader?: JWTHeaderParameters; + identityProvider?: IdentityProviderName; + identity?: IdentityDocument; + user?: UserDocument; + } +} diff --git a/apps/api/src/modules/auth/auth.middleware.ts b/apps/api/src/modules/auth/auth.middleware.ts new file mode 100644 index 00000000..ff8f5e58 --- /dev/null +++ b/apps/api/src/modules/auth/auth.middleware.ts @@ -0,0 +1,18 @@ +import { Injectable, NestMiddleware } from '@nestjs/common'; +import type { NextFunction, Request, Response } from 'express'; +import { AuthService } from './auth.service'; +import './auth-request'; + +@Injectable() +export class AuthMiddleware implements NestMiddleware { + constructor(private readonly authService: AuthService) {} + + public async use(req: Request, _res: Response, next: NextFunction) { + const fallback = await this.authService.resolveDevFallbackFromRequest(req); + if (fallback) { + req.user = fallback.user; + req.identity = fallback.identity; + } + next(); + } +} diff --git a/apps/api/src/modules/auth/auth.module.ts b/apps/api/src/modules/auth/auth.module.ts new file mode 100644 index 00000000..58d7ff02 --- /dev/null +++ b/apps/api/src/modules/auth/auth.module.ts @@ -0,0 +1,33 @@ +import { Global, Module } from '@nestjs/common'; +import { APP_GUARD } from '@nestjs/core'; +import { AuthService } from './auth.service'; +import { IdentityResolverGuard } from './identity-resolver.guard'; +import { IdentityService } from './identity.service'; +import { JwtAuthGuard } from './jwt.guard'; +import { JwtService } from './jwt.service'; +import { RolesGuard } from './roles.guard'; +import { UserResolverGuard } from './user-resolver.guard'; + +@Global() +@Module({ + providers: [ + AuthService, + JwtService, + IdentityService, + JwtAuthGuard, + IdentityResolverGuard, + UserResolverGuard, + RolesGuard, + { provide: APP_GUARD, useClass: JwtAuthGuard }, + { provide: APP_GUARD, useClass: IdentityResolverGuard }, + { provide: APP_GUARD, useClass: UserResolverGuard }, + ], + exports: [ + AuthService, + JwtService, + IdentityService, + UserResolverGuard, + RolesGuard, + ], +}) +export class AuthModule {} diff --git a/apps/api/src/modules/auth/auth.service.ts b/apps/api/src/modules/auth/auth.service.ts new file mode 100644 index 00000000..373aa71f --- /dev/null +++ b/apps/api/src/modules/auth/auth.service.ts @@ -0,0 +1,62 @@ +import { Injectable } from '@nestjs/common'; +import type { Request } from 'express'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + IdentityDocument, + UserDocument, +} from '../global/database/schema'; +import { SecretService } from '../global/secret/secret.service'; +import './auth-request'; + +interface DevFallbackResult { + user: UserDocument; + identity?: IdentityDocument; +} + +@Injectable() +export class AuthService { + constructor( + private readonly connectionService: ConnectionService, + private readonly secretService: SecretService, + ) {} + + public async resolveDevFallbackFromRequest( + req: Request, + ): Promise { + if (!(await this.isDevHeaderEnabled())) return null; + const header = req.headers['x-auth-user-id']; + const userId = Array.isArray(header) ? header[0] : header; + return this.resolveDevUserById(userId); + } + + public async resolveDevUserById( + userId: unknown, + ): Promise { + if (!(await this.isDevHeaderEnabled())) return null; + if (typeof userId !== 'string' || !mongoose.isValidObjectId(userId)) { + return null; + } + + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findById(userId).exec(); + if (!user) return null; + + const result: DevFallbackResult = { user }; + if (user.identityId) { + const IdentityModel = await this.connectionService.getModel('identity'); + const identity = await IdentityModel.findById(user.identityId).exec(); + if (identity) result.identity = identity; + } + return result; + } + + private async isDevHeaderEnabled(): Promise { + if (process.env.NODE_ENV === 'prod') return false; + const value = await this.secretService.get( + 'AUTH_DEV_HEADER_ENABLED', + process.env.AUTH_DEV_HEADER_ENABLED ?? 'false', + ); + return value === 'true'; + } +} diff --git a/apps/api/src/modules/auth/current-identity.decorator.ts b/apps/api/src/modules/auth/current-identity.decorator.ts new file mode 100644 index 00000000..e3d0829b --- /dev/null +++ b/apps/api/src/modules/auth/current-identity.decorator.ts @@ -0,0 +1,11 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import type { Request } from 'express'; +import { IdentityDocument } from '../global/database/schema'; +import './auth-request'; + +export const CurrentIdentity = createParamDecorator( + (_data: unknown, ctx: ExecutionContext): IdentityDocument | undefined => { + const req = ctx.switchToHttp().getRequest(); + return req.identity; + }, +); diff --git a/apps/api/src/modules/auth/current-user.decorator.ts b/apps/api/src/modules/auth/current-user.decorator.ts new file mode 100644 index 00000000..faac9965 --- /dev/null +++ b/apps/api/src/modules/auth/current-user.decorator.ts @@ -0,0 +1,11 @@ +import { createParamDecorator, ExecutionContext } from '@nestjs/common'; +import type { Request } from 'express'; +import { UserDocument } from '../global/database/schema'; +import './auth-request'; + +export const CurrentUser = createParamDecorator( + (_data: unknown, ctx: ExecutionContext): UserDocument | undefined => { + const req = ctx.switchToHttp().getRequest(); + return req.user; + }, +); diff --git a/apps/api/src/modules/auth/identity-resolver.guard.ts b/apps/api/src/modules/auth/identity-resolver.guard.ts new file mode 100644 index 00000000..2e343ba5 --- /dev/null +++ b/apps/api/src/modules/auth/identity-resolver.guard.ts @@ -0,0 +1,38 @@ +import { + CanActivate, + ExecutionContext, + Injectable, + UnauthorizedException, +} from '@nestjs/common'; +import type { Request } from 'express'; +import { IdentityService } from './identity.service'; +import './auth-request'; + +@Injectable() +export class IdentityResolverGuard implements CanActivate { + constructor(private readonly identityService: IdentityService) {} + + public async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + if (request.identity || !request.tokenPayload) return true; + + const entraOid = stringClaim(request.tokenPayload.oid); + if (!entraOid) { + throw new UnauthorizedException('Token is missing oid claim.'); + } + + request.identity = await this.identityService.findOrCreateByOid({ + entraOid, + tenantId: stringClaim(request.tokenPayload.tid), + email: + stringClaim(request.tokenPayload.preferred_username) ?? + stringClaim(request.tokenPayload.email), + displayName: stringClaim(request.tokenPayload.name), + }); + return true; + } +} + +function stringClaim(value: unknown): string | undefined { + return typeof value === 'string' && value.length > 0 ? value : undefined; +} diff --git a/apps/api/src/modules/auth/identity.service.ts b/apps/api/src/modules/auth/identity.service.ts new file mode 100644 index 00000000..2504f5a1 --- /dev/null +++ b/apps/api/src/modules/auth/identity.service.ts @@ -0,0 +1,39 @@ +import { Injectable, InternalServerErrorException } from '@nestjs/common'; +import { ConnectionService } from '../global/database/connection.service'; +import { IdentityDocument } from '../global/database/schema'; + +interface IdentityInput { + entraOid: string; + tenantId?: string; + email?: string; + displayName?: string; +} + +@Injectable() +export class IdentityService { + constructor(private readonly connectionService: ConnectionService) {} + + public async findOrCreateByOid( + input: IdentityInput, + ): Promise { + const IdentityModel = await this.connectionService.getModel('identity'); + const identity = await IdentityModel.findOneAndUpdate( + { entraOid: input.entraOid }, + { + $set: { + tenantId: input.tenantId, + email: input.email, + displayName: input.displayName, + lastSignInAt: new Date(), + }, + $setOnInsert: { entraOid: input.entraOid }, + }, + { upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }, + ).exec(); + + if (!identity) { + throw new InternalServerErrorException('Failed to resolve identity.'); + } + return identity; + } +} diff --git a/apps/api/src/modules/auth/jwt.guard.ts b/apps/api/src/modules/auth/jwt.guard.ts new file mode 100644 index 00000000..e3d405a1 --- /dev/null +++ b/apps/api/src/modules/auth/jwt.guard.ts @@ -0,0 +1,91 @@ +import { + CanActivate, + ExecutionContext, + Injectable, + UnauthorizedException, +} from '@nestjs/common'; +import { Reflector } from '@nestjs/core'; +import { decodeJwt } from 'jose'; +import type { Request } from 'express'; +import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from './allow-public-access.decorator'; +import { AuthService } from './auth.service'; +import { IdentityProviderName, JwtService } from './jwt.service'; +import './auth-request'; + +@Injectable() +export class JwtAuthGuard implements CanActivate { + constructor( + private readonly reflector: Reflector, + private readonly jwtService: JwtService, + private readonly authService: AuthService, + ) {} + + public async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const isPublicAccessAllowed = this.reflector.getAllAndOverride( + METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, + [context.getHandler(), context.getClass()], + ); + const authz = request.headers?.authorization; + const authzHeader = Array.isArray(authz) ? authz[0] : authz; + + if (!authzHeader) { + const fallback = + await this.authService.resolveDevFallbackFromRequest(request); + if (fallback) { + request.user = fallback.user; + request.identity = fallback.identity; + return true; + } + if (isPublicAccessAllowed) return true; + throw new UnauthorizedException( + 'Missing or invalid Authorization header', + ); + } + + if (!authzHeader.startsWith('Bearer ')) { + throw new UnauthorizedException( + 'Missing or invalid Authorization header', + ); + } + + const token = authzHeader.slice('Bearer '.length).trim(); + if (!token) { + throw new UnauthorizedException('Empty bearer token'); + } + + const identityProvider = this.pickIdPFromToken(token); + + try { + const verifyResult = await this.jwtService.verify( + token, + identityProvider, + ); + request.tokenPayload = verifyResult.payload; + request.tokenHeader = verifyResult.protectedHeader; + request.identityProvider = identityProvider; + return true; + } catch (err) { + const message = + err instanceof Error ? err.message : 'JWT verification failed'; + throw new UnauthorizedException(message); + } + } + + private pickIdPFromToken(token: string): IdentityProviderName { + try { + const { iss } = decodeJwt(token) as { iss?: string }; + if (!iss) { + throw new Error('Token has no issuer (iss) claim'); + } + const lower = iss.toLowerCase(); + if (lower.includes('login.microsoftonline.com')) { + return 'MICROSOFT_ENTRAID'; + } + throw new Error(`Unknown issuer: ${iss}`); + } catch (err) { + const message = err instanceof Error ? err.message : 'Unable to decode token'; + throw new UnauthorizedException(message); + } + } +} diff --git a/apps/api/src/modules/auth/jwt.service.ts b/apps/api/src/modules/auth/jwt.service.ts new file mode 100644 index 00000000..166ca211 --- /dev/null +++ b/apps/api/src/modules/auth/jwt.service.ts @@ -0,0 +1,100 @@ +import { Injectable } from '@nestjs/common'; +import { + createRemoteJWKSet, + jwtVerify, + JWTPayload, + JWTVerifyGetKey, + JWTVerifyResult, +} from 'jose'; +import { SecretService } from '../global/secret/secret.service'; + +export type IdentityProviderName = 'MICROSOFT_ENTRAID'; + +interface EntraConfig { + tenantId: string; + audience: string; + issuer: string; + allowedAlgs: string[]; + jwks: JWTVerifyGetKey; +} + +@Injectable() +export class JwtService { + private entraConfig?: EntraConfig; + private readonly clockTolerance = Number( + process.env.JWT_CLOCK_TOLERANCE || 5, + ); + + constructor(private readonly secretService: SecretService) {} + + public async verify( + token: string, + identityProvider: IdentityProviderName, + ): Promise> { + if (!token) { + throw new Error('Empty token'); + } + + if (identityProvider !== 'MICROSOFT_ENTRAID') { + throw new Error(`Identity provider not configured: ${identityProvider}`); + } + + const provider = await this.getEntraConfig(); + const result = await jwtVerify(token, provider.jwks, { + issuer: provider.issuer, + audience: provider.audience, + algorithms: provider.allowedAlgs, + clockTolerance: this.clockTolerance, + }); + + const { payload, protectedHeader } = result; + if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) { + throw new Error(`Unexpected alg: ${protectedHeader.alg}`); + } + if (payload.ver && payload.ver !== '2.0') { + throw new Error(`Unsupported Entra token version: ${payload.ver}`); + } + if (payload.tid && payload.tid !== provider.tenantId) { + throw new Error(`Unexpected tenant: ${payload.tid}`); + } + + return result; + } + + private async getEntraConfig(): Promise { + if (this.entraConfig) return this.entraConfig; + + await this.secretService.ready(); + const [audience, tenantId, allowedAlgsRaw] = await Promise.all([ + this.secretService.get('JWT_CLAIM_AUDIENCE'), + this.secretService.get('MICROSOFT_ENTRAID_TENANT_ID'), + this.secretService.get('MICROSOFT_ENTRAID_ALLOWED_ALGS', 'RS256'), + ]); + + const allowedAlgs = allowedAlgsRaw + .split(',') + .map((alg) => alg.trim()) + .filter(Boolean); + if (allowedAlgs.length === 0) { + allowedAlgs.push('RS256'); + } + + const issuer = `https://login.microsoftonline.com/${tenantId}/v2.0`; + const jwks = createRemoteJWKSet( + new URL('https://login.microsoftonline.com/common/discovery/v2.0/keys'), + { + cooldownDuration: 30_000, + timeoutDuration: 10_000, + }, + ); + + this.entraConfig = { + tenantId, + audience, + issuer, + allowedAlgs, + jwks, + }; + return this.entraConfig; + } +} diff --git a/apps/api/src/modules/auth/permissions.ts b/apps/api/src/modules/auth/permissions.ts new file mode 100644 index 00000000..7e7f7800 --- /dev/null +++ b/apps/api/src/modules/auth/permissions.ts @@ -0,0 +1,35 @@ +import { CommunityRole } from '../global/database/schema'; + +export type Permission = + | 'community:edit' + | 'community:delete' + | 'community:transfer' + | 'user:role:manage' + | 'match:create' + | 'match:edit' + | 'match:delete' + | 'auction:manage'; + +type PermissionSet = readonly Permission[] | readonly ['*']; + +export const ROLE_PERMISSIONS: Record = { + owner: ['*'] as const, + admin: [ + 'community:edit', + 'user:role:manage', + 'match:create', + 'match:edit', + 'match:delete', + 'auction:manage', + ] as const, + member: [] as const, +}; + +export function roleHasPermission( + role: CommunityRole, + permission: Permission, +): boolean { + const perms = ROLE_PERMISSIONS[role]; + if (perms.length === 1 && perms[0] === '*') return true; + return (perms as readonly Permission[]).includes(permission); +} diff --git a/apps/api/src/modules/auth/roles.decorator.ts b/apps/api/src/modules/auth/roles.decorator.ts new file mode 100644 index 00000000..819cbb3a --- /dev/null +++ b/apps/api/src/modules/auth/roles.decorator.ts @@ -0,0 +1,7 @@ +import { SetMetadata } from '@nestjs/common'; +import { CommunityRole } from '../global/database/schema'; + +export const ROLES_KEY = 'lolympus:roles'; + +export const Roles = (...roles: CommunityRole[]) => + SetMetadata(ROLES_KEY, roles); diff --git a/apps/api/src/modules/auth/roles.guard.ts b/apps/api/src/modules/auth/roles.guard.ts new file mode 100644 index 00000000..6e76e87d --- /dev/null +++ b/apps/api/src/modules/auth/roles.guard.ts @@ -0,0 +1,36 @@ +import { + CanActivate, + ExecutionContext, + ForbiddenException, + Injectable, + UnauthorizedException, +} from '@nestjs/common'; +import { Reflector } from '@nestjs/core'; +import type { Request } from 'express'; +import { CommunityRole, UserDocument } from '../global/database/schema'; +import { ROLES_KEY } from './roles.decorator'; +import './auth-request'; + +@Injectable() +export class RolesGuard implements CanActivate { + constructor(private readonly reflector: Reflector) {} + + public canActivate(context: ExecutionContext): boolean { + const requiredRoles = this.reflector.getAllAndOverride( + ROLES_KEY, + [context.getHandler(), context.getClass()], + ); + if (!requiredRoles || requiredRoles.length === 0) return true; + + const req = context.switchToHttp().getRequest(); + const user = req.user as UserDocument | undefined; + if (!user && req.identity) { + throw new ForbiddenException('No membership in this community.'); + } + if (!user) throw new UnauthorizedException('Authentication required.'); + if (!requiredRoles.includes(user.role)) { + throw new ForbiddenException('Insufficient role.'); + } + return true; + } +} diff --git a/apps/api/src/modules/auth/user-resolver.guard.spec.ts b/apps/api/src/modules/auth/user-resolver.guard.spec.ts new file mode 100644 index 00000000..559a054f --- /dev/null +++ b/apps/api/src/modules/auth/user-resolver.guard.spec.ts @@ -0,0 +1,55 @@ +import { ExecutionContext } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { IdentityDocument, UserDocument } from '../global/database/schema'; +import { UserResolverGuard } from './user-resolver.guard'; +import './auth-request'; + +function createContext(request: Record): ExecutionContext { + return { + switchToHttp: () => ({ + getRequest: () => request, + }), + } as ExecutionContext; +} + +describe('UserResolverGuard', () => { + it('resolves the community membership before role guards run', async () => { + const communityId = new mongoose.Types.ObjectId(); + const identityId = new mongoose.Types.ObjectId(); + const user = { _id: new mongoose.Types.ObjectId() } as UserDocument; + const findOne = jest.fn().mockReturnValue({ + exec: jest.fn().mockResolvedValue(user), + }); + const connectionService = { + getModel: jest.fn().mockResolvedValue({ findOne }), + } as unknown as ConnectionService; + const request = { + params: { communityId: communityId.toString() }, + identity: { _id: identityId } as IdentityDocument, + }; + const guard = new UserResolverGuard(connectionService); + + await expect(guard.canActivate(createContext(request))).resolves.toBe(true); + + expect(findOne).toHaveBeenCalledWith({ + communityId, + identityId, + }); + expect(request.user).toBe(user); + }); + + it('skips lookup when there is no resolved identity', async () => { + const connectionService = { + getModel: jest.fn(), + } as unknown as ConnectionService; + const request = { + params: { communityId: new mongoose.Types.ObjectId().toString() }, + }; + const guard = new UserResolverGuard(connectionService); + + await expect(guard.canActivate(createContext(request))).resolves.toBe(true); + + expect(connectionService.getModel).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/modules/auth/user-resolver.guard.ts b/apps/api/src/modules/auth/user-resolver.guard.ts new file mode 100644 index 00000000..56eac35a --- /dev/null +++ b/apps/api/src/modules/auth/user-resolver.guard.ts @@ -0,0 +1,33 @@ +import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; +import type { Request } from 'express'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import './auth-request'; + +@Injectable() +export class UserResolverGuard implements CanActivate { + constructor(private readonly connectionService: ConnectionService) {} + + public async canActivate(context: ExecutionContext): Promise { + const request = context.switchToHttp().getRequest(); + const communityId = request.params?.communityId; + + if ( + request.user || + !request.identity || + typeof communityId !== 'string' || + !mongoose.isValidObjectId(communityId) + ) { + return true; + } + + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findOne({ + communityId: new mongoose.Types.ObjectId(communityId), + identityId: request.identity._id, + }).exec(); + + if (user) request.user = user; + return true; + } +} 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/community-stats/community-stats-cache.service.ts b/apps/api/src/modules/community-stats/community-stats-cache.service.ts new file mode 100644 index 00000000..4d6abeb7 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -0,0 +1,59 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { GarnetService } from '../global/garnet/garnet.service'; + +const COMMUNITY_STATS_TTL_SECONDS = 60 * 60; +const COMMUNITY_STATS_DETAIL_TTL_SECONDS = 24 * 60 * 60; + +@Injectable() +export class CommunityStatsCacheService { + private readonly logger = new Logger(CommunityStatsCacheService.name); + + constructor(private readonly garnetService: GarnetService) {} + + public get(key: string): Promise { + return this.garnetService.getJson(key); + } + + public set( + key: string, + value: unknown, + ttlSeconds = COMMUNITY_STATS_TTL_SECONDS, + ): Promise { + return this.garnetService.setJson(key, value, ttlSeconds); + } + + public setDetail(key: string, value: unknown): Promise { + return this.set(key, value, COMMUNITY_STATS_DETAIL_TTL_SECONDS); + } + + public async invalidateCommunity(communityId: string): Promise { + const prefix = `riot:communitystats:`; + const match = `${prefix}*${communityId}*`; + const client = this.garnetService.raw(); + let cursor = '0'; + let deleted = 0; + + do { + const reply = (await client.sendCommand([ + 'SCAN', + cursor, + 'MATCH', + match, + 'COUNT', + '100', + ])) as [string, string[]]; + cursor = reply[0]; + const keys = reply[1] ?? []; + if (keys.length > 0) { + deleted += await client.del(keys); + } + } while (cursor !== '0'); + + if (deleted > 0) { + this.logger.debug( + `Invalidated ${deleted} community stats cache keys for ${communityId}.`, + ); + } + return deleted; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.controller.ts b/apps/api/src/modules/community-stats/community-stats.controller.ts new file mode 100644 index 00000000..e8d4ee69 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.controller.ts @@ -0,0 +1,115 @@ +import { Controller, Get, Param, Query } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; +import { CommunityStatsService } from './community-stats.service'; +import type { CommunityStatsFilters } from './community-stats.types'; + +@Controller('communities/:communityId') +export class CommunityStatsController { + constructor(private readonly communityStatsService: CommunityStatsService) {} + + @Get('internal-stats/matches') + @AllowPublicAccess() + public getMatches( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('seasonId') seasonId?: string, + @Query('from') from?: string, + @Query('to') to?: string, + @Query('championId') championId?: string, + @Query('cursor') cursor?: string, + @Query('limit') limit?: string, + ) { + return this.communityStatsService.getMatches({ + communityId, + filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), + }); + } + + @Get('internal-stats/leaderboard') + @AllowPublicAccess() + public getLeaderboard( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('seasonId') seasonId?: string, + @Query('from') from?: string, + @Query('to') to?: string, + @Query('championId') championId?: string, + ) { + return this.communityStatsService.getLeaderboard({ + communityId, + filters: this.toFilters({ seasonId, from, to, championId }), + }); + } + + @Get('internal-stats/team-insights') + @AllowPublicAccess() + public getTeamInsights( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('seasonId') seasonId?: string, + @Query('from') from?: string, + @Query('to') to?: string, + @Query('championId') championId?: string, + ) { + return this.communityStatsService.getTeamInsights({ + communityId, + filters: this.toFilters({ seasonId, from, to, championId }), + }); + } + + @Get('internal-stats/match/:matchId') + @AllowPublicAccess() + public getMatchDetail( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + return this.communityStatsService.getMatchDetail({ communityId, matchId }); + } + + @Get('users/:userId/internal-history') + @AllowPublicAccess() + public getUserInternalHistory( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Query('seasonId') seasonId?: string, + @Query('from') from?: string, + @Query('to') to?: string, + @Query('championId') championId?: string, + @Query('cursor') cursor?: string, + @Query('limit') limit?: string, + ) { + return this.communityStatsService.getUserInternalHistory({ + communityId, + userId, + filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), + }); + } + + private toFilters(params: { + seasonId?: string; + from?: string; + to?: string; + championId?: string; + cursor?: string; + limit?: string; + }): CommunityStatsFilters { + return { + seasonId: params.seasonId, + from: params.from, + to: params.to, + championId: this.toNumber(params.championId), + cursor: this.toNumber(params.cursor), + limit: this.toNumber(params.limit), + }; + } + + private toNumber(value: string | undefined): number | undefined { + if (!value) return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.module.ts b/apps/api/src/modules/community-stats/community-stats.module.ts new file mode 100644 index 00000000..c52af44c --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { CommunityStatsCacheService } from './community-stats-cache.service'; +import { CommunityStatsController } from './community-stats.controller'; +import { CommunityStatsService } from './community-stats.service'; + +@Module({ + controllers: [CommunityStatsController], + providers: [CommunityStatsService, CommunityStatsCacheService], + exports: [CommunityStatsService], +}) +export class CommunityStatsModule {} diff --git a/apps/api/src/modules/community-stats/community-stats.service.ts b/apps/api/src/modules/community-stats/community-stats.service.ts new file mode 100644 index 00000000..c9e76511 --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.service.ts @@ -0,0 +1,1072 @@ +import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + CommunityDocument, + MatchDocument, + MatchGameResultParticipant, + RiotLane, + TeamSide, +} from '../global/database/schema'; +import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; +import type { HistorySeasonDto, RecentMatchView } from '../match-history/match-history.types'; +import { CommunityStatsCacheService } from './community-stats-cache.service'; +import type { + CommunityStatsFilters, + InternalMatchCardView, + InternalMatchDetailResponse, + InternalMatchListResponse, + LeaderboardChampionStats, + LeaderboardResponse, + LeaderboardRow, + LeaderHighlight, + TeamInsightsResponse, + UserInternalHistoryResponse, +} from './community-stats.types'; + +const DEFAULT_LIST_LIMIT = 20; +const MAX_LIST_LIMIT = 50; +const MAX_MATCH_SCAN = 300; +const MIN_HIGHLIGHT_GAMES = 5; + +interface CommunityStatsContext { + community: CommunityDocument; + season: HistorySeasonDto; + from: Date | null; + to: Date | null; +} + +interface InternalRecord { + matchId: string; + title: string; + scheduledAt: Date; + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + userId: string; + summonerName: string; + profileIconId: number; + side: TeamSide; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + win: boolean; + cs: number; + csPerMin: number; + gold: number; + gpm: number; + damageDealtToChampions: number; + damageTaken: number; + damageShare: number; + killParticipation: number; + visionScore: number; + controlWardsBought: number; + wardsPlaced: number; + wardsKilled: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + rating: number; +} + +interface InternalGameDetail { + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + winnerSide: TeamSide; + teams: Array<{ + side: TeamSide; + win: boolean; + objectives: { baron: number; dragon: number; tower: number }; + participants: InternalRecord[]; + }>; +} + +interface BaseDataset { + season: HistorySeasonDto; + matches: InternalMatchCardView[]; + records: InternalRecord[]; + detailsByMatchId: Map; +} + +@Injectable() +export class CommunityStatsService { + constructor( + private readonly connectionService: ConnectionService, + private readonly cacheService: CommunityStatsCacheService, + ) {} + + public async getMatches(params: { + communityId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey('matches', params.communityId, params.filters); + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const limit = this.clampLimit(params.filters.limit, DEFAULT_LIST_LIMIT, MAX_LIST_LIMIT); + const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const filtered = params.filters.championId + ? dataset.matches.filter((match) => + dataset.records.some( + (record) => + record.matchId === match.matchId && + record.championId === params.filters.championId, + ), + ) + : dataset.matches; + const cursor = params.filters.cursor; + const page = filtered + .filter((match) => !cursor || new Date(match.scheduledAt).getTime() < cursor) + .slice(0, limit + 1); + const visible = page.slice(0, limit); + const response: InternalMatchListResponse = { + matches: visible, + nextCursor: + page.length > limit + ? new Date(visible[visible.length - 1]?.scheduledAt ?? 0).getTime() + : null, + season: dataset.season, + }; + await this.cacheService.set(key, response); + return response; + } + + public async getLeaderboard(params: { + communityId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey('leaderboard', params.communityId, params.filters); + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const records = this.applyChampionFilter(dataset.records, params.filters); + const rows = this.buildLeaderboardRows(records); + const response = { rows, season: dataset.season }; + await this.cacheService.set(key, response); + return response; + } + + public async getTeamInsights(params: { + communityId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey('teamInsights', params.communityId, params.filters); + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const records = this.applyChampionFilter(dataset.records, params.filters); + const rows = this.buildLeaderboardRows(records); + const gameDetails = [...dataset.detailsByMatchId.values()].flat(); + const blueGames = gameDetails.length; + const redGames = gameDetails.length; + const blueWins = gameDetails.filter((game) => game.winnerSide === 'blue').length; + const redWins = gameDetails.filter((game) => game.winnerSide === 'red').length; + + const response: TeamInsightsResponse = { + season: dataset.season, + sideWinRate: { + blue: this.percent(blueWins, blueGames), + red: this.percent(redWins, redGames), + bluePicks: blueGames, + redPicks: redGames, + }, + topKda: this.toHighlight( + rows + .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) + .sort((left, right) => right.kda - left.kda)[0], + 'kda', + ), + mostKills: this.toHighlight( + rows.sort((left, right) => right.totalKills - left.totalKills)[0], + 'totalKills', + ), + topTeamGpm: this.toSingleGameHighlight( + records.sort((left, right) => right.gpm - left.gpm)[0], + 'gpm', + ), + topKillParticipation: this.toHighlight( + rows + .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) + .sort( + (left, right) => + right.avgKillParticipation - left.avgKillParticipation, + )[0], + 'avgKillParticipation', + ), + bestFarm: this.toHighlight( + rows + .filter((row) => row.games >= MIN_HIGHLIGHT_GAMES) + .sort((left, right) => right.avgCsPerMin - left.avgCsPerMin)[0], + 'avgCsPerMin', + ), + minGamesThreshold: MIN_HIGHLIGHT_GAMES, + }; + await this.cacheService.set(key, response); + return response; + } + + public async getMatchDetail(params: { + communityId: mongoose.Types.ObjectId; + matchId: mongoose.Types.ObjectId; + }): Promise { + const key = `riot:communitystats:matchDetail:${params.communityId.toString()}:${params.matchId.toString()}`; + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const dataset = await this.buildBaseDataset(params.communityId, { + seasonId: 'all', + }); + const match = dataset.matches.find( + (item) => item.matchId === params.matchId.toString(), + ); + if (!match) throw new NotFoundException('Internal match not found.'); + const response: InternalMatchDetailResponse = { + match, + games: (dataset.detailsByMatchId.get(match.matchId) ?? []).map((game) => ({ + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + teams: game.teams.map((team) => ({ + side: team.side, + win: team.win, + objectives: team.objectives, + participants: team.participants.map((record) => ({ + userId: record.userId, + summonerName: record.summonerName, + side: record.side, + teamPosition: record.teamPosition, + championId: record.championId, + kills: record.kills, + deaths: record.deaths, + assists: record.assists, + cs: record.cs, + csPerMin: record.csPerMin, + gold: record.gold, + gpm: record.gpm, + damageDealtToChampions: record.damageDealtToChampions, + damageShare: record.damageShare, + killParticipation: record.killParticipation, + visionScore: record.visionScore, + items: record.items, + trinket: record.trinket, + summonerSpells: record.summonerSpells, + perks: record.perks, + win: record.win, + })), + })), + })), + }; + await this.cacheService.setDetail(key, response); + return response; + } + + public async getUserInternalHistory(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: CommunityStatsFilters; + }): Promise { + const key = this.cacheKey( + `userInternal:${params.userId.toString()}`, + params.communityId, + params.filters, + ); + const cached = await this.cacheService.get(key); + if (cached) return cached; + + const dataset = await this.buildBaseDataset(params.communityId, params.filters); + const allUserRecords = dataset.records + .filter((record) => record.userId === params.userId.toString()) + .sort((left, right) => right.gameCreation - left.gameCreation); + const records = this.applyChampionFilter(allUserRecords, params.filters); + const limit = this.clampLimit(params.filters.limit, 30, 50); + const cursor = params.filters.cursor; + const page = records + .filter((record) => !cursor || record.gameCreation < cursor) + .slice(0, limit + 1); + const visible = page.slice(0, limit); + const response: UserInternalHistoryResponse = { + season: dataset.season, + championStats: this.buildUserChampionStats(allUserRecords, dataset.season), + summary: this.buildUserSummary(records, visible.length || limit), + matches: visible.map((record) => this.toRecentMatchView(record, dataset)), + nextCursor: + page.length > limit + ? visible[visible.length - 1]?.gameCreation ?? null + : null, + lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, + }; + await this.cacheService.set(key, response); + return response; + } + + public invalidateCommunity(communityId: mongoose.Types.ObjectId): Promise { + return this.cacheService.invalidateCommunity(communityId.toString()); + } + + private async buildBaseDataset( + communityId: mongoose.Types.ObjectId, + filters: CommunityStatsFilters, + ): Promise { + const context = await this.resolveContext(communityId, filters); + const MatchModel = await this.connectionService.getModel('match'); + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const matches = await MatchModel.find({ + communityId, + status: { $in: ['finished', 'in-progress'] }, + 'result.games.0': { $exists: true }, + }) + .sort({ scheduledAt: -1 }) + .limit(MAX_MATCH_SCAN) + .exec(); + const riotMatchIds = [ + ...new Set( + matches.flatMap((match) => + (match.result?.games ?? []).map((game) => game.riotMatchId), + ), + ), + ]; + const riotDocs = await RiotMatchModel.find({ matchId: { $in: riotMatchIds } }) + .lean() + .exec(); + const rawByMatchId = new Map( + riotDocs.map((doc) => [doc.matchId, doc.raw as unknown as RiotMatchDto]), + ); + + const cards: InternalMatchCardView[] = []; + const records: InternalRecord[] = []; + const detailsByMatchId = new Map(); + + for (const match of matches) { + const games = (match.result?.games ?? []) + .filter((game) => this.isGameInRange(game.gameCreation, context)) + .sort((left, right) => left.gameNumber - right.gameNumber); + if (games.length === 0) continue; + cards.push(this.toMatchCard(match, games)); + + for (const game of games) { + const raw = rawByMatchId.get(game.riotMatchId); + const detail = raw + ? this.toGameDetail(match, game, raw) + : this.toFallbackGameDetail(match, game); + detailsByMatchId.set(match._id.toString(), [ + ...(detailsByMatchId.get(match._id.toString()) ?? []), + detail, + ]); + records.push(...detail.teams.flatMap((team) => team.participants)); + } + } + + return { + season: context.season, + matches: cards, + records, + detailsByMatchId, + }; + } + + private async resolveContext( + communityId: mongoose.Types.ObjectId, + filters: CommunityStatsFilters, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId).exec(); + if (!community) throw new NotFoundException('Community not found.'); + const season = this.resolveSeason(community, filters.seasonId); + const from = + filters.from ? new Date(filters.from) : + season.startedAt ? new Date(season.startedAt) : + null; + const to = filters.to ? new Date(filters.to) : null; + if (from && Number.isNaN(from.getTime())) { + throw new BadRequestException('Invalid from date.'); + } + if (to && Number.isNaN(to.getTime())) { + throw new BadRequestException('Invalid to date.'); + } + return { community, season, from, to }; + } + + private resolveSeason( + community: CommunityDocument, + seasonId?: string, + ): HistorySeasonDto { + const seasons = this.resolveSeasons(community); + if (seasonId === 'all') { + return { id: 'all', label: '전체 시즌', startedAt: null, endedAt: null }; + } + if (seasonId && seasonId !== 'current') { + const selected = seasons.find((season) => season.id === seasonId); + if (!selected) throw new BadRequestException('Invalid seasonId.'); + return selected; + } + return ( + seasons.find((season) => !season.endedAt) ?? + seasons[0] ?? { + id: 'current', + label: '현재 시즌', + startedAt: community.seasonStartedAt?.toISOString() ?? null, + endedAt: null, + } + ); + } + + private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] { + const configured = community.seasons?.map((season) => ({ + id: season.id, + label: season.label, + startedAt: season.startedAt.toISOString(), + endedAt: season.endedAt?.toISOString() ?? null, + })); + if (configured?.length) return configured; + return [ + { + id: 'current', + label: '현재 시즌', + startedAt: community.seasonStartedAt?.toISOString() ?? null, + endedAt: null, + }, + ]; + } + + private toMatchCard( + match: MatchDocument, + games: NonNullable['games'], + ): InternalMatchCardView { + const participantById = new Map( + match.participants.map((participant) => [ + participant.userId.toString(), + participant, + ]), + ); + return { + matchId: match._id.toString(), + title: match.title, + scheduledAt: match.scheduledAt.toISOString(), + status: match.status === 'finished' ? 'finished' : 'in-progress', + gameCount: match.gameCount, + blueScore: match.result?.blueScore ?? 0, + redScore: match.result?.redScore ?? 0, + winnerSide: match.result?.winnerSide, + games: games.map((game) => ({ + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId ?? null, + winnerSide: game.winnerSide ?? null, + gameDuration: game.gameDuration, + })), + teams: match.teams.map((team) => ({ + side: team.side, + name: team.name, + members: team.members.map((member) => { + const participant = participantById.get(member.userId.toString()); + return { + userId: member.userId.toString(), + summonerName: participant?.gameName ?? 'Unknown', + profileIconId: participant?.profileIconId ?? 0, + }; + }), + })), + }; + } + + private toGameDetail( + match: MatchDocument, + game: NonNullable['games'][number], + raw: RiotMatchDto, + ): InternalGameDetail { + const puuidByUserId = new Map( + match.participants + .filter((participant) => participant.puuid) + .map((participant) => [ + participant.userId.toString(), + participant.puuid as string, + ]), + ); + const rawByPuuid = new Map( + raw.info.participants.map((participant) => [participant.puuid, participant]), + ); + const rawTeamIdBySide = new Map(); + for (const participant of game.participants) { + const puuid = puuidByUserId.get(participant.userId.toString()); + const rawParticipant = puuid ? rawByPuuid.get(puuid) : undefined; + if (rawParticipant) rawTeamIdBySide.set(participant.side, rawParticipant.teamId); + } + + return { + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + winnerSide: game.winnerSide, + teams: (['blue', 'red'] as TeamSide[]).map((side) => { + const rawTeamId = rawTeamIdBySide.get(side); + const rawTeam = raw.info.teams.find((team) => team.teamId === rawTeamId); + const teamRawParticipants = raw.info.participants.filter( + (participant) => participant.teamId === rawTeamId, + ); + const teamKills = teamRawParticipants.reduce( + (sum, participant) => sum + participant.kills, + 0, + ); + const teamDamage = teamRawParticipants.reduce( + (sum, participant) => sum + participant.totalDamageDealtToChampions, + 0, + ); + return { + side, + win: game.winnerSide === side, + objectives: { + baron: rawTeam?.objectives?.baron?.kills ?? 0, + dragon: rawTeam?.objectives?.dragon?.kills ?? 0, + tower: rawTeam?.objectives?.tower?.kills ?? 0, + }, + participants: game.participants + .filter((participant) => participant.side === side) + .map((participant) => + this.toRecord({ + match, + game, + participant, + rawParticipant: rawByPuuid.get( + puuidByUserId.get(participant.userId.toString()) ?? '', + ), + teamKills, + teamDamage, + }), + ), + }; + }), + }; + } + + private toFallbackGameDetail( + match: MatchDocument, + game: NonNullable['games'][number], + ): InternalGameDetail { + return { + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + winnerSide: game.winnerSide, + teams: (['blue', 'red'] as TeamSide[]).map((side) => ({ + side, + win: game.winnerSide === side, + objectives: { baron: 0, dragon: 0, tower: 0 }, + participants: game.participants + .filter((participant) => participant.side === side) + .map((participant) => + this.toRecord({ match, game, participant, teamKills: 0, teamDamage: 0 }), + ), + })), + }; + } + + private toRecord(params: { + match: MatchDocument; + game: NonNullable['games'][number]; + participant: MatchGameResultParticipant; + rawParticipant?: RiotMatchParticipantDto; + teamKills: number; + teamDamage: number; + }): InternalRecord { + const { match, game, participant, rawParticipant, teamKills, teamDamage } = params; + const snapshot = match.participants.find((item) => + item.userId.equals(participant.userId), + ); + const minutes = Math.max( + (rawParticipant?.timePlayed ?? game.gameDuration) / 60, + 1, + ); + const cs = rawParticipant + ? rawParticipant.totalMinionsKilled + rawParticipant.neutralMinionsKilled + : 0; + const damage = rawParticipant?.totalDamageDealtToChampions ?? 0; + const killParticipation = this.percent( + participant.kills + participant.assists, + teamKills, + ); + const damageShare = this.percent(damage, teamDamage); + const rating = this.resolveRating({ + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + killParticipation, + csPerMin: this.average(cs, minutes), + damageShare, + visionPerMin: this.average(rawParticipant?.visionScore ?? 0, minutes), + }); + + return { + matchId: match._id.toString(), + title: match.title, + scheduledAt: match.scheduledAt, + gameNumber: game.gameNumber, + riotMatchId: game.riotMatchId, + gameCreation: game.gameCreation, + gameDuration: game.gameDuration, + userId: participant.userId.toString(), + summonerName: + snapshot?.gameName ?? + rawParticipant?.riotIdGameName ?? + rawParticipant?.summonerName ?? + 'Unknown', + profileIconId: snapshot?.profileIconId ?? 0, + side: participant.side, + championId: participant.championId, + championLevel: rawParticipant?.champLevel ?? 0, + teamPosition: + rawParticipant?.teamPosition || rawParticipant?.individualPosition || '', + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + win: participant.win, + cs, + csPerMin: this.average(cs, minutes), + gold: rawParticipant?.goldEarned ?? 0, + gpm: this.average(rawParticipant?.goldEarned ?? 0, minutes), + damageDealtToChampions: damage, + damageTaken: rawParticipant?.totalDamageTaken ?? 0, + damageShare, + killParticipation, + visionScore: rawParticipant?.visionScore ?? 0, + controlWardsBought: this.numberField(rawParticipant, 'visionWardsBoughtInGame'), + wardsPlaced: rawParticipant?.wardsPlaced ?? 0, + wardsKilled: rawParticipant?.wardsKilled ?? 0, + items: [ + rawParticipant?.item0 ?? 0, + rawParticipant?.item1 ?? 0, + rawParticipant?.item2 ?? 0, + rawParticipant?.item3 ?? 0, + rawParticipant?.item4 ?? 0, + rawParticipant?.item5 ?? 0, + ], + trinket: rawParticipant?.item6 ?? 0, + summonerSpells: [ + rawParticipant?.summoner1Id ?? 0, + rawParticipant?.summoner2Id ?? 0, + ], + perks: rawParticipant ? this.resolvePerks(rawParticipant) : {}, + rating, + }; + } + + private buildLeaderboardRows(records: InternalRecord[]): LeaderboardRow[] { + const byUser = new Map(); + for (const record of records) { + byUser.set(record.userId, [...(byUser.get(record.userId) ?? []), record]); + } + return [...byUser.entries()] + .map(([userId, rows]) => this.toLeaderboardRow(userId, rows)) + .sort((left, right) => right.games - left.games || right.winRate - left.winRate); + } + + private toLeaderboardRow(userId: string, records: InternalRecord[]): LeaderboardRow { + const first = records[0]; + const wins = records.filter((record) => record.win).length; + const kills = this.sum(records, 'kills'); + const deaths = this.sum(records, 'deaths'); + const assists = this.sum(records, 'assists'); + const byLane: LeaderboardRow['byLane'] = {}; + for (const lane of ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'] as RiotLane[]) { + const laneRecords = records.filter((record) => record.teamPosition === lane); + if (laneRecords.length === 0) continue; + byLane[lane] = { + games: laneRecords.length, + wins: laneRecords.filter((record) => record.win).length, + kda: this.kda( + this.sum(laneRecords, 'kills'), + this.sum(laneRecords, 'deaths'), + this.sum(laneRecords, 'assists'), + ), + }; + } + const championCounts = new Map(); + for (const record of records) { + const current = + championCounts.get(record.championId) ?? { games: 0, wins: 0 }; + current.games += 1; + current.wins += record.win ? 1 : 0; + championCounts.set(record.championId, current); + } + + return { + userId, + summonerName: first?.summonerName ?? 'Unknown', + profileIconId: first?.profileIconId ?? 0, + games: records.length, + wins, + losses: records.length - wins, + winRate: this.percent(wins, records.length), + totalKills: kills, + totalDeaths: deaths, + totalAssists: assists, + kda: this.kda(kills, deaths, assists), + avgGoldPerMin: this.average(this.sum(records, 'gpm'), records.length), + avgKillParticipation: this.average( + this.sum(records, 'killParticipation'), + records.length, + ), + avgCsPerMin: this.average(this.sum(records, 'csPerMin'), records.length), + avgDamageShare: this.average(this.sum(records, 'damageShare'), records.length), + avgVisionScore: this.average(this.sum(records, 'visionScore'), records.length), + byLane, + topChampions: [...championCounts.entries()] + .map(([championId, stat]) => ({ + championId, + games: stat.games, + winRate: this.percent(stat.wins, stat.games), + })) + .sort((left, right) => right.games - left.games || right.winRate - left.winRate) + .slice(0, 3), + }; + } + + private buildUserChampionStats( + records: InternalRecord[], + season: HistorySeasonDto, + ): LeaderboardChampionStats { + const byChampion = new Map(); + for (const record of records) { + byChampion.set(record.championId, [ + ...(byChampion.get(record.championId) ?? []), + record, + ]); + } + const champions = [...byChampion.entries()] + .map(([championId, rows]) => this.toChampionRow(championId, rows)) + .sort((left, right) => right.games - left.games || right.winRate - left.winRate); + const totals = this.toChampionRow(0, records); + return { + queueGroup: 'internal', + rank: 'all', + queueIds: [], + season, + lastFetchedAt: records[0] ? new Date(records[0].gameCreation).toISOString() : null, + champions, + totals, + }; + } + + private toChampionRow(championId: number, rows: InternalRecord[]) { + const wins = rows.filter((record) => record.win).length; + const kills = this.sum(rows, 'kills'); + const deaths = this.sum(rows, 'deaths'); + const assists = this.sum(rows, 'assists'); + const gameMinutes = rows.reduce( + (sum, record) => sum + Math.max(record.gameDuration / 60, 1), + 0, + ); + return { + championId, + games: rows.length, + wins, + losses: rows.length - wins, + winRate: this.percent(wins, rows.length), + avgKills: this.average(kills, rows.length), + avgDeaths: this.average(deaths, rows.length), + avgAssists: this.average(assists, rows.length), + kda: this.kda(kills, deaths, assists), + totalKills: kills, + totalDeaths: deaths, + totalAssists: assists, + doubleKills: 0, + tripleKills: 0, + quadraKills: 0, + pentaKills: 0, + avgCs: this.average(this.sum(rows, 'cs'), rows.length), + avgCsPerMin: this.average(this.sum(rows, 'cs'), gameMinutes), + }; + } + + private buildUserSummary( + records: InternalRecord[], + requestedLimit: number, + ): UserInternalHistoryResponse['summary'] { + const views = records.slice(0, requestedLimit); + const wins = views.filter((record) => record.win).length; + const kills = this.sum(views, 'kills'); + const deaths = this.sum(views, 'deaths'); + const assists = this.sum(views, 'assists'); + const best = views.reduce((bestRecord, record) => { + if (!bestRecord) return record; + return record.deaths === 0 || record.rating > bestRecord.rating + ? record + : bestRecord; + }, null); + + return { + windowSize: views.length, + winRate: this.percent(wins, views.length), + wins, + losses: views.length - wins, + streak: this.resolveStreak(views), + kda: this.kda(kills, deaths, assists), + avgKills: this.average(kills, views.length), + avgDeaths: this.average(deaths, views.length), + avgAssists: this.average(assists, views.length), + bestRating: best + ? { + rating: best.deaths === 0 ? 'Perfect' : best.rating, + kills: best.kills, + deaths: best.deaths, + assists: best.assists, + matchId: best.riotMatchId, + } + : null, + positionRates: this.resolvePositionRates(views), + topChampions: this.resolveTopChampions(views), + lastFetchedAt: views[0] ? new Date(views[0].gameCreation).toISOString() : null, + }; + } + + private toRecentMatchView(record: InternalRecord, dataset: BaseDataset): RecentMatchView { + const detail = dataset.detailsByMatchId + .get(record.matchId) + ?.find((game) => game.riotMatchId === record.riotMatchId); + return { + matchId: record.riotMatchId, + queueId: 0, + queueLabel: '내전', + gameCreation: record.gameCreation, + gameDuration: record.gameDuration, + win: record.win, + remake: false, + championId: record.championId, + championLevel: record.championLevel, + teamPosition: record.teamPosition, + kills: record.kills, + deaths: record.deaths, + assists: record.assists, + kda: this.kda(record.kills, record.deaths, record.assists), + rating: record.rating, + totalCs: record.cs, + csPerMin: record.csPerMin, + killParticipation: record.killParticipation, + visionScore: record.visionScore, + controlWardsBought: record.controlWardsBought, + wardsPlaced: record.wardsPlaced, + wardsKilled: record.wardsKilled, + damageDealtToChampions: record.damageDealtToChampions, + damageTaken: record.damageTaken, + goldEarned: record.gold, + items: record.items, + trinket: record.trinket, + summonerSpells: record.summonerSpells, + perks: record.perks, + teams: (detail?.teams ?? []).map((team) => ({ + side: team.side === 'blue' ? 100 : 200, + win: team.win, + objectives: team.objectives, + participants: team.participants.map((participant) => ({ + puuid: participant.userId, + gameName: participant.summonerName, + tagLine: '', + championId: participant.championId, + teamPosition: participant.teamPosition, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + })), + })), + }; + } + + private applyChampionFilter( + records: InternalRecord[], + filters: CommunityStatsFilters, + ): InternalRecord[] { + if (!filters.championId) return records; + return records.filter((record) => record.championId === filters.championId); + } + + private isGameInRange( + gameCreation: number, + context: CommunityStatsContext, + ): boolean { + if (context.from && gameCreation < context.from.getTime()) return false; + if (context.to && gameCreation > context.to.getTime()) return false; + return true; + } + + private toHighlight( + row: LeaderboardRow | undefined, + field: keyof Pick< + LeaderboardRow, + 'kda' | 'totalKills' | 'avgKillParticipation' | 'avgCsPerMin' + >, + ): LeaderHighlight | null { + if (!row) return null; + return { + metric: Number(row[field]), + userId: row.userId, + summonerName: row.summonerName, + isSingleGame: false, + }; + } + + private toSingleGameHighlight( + record: InternalRecord | undefined, + field: keyof Pick, + ): LeaderHighlight | null { + if (!record) return null; + return { + metric: record[field], + userId: record.userId, + summonerName: record.summonerName, + championId: record.championId, + matchId: record.riotMatchId, + isSingleGame: true, + }; + } + + private resolveStreak( + records: InternalRecord[], + ): UserInternalHistoryResponse['summary']['streak'] { + if (records.length === 0) return null; + const firstWin = records[0].win; + let count = 0; + for (const record of records) { + if (record.win !== firstWin) break; + count += 1; + } + return { type: firstWin ? 'win' : 'loss', count }; + } + + private resolvePositionRates( + records: InternalRecord[], + ): Partial> { + const counts = new Map(); + for (const record of records) { + if (!record.teamPosition) continue; + counts.set(record.teamPosition, (counts.get(record.teamPosition) ?? 0) + 1); + } + return Object.fromEntries( + [...counts.entries()].map(([lane, count]) => [ + lane, + this.percent(count, records.length), + ]), + ) as Partial>; + } + + private resolveTopChampions(records: InternalRecord[]) { + const byChampion = new Map(); + for (const record of records) { + const current = + byChampion.get(record.championId) ?? { games: 0, wins: 0, rating: 0 }; + current.games += 1; + current.wins += record.win ? 1 : 0; + current.rating += record.rating; + byChampion.set(record.championId, current); + } + return [...byChampion.entries()] + .map(([championId, stat]) => ({ + championId, + games: stat.games, + winRate: this.percent(stat.wins, stat.games), + pickRate: this.percent(stat.games, records.length), + avgRating: this.average(stat.rating, stat.games), + })) + .sort((left, right) => right.games - left.games || right.winRate - left.winRate) + .slice(0, 3); + } + + private resolvePerks(participant: RiotMatchParticipantDto) { + const primary = participant.perks.styles.find( + (style) => style.description === 'primaryStyle', + ); + const sub = participant.perks.styles.find( + (style) => style.description === 'subStyle', + ); + return { + primaryStyle: primary?.style, + subStyle: sub?.style, + keystone: primary?.selections[0]?.perk, + }; + } + + private resolveRating(params: { + kills: number; + deaths: number; + assists: number; + killParticipation: number; + csPerMin: number; + damageShare: number; + visionPerMin: number; + }): number { + const kda = this.kda(params.kills, params.deaths, params.assists); + const score = + Math.min(kda / 6, 1) * 4 + + Math.min(params.killParticipation / 100, 1) * 2 + + Math.min(params.csPerMin / 9, 1) * 2 + + Math.min(params.damageShare / 35, 1) + + Math.min(params.visionPerMin / 2, 1); + return this.round(score); + } + + private cacheKey( + scope: string, + communityId: mongoose.Types.ObjectId, + filters: CommunityStatsFilters, + ): string { + return [ + 'riot:communitystats', + scope, + communityId.toString(), + filters.seasonId ?? 'current', + filters.from ?? '', + filters.to ?? '', + filters.championId ?? '', + filters.cursor ?? '', + filters.limit ?? '', + ].join(':'); + } + + private clampLimit(value: number | undefined, fallback: number, max: number): number { + if (!value || !Number.isFinite(value)) return fallback; + return Math.max(1, Math.min(Math.floor(value), max)); + } + + private sum( + records: InternalRecord[], + field: T, + ): number { + return records.reduce((total, record) => { + const value = record[field]; + return total + (typeof value === 'number' ? value : 0); + }, 0); + } + + private kda(kills: number, deaths: number, assists: number): number { + return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths); + } + + private percent(value: number, total: number): number { + return total > 0 ? Math.round((value / total) * 100) : 0; + } + + private average(value: number, total: number): number { + return total > 0 ? this.round(value / total) : 0; + } + + private round(value: number): number { + return Math.round(value * 10) / 10; + } + + private numberField( + participant: RiotMatchParticipantDto | undefined, + key: string, + ): number { + const value = participant?.[key]; + return typeof value === 'number' && Number.isFinite(value) ? value : 0; + } +} diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts new file mode 100644 index 00000000..4696f1cb --- /dev/null +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -0,0 +1,196 @@ +import type { RiotLane, TeamSide } from '../global/database/schema'; +import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types'; + +export interface CommunityStatsFilters { + seasonId?: string; + from?: string; + to?: string; + championId?: number; + cursor?: number; + limit?: number; +} + +export interface InternalMatchListResponse { + matches: InternalMatchCardView[]; + nextCursor: number | null; + season: HistorySeasonDto; +} + +export interface InternalMatchCardView { + matchId: string; + title: string; + scheduledAt: string; + status: 'finished' | 'in-progress'; + gameCount: number; + blueScore: number; + redScore: number; + winnerSide?: TeamSide; + games: Array<{ + gameNumber: number; + riotMatchId: string | null; + winnerSide: TeamSide | null; + gameDuration: number; + }>; + teams: Array<{ + side: TeamSide; + name: string; + members: Array<{ + userId: string; + summonerName: string; + profileIconId: number; + }>; + }>; +} + +export interface LeaderboardResponse { + rows: LeaderboardRow[]; + season: HistorySeasonDto; +} + +export interface LeaderboardRow { + userId: string; + summonerName: string; + profileIconId: number; + games: number; + wins: number; + losses: number; + winRate: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + kda: number; + avgGoldPerMin: number; + avgKillParticipation: number; + avgCsPerMin: number; + avgDamageShare: number; + avgVisionScore: number; + byLane: Partial>; + topChampions: Array<{ championId: number; games: number; winRate: number }>; +} + +export interface LeaderHighlight { + metric: number; + userId: string; + summonerName: string; + championId?: number; + matchId?: string; + isSingleGame: boolean; +} + +export interface TeamInsightsResponse { + season: HistorySeasonDto; + sideWinRate: { + blue: number; + red: number; + bluePicks: number; + redPicks: number; + }; + topKda: LeaderHighlight | null; + mostKills: LeaderHighlight | null; + topTeamGpm: LeaderHighlight | null; + topKillParticipation: LeaderHighlight | null; + bestFarm: LeaderHighlight | null; + minGamesThreshold: number; +} + +export interface InternalMatchDetailResponse { + match: InternalMatchCardView; + games: Array<{ + gameNumber: number; + riotMatchId: string; + gameCreation: number; + gameDuration: number; + teams: Array<{ + side: TeamSide; + win: boolean; + objectives: { baron: number; dragon: number; tower: number }; + participants: Array<{ + userId: string | null; + summonerName: string; + side: TeamSide; + teamPosition: string; + championId: number; + kills: number; + deaths: number; + assists: number; + cs: number; + csPerMin: number; + gold: number; + gpm: number; + damageDealtToChampions: number; + damageShare: number; + killParticipation: number; + visionScore: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + win: boolean; + }>; + }>; + }>; +} + +export interface UserInternalHistoryResponse { + season: HistorySeasonDto; + championStats: LeaderboardChampionStats; + summary: { + windowSize: number; + winRate: number; + wins: number; + losses: number; + streak: { type: 'win' | 'loss'; count: number } | null; + kda: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + bestRating: { + rating: number | 'Perfect'; + kills: number; + deaths: number; + assists: number; + matchId: string; + } | null; + positionRates: Partial>; + topChampions: Array<{ + championId: number; + games: number; + winRate: number; + pickRate: number; + avgRating: number; + }>; + lastFetchedAt: string | null; + }; + matches: RecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; +} + +export interface LeaderboardChampionStats { + queueGroup: 'internal'; + rank: 'all'; + queueIds: number[]; + season: HistorySeasonDto; + lastFetchedAt: string | null; + champions: Array<{ + championId: number; + games: number; + wins: number; + losses: number; + winRate: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + kda: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + doubleKills: number; + tripleKills: number; + quadraKills: number; + pentaKills: number; + avgCs: number; + avgCsPerMin: number; + }>; + totals: LeaderboardChampionStats['champions'][number]; +} diff --git a/apps/api/src/modules/community/community.controller.ts b/apps/api/src/modules/community/community.controller.ts new file mode 100644 index 00000000..be0f5327 --- /dev/null +++ b/apps/api/src/modules/community/community.controller.ts @@ -0,0 +1,107 @@ +import { + Body, + Controller, + BadRequestException, + ForbiddenException, + Get, + Param, + Patch, + Post, + Req, + UseGuards, +} from '@nestjs/common'; +import type { Request } from 'express'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +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 '../auth/auth-request'; +import { CommunityService } from './community.service'; +import { CreateCommunityDto } from './dto/create-community.dto'; +import { TransferOwnershipDto } from './dto/transfer-ownership.dto'; + +@Controller('communities') +export class CommunityController { + constructor(private readonly communityService: CommunityService) {} + + @Post() + @AllowPublicAccess() + public async createCommunity( + @Body() body: CreateCommunityDto, + @Req() req: Request, + ) { + if (!req.identity && !body.owner) { + throw new BadRequestException( + 'owner is required when not authenticated.', + ); + } + return this.communityService.createCommunityWithOwner({ + ...body, + identityId: req.identity?._id, + }); + } + + @Get(':communityId') + @AllowPublicAccess() + public async getCommunity( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + ) { + return this.communityService.getById(communityId); + } + + @Patch(':communityId/members/:userId/promote') + @Roles('owner') + @UseGuards(RolesGuard) + public async promoteToAdmin( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.promoteToAdmin({ communityId, targetUserId }); + } + + @Patch(':communityId/members/:userId/demote') + @Roles('owner') + @UseGuards(RolesGuard) + public async demoteToMember( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) targetUserId: mongoose.Types.ObjectId, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.demoteToMember({ communityId, targetUserId }); + } + + @Patch(':communityId/transfer-ownership') + @Roles('owner') + @UseGuards(RolesGuard) + public async transferOwnership( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Body() body: TransferOwnershipDto, + ) { + this.assertOwnerOfCommunity(currentUser, communityId); + return this.communityService.transferOwnership({ + communityId, + currentOwnerUserId: currentUser._id, + newOwnerUserId: new mongoose.Types.ObjectId(body.newOwnerUserId), + }); + } + + private assertOwnerOfCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new ForbiddenException('You do not belong to this community.'); + } + } +} diff --git a/apps/api/src/modules/community/community.module.ts b/apps/api/src/modules/community/community.module.ts new file mode 100644 index 00000000..24e60fd7 --- /dev/null +++ b/apps/api/src/modules/community/community.module.ts @@ -0,0 +1,10 @@ +import { Module } from '@nestjs/common'; +import { CommunityController } from './community.controller'; +import { CommunityService } from './community.service'; + +@Module({ + controllers: [CommunityController], + providers: [CommunityService], + exports: [CommunityService], +}) +export class CommunityModule {} diff --git a/apps/api/src/modules/community/community.service.ts b/apps/api/src/modules/community/community.service.ts new file mode 100644 index 00000000..44a52e42 --- /dev/null +++ b/apps/api/src/modules/community/community.service.ts @@ -0,0 +1,196 @@ +import { + BadRequestException, + Injectable, + InternalServerErrorException, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + CommunityDocument, + UserDocument, +} from '../global/database/schema'; + +export interface CreateCommunityInput { + name: string; + description?: string; + identityId?: mongoose.Types.ObjectId; + owner?: { + kakaoTalkId?: string; + kakaoTalkNickname?: string; + discordId?: string; + discordNickname?: string; + }; +} + +@Injectable() +export class CommunityService { + constructor(private readonly connectionService: ConnectionService) {} + + public async getById( + communityId: mongoose.Types.ObjectId, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId).exec(); + if (!community) throw new NotFoundException('Community not found.'); + return community; + } + + public async createCommunityWithOwner(input: CreateCommunityInput): Promise<{ + community: CommunityDocument; + owner: UserDocument; + }> { + const CommunityModel = await this.connectionService.getModel('community'); + const UserModel = await this.connectionService.getModel('user'); + + const communityId = new mongoose.Types.ObjectId(); + const ownerUserId = new mongoose.Types.ObjectId(); + + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + + try { + session.startTransaction(); + + const [community] = await CommunityModel.create( + [ + { + _id: communityId, + name: input.name, + description: input.description ?? '', + ownerUserId, + }, + ], + { session }, + ); + + const [owner] = await UserModel.create( + [ + { + _id: ownerUserId, + communityId, + identityId: input.identityId, + role: 'owner', + kakaoTalkId: input.owner?.kakaoTalkId, + kakaoTalkNickname: input.owner?.kakaoTalkNickname, + discordId: input.owner?.discordId, + discordNickname: input.owner?.discordNickname, + }, + ], + { session }, + ); + + await session.commitTransaction(); + return { community, owner }; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + public async promoteToAdmin(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + }): Promise { + return this.changeNonOwnerRole({ ...params, nextRole: 'admin' }); + } + + public async demoteToMember(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + }): Promise { + return this.changeNonOwnerRole({ ...params, nextRole: 'member' }); + } + + public async transferOwnership(params: { + communityId: mongoose.Types.ObjectId; + currentOwnerUserId: mongoose.Types.ObjectId; + newOwnerUserId: mongoose.Types.ObjectId; + }): Promise<{ + community: CommunityDocument; + previousOwner: UserDocument; + newOwner: UserDocument; + }> { + if (params.currentOwnerUserId.equals(params.newOwnerUserId)) { + throw new BadRequestException('New owner is already the current owner.'); + } + + const CommunityModel = await this.connectionService.getModel('community'); + const UserModel = await this.connectionService.getModel('user'); + + const session = await this.connectionService.createSession(); + if (!session) { + throw new InternalServerErrorException('Failed to start DB session.'); + } + + try { + session.startTransaction(); + + const community = await CommunityModel.findById( + params.communityId, + ).session(session); + if (!community) throw new NotFoundException('Community not found.'); + if (!community.ownerUserId.equals(params.currentOwnerUserId)) { + throw new BadRequestException('Acting user is not the current owner.'); + } + + const [previousOwner, newOwner] = await Promise.all([ + UserModel.findById(params.currentOwnerUserId).session(session), + UserModel.findById(params.newOwnerUserId).session(session), + ]); + if (!previousOwner) + throw new NotFoundException('Previous owner user not found.'); + if (!newOwner) throw new NotFoundException('New owner user not found.'); + if (!newOwner.communityId.equals(params.communityId)) { + throw new BadRequestException( + 'New owner does not belong to this community.', + ); + } + + community.ownerUserId = newOwner._id; + previousOwner.role = 'admin'; + newOwner.role = 'owner'; + + await Promise.all([ + community.save({ session }), + previousOwner.save({ session }), + newOwner.save({ session }), + ]); + + await session.commitTransaction(); + return { community, previousOwner, newOwner }; + } catch (err) { + await session.abortTransaction(); + throw err; + } finally { + await session.endSession(); + } + } + + private async changeNonOwnerRole(params: { + communityId: mongoose.Types.ObjectId; + targetUserId: mongoose.Types.ObjectId; + nextRole: 'admin' | 'member'; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findById(params.targetUserId); + if (!user) throw new NotFoundException('Target user not found.'); + if (!user.communityId.equals(params.communityId)) { + throw new BadRequestException( + 'Target user does not belong to this community.', + ); + } + if (user.role === 'owner') { + throw new BadRequestException( + 'Owner role must be changed via transferOwnership.', + ); + } + user.role = params.nextRole; + await user.save(); + return user; + } +} diff --git a/apps/api/src/modules/community/dto/create-community.dto.ts b/apps/api/src/modules/community/dto/create-community.dto.ts new file mode 100644 index 00000000..e175b7fb --- /dev/null +++ b/apps/api/src/modules/community/dto/create-community.dto.ts @@ -0,0 +1,47 @@ +import { Type } from 'class-transformer'; +import { + IsOptional, + IsString, + MaxLength, + MinLength, + ValidateNested, +} from 'class-validator'; + +class CreateCommunityOwnerDto { + @IsOptional() + @IsString() + @MaxLength(64) + kakaoTalkId?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + kakaoTalkNickname?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + discordId?: string; + + @IsOptional() + @IsString() + @MaxLength(64) + discordNickname?: string; +} + +export class CreateCommunityDto { + @IsString() + @MinLength(1) + @MaxLength(64) + name!: string; + + @IsOptional() + @IsString() + @MaxLength(1024) + description?: string; + + @IsOptional() + @ValidateNested() + @Type(() => CreateCommunityOwnerDto) + owner?: CreateCommunityOwnerDto; +} diff --git a/apps/api/src/modules/community/dto/transfer-ownership.dto.ts b/apps/api/src/modules/community/dto/transfer-ownership.dto.ts new file mode 100644 index 00000000..90d472ec --- /dev/null +++ b/apps/api/src/modules/community/dto/transfer-ownership.dto.ts @@ -0,0 +1,6 @@ +import { IsMongoId } from 'class-validator'; + +export class TransferOwnershipDto { + @IsMongoId() + newOwnerUserId!: string; +} diff --git a/apps/api/src/modules/dakao/dakao-user.service.spec.ts b/apps/api/src/modules/dakao/dakao-user.service.spec.ts new file mode 100644 index 00000000..13248439 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao-user.service.spec.ts @@ -0,0 +1,90 @@ +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { RiotAccount, UserDocument } from '../global/database/schema'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import { RiotAccountService } from '../riot/riot-account.service'; +import { DakaoUserError, DakaoUserService } from './dakao-user.service'; + +const objectId = (hex: string) => new mongoose.Types.ObjectId(hex); + +function makeQuery(value: T) { + return { + exec: jest.fn().mockResolvedValue(value), + }; +} + +function makeService(params: { + user: Partial; + riotAccountService?: Partial; + enrichmentService?: Partial; +}) { + const findOneAndUpdate = jest + .fn() + .mockReturnValue(makeQuery(params.user as UserDocument)); + const connectionService = { + getModel: jest.fn().mockResolvedValue({ findOneAndUpdate }), + } as unknown as ConnectionService; + const riotAccountService = { + getByRiotId: jest.fn(), + ...params.riotAccountService, + } as unknown as RiotAccountService; + const enrichmentService = { + enrichRiotAccount: jest.fn(), + ...params.enrichmentService, + } as unknown as RiotAccountEnrichmentService; + + return { + service: new DakaoUserService( + connectionService, + riotAccountService, + enrichmentService, + ), + connectionService, + findOneAndUpdate, + riotAccountService, + enrichmentService, + }; +} + +describe('DakaoUserService', () => { + it('rejects account registration when the user already has a Riot account', async () => { + const save = jest.fn().mockResolvedValue(undefined); + const existingAccount = { + puuid: 'puuid-1', + gameName: '기존소환사', + tagLine: 'KR1', + isPrimary: true, + } as RiotAccount; + const { + service, + connectionService, + riotAccountService, + enrichmentService, + } = makeService({ + user: { + _id: objectId('222222222222222222222222'), + riotAccounts: [existingAccount], + save, + } as Partial, + }); + + await expect( + service.registerPrimaryRiotAccount({ + communityId: objectId('111111111111111111111111'), + kakaoTalkId: 'kakao-user-1', + kakaoTalkNickname: '프리리', + gameName: '새소환사', + tagLine: 'KR2', + }), + ).rejects.toMatchObject({ + code: 'riot_account_already_registered', + detail: '기존소환사#KR1', + } satisfies Partial); + + expect(connectionService.getModel).toHaveBeenCalledTimes(1); + expect(connectionService.getModel).toHaveBeenCalledWith('user'); + expect(riotAccountService.getByRiotId).not.toHaveBeenCalled(); + expect(enrichmentService.enrichRiotAccount).not.toHaveBeenCalled(); + expect(save).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/api/src/modules/dakao/dakao-user.service.ts b/apps/api/src/modules/dakao/dakao-user.service.ts new file mode 100644 index 00000000..00c17ab1 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao-user.service.ts @@ -0,0 +1,393 @@ +import { Injectable, Logger } from '@nestjs/common'; +import mongoose, { isValidObjectId } from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { RiotAccount, UserDocument } from '../global/database/schema'; +import { RiotApiError } from '../riot/riot.client.service'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import { RiotAccountService } from '../riot/riot-account.service'; +import { + RIOT_PLATFORM_ROUTES, + RIOT_REGIONAL_ROUTES, + RiotPlatformRoute, + RiotRegionalRoute, +} from '../riot/riot.types'; +import { formatCodePoints, normalizeRiotIdPart } from './riot-id.util'; + +export class DakaoUserError extends Error { + constructor( + public readonly code: + | 'invalid_project_id' + | 'community_not_found' + | 'riot_account_not_found' + | 'riot_account_already_registered' + | 'riot_account_conflict' + | 'riot_account_lookup_failed', + public readonly detail?: string, + ) { + super(`Dakao user error: ${code}${detail ? ` (${detail})` : ''}`); + } +} + +interface ResolveContext { + communityId: mongoose.Types.ObjectId; + kakaoTalkId: string; + kakaoTalkNickname: string; + gameName: string; + tagLine: string; +} + +interface ResolveResult { + user: UserDocument; + riotAccount: RiotAccount; +} + +interface RiotRouting { + platform: RiotPlatformRoute; + region: RiotRegionalRoute; +} + +interface ResolvedRiotIdentity { + requestedGameName: string; + requestedTagLine: string; + dto: { puuid: string; gameName: string | null; tagLine: string | null }; +} + +const DEFAULT_RIOT_PLATFORM: RiotPlatformRoute = 'kr'; +const DEFAULT_RIOT_REGION: RiotRegionalRoute = 'asia'; + +@Injectable() +export class DakaoUserService { + private readonly logger = new Logger(DakaoUserService.name); + + constructor( + private readonly connectionService: ConnectionService, + private readonly riotAccountService: RiotAccountService, + private readonly enrichmentService: RiotAccountEnrichmentService, + ) {} + + public async resolveCommunityIdByDakaoProjectId( + dakaoProjectId: string, + ): Promise { + if (!isValidObjectId(dakaoProjectId)) { + throw new DakaoUserError('invalid_project_id', dakaoProjectId); + } + + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findOne({ + dakaoProjectId: dakaoProjectId, + }) + .select({ _id: 1 }) + .lean() + .exec(); + if (!community) { + throw new DakaoUserError('community_not_found', dakaoProjectId); + } + return community._id as mongoose.Types.ObjectId; + } + + public async upsertUser(params: { + communityId: mongoose.Types.ObjectId; + kakaoTalkId: string; + kakaoTalkNickname: string; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findOneAndUpdate( + { communityId: params.communityId, kakaoTalkId: params.kakaoTalkId }, + { + $set: { kakaoTalkNickname: params.kakaoTalkNickname }, + $setOnInsert: { + communityId: params.communityId, + kakaoTalkId: params.kakaoTalkId, + role: 'member', + isActivated: true, + }, + }, + { upsert: true, returnDocument: 'after', setDefaultsOnInsert: true }, + ).exec(); + if (!user) { + // upsert + returnDocument='after' 이면 항상 반환되지만 타입 안전을 위해 가드. + throw new DakaoUserError('community_not_found'); + } + return user; + } + + public async resolveRiotAccount( + context: ResolveContext, + ): Promise { + const user = await this.upsertUser(context); + const routing = await this.resolveRiotRouting(context.communityId); + const { requestedGameName, requestedTagLine, dto } = + await this.lookupRiotIdentity(context, routing); + + const existing = user.riotAccounts.find( + (a) => + a.gameName.toLowerCase() === requestedGameName.toLowerCase() && + a.tagLine.toLowerCase() === requestedTagLine.toLowerCase(), + ); + if (existing) { + this.logger.log( + `Found existing Riot account ${requestedGameName}#${requestedTagLine}: puuid=${existing.puuid}`, + ); + } + + if (existing) { + const nextGameName = dto.gameName ?? requestedGameName; + const nextTagLine = dto.tagLine ?? requestedTagLine; + if (existing.puuid !== dto.puuid) { + this.logger.warn( + `Riot account puuid mismatch for ${requestedGameName}#${requestedTagLine}: stored=${existing.puuid} resolved=${dto.puuid}. Updating stored account.`, + ); + existing.puuid = dto.puuid; + existing.gameName = nextGameName; + existing.tagLine = nextTagLine; + this.clearRiotCache(existing); + await this.saveUserHandlingDuplicate(user, nextGameName, nextTagLine); + return this.enrichAttachedAccount({ + user, + riotAccount: existing, + platform: routing.platform, + region: routing.region, + }); + } + + if ( + existing.gameName !== nextGameName || + existing.tagLine !== nextTagLine + ) { + existing.gameName = nextGameName; + existing.tagLine = nextTagLine; + await user.save(); + } + return { user, riotAccount: existing }; + } + + return this.attachRiotAccount({ + user, + puuid: dto.puuid, + gameName: dto.gameName ?? requestedGameName, + tagLine: dto.tagLine ?? requestedTagLine, + platform: routing.platform, + region: routing.region, + }); + } + + public async registerPrimaryRiotAccount( + context: ResolveContext, + ): Promise { + const user = await this.upsertUser(context); + const existingPrimary = user.riotAccounts.find( + (account) => account.isPrimary, + ); + const existingAccount = existingPrimary ?? user.riotAccounts[0]; + if (existingAccount) { + throw new DakaoUserError( + 'riot_account_already_registered', + `${existingAccount.gameName}#${existingAccount.tagLine}`, + ); + } + + const routing = await this.resolveRiotRouting(context.communityId); + const { requestedGameName, requestedTagLine, dto } = + await this.lookupRiotIdentity(context, routing); + const nextGameName = dto.gameName ?? requestedGameName; + const nextTagLine = dto.tagLine ?? requestedTagLine; + + return this.attachRiotAccount({ + user, + puuid: dto.puuid, + gameName: nextGameName, + tagLine: nextTagLine, + platform: routing.platform, + region: routing.region, + }); + } + + private async lookupRiotIdentity( + context: ResolveContext, + routing: RiotRouting, + ): Promise { + const requestedGameName = normalizeRiotIdPart(context.gameName); + const requestedTagLine = normalizeRiotIdPart(context.tagLine); + this.logRiotIdNormalization(context, requestedGameName, requestedTagLine); + + try { + const dto = await this.riotAccountService.getByRiotId( + requestedGameName, + requestedTagLine, + { region: routing.region }, + ); + this.logger.log( + `Resolved Riot ID ${requestedGameName}#${requestedTagLine} via ${routing.region}: puuid=${dto.puuid} canonical=${dto.gameName ?? '-'}#${dto.tagLine ?? '-'}`, + ); + return { requestedGameName, requestedTagLine, dto }; + } catch (err) { + if (err instanceof RiotApiError && err.status === 404) { + throw new DakaoUserError( + 'riot_account_not_found', + `${requestedGameName}#${requestedTagLine}`, + ); + } + this.logger.error( + `Riot account lookup failed for ${requestedGameName}#${requestedTagLine}: ${ + (err as Error)?.message ?? err + }`, + ); + throw new DakaoUserError( + 'riot_account_lookup_failed', + (err as Error)?.message, + ); + } + } + + private logRiotIdNormalization( + context: ResolveContext, + normalizedGameName: string, + normalizedTagLine: string, + ): void { + if ( + context.gameName === normalizedGameName && + context.tagLine === normalizedTagLine + ) { + return; + } + + this.logger.warn( + `Normalized Riot ID input ${context.gameName}#${context.tagLine} -> ${normalizedGameName}#${normalizedTagLine} ` + + `(gameNameCodePoints=${formatCodePoints(context.gameName)}, tagLineCodePoints=${formatCodePoints(context.tagLine)})`, + ); + } + + private async resolveRiotRouting( + communityId: mongoose.Types.ObjectId, + ): Promise { + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(communityId) + .select({ riotPlatform: 1, riotRegion: 1 }) + .lean() + .exec(); + + return { + platform: this.toRiotPlatform(community?.riotPlatform), + region: this.toRiotRegion(community?.riotRegion), + }; + } + + private async attachRiotAccount(params: { + user: UserDocument; + puuid: string; + gameName: string; + tagLine: string; + platform: RiotPlatformRoute; + region: RiotRegionalRoute; + }): Promise { + const { user } = params; + const isFirst = user.riotAccounts.length === 0; + user.riotAccounts.push({ + puuid: params.puuid, + gameName: params.gameName, + tagLine: params.tagLine, + profileIconId: 0, + revisionDate: 0, + summonerLevel: 0, + isPrimary: isFirst, + tiers: [], + tierHistory: [], + matchIds: [], + championMasteries: [], + championRecords: {}, + } as unknown as RiotAccount); + + await this.saveUserHandlingDuplicate(user, params.gameName, params.tagLine); + + const attached = user.riotAccounts.find((a) => a.puuid === params.puuid); + if (!attached) { + throw new DakaoUserError('riot_account_lookup_failed', 'attach failed'); + } + + return this.enrichAttachedAccount({ + user, + riotAccount: attached, + platform: params.platform, + region: params.region, + }); + } + + private async enrichAttachedAccount(params: { + user: UserDocument; + riotAccount: RiotAccount; + platform: RiotPlatformRoute; + region: RiotRegionalRoute; + }): Promise { + // 외부 API 실패는 등록 자체를 막지 않음. + try { + const enrichResult = await this.enrichmentService.enrichRiotAccount({ + userId: params.user._id, + puuid: params.riotAccount.puuid, + options: { + force: true, + platform: params.platform, + region: params.region, + }, + }); + if (enrichResult.account) { + return { user: params.user, riotAccount: enrichResult.account }; + } + } catch (err) { + this.logger.warn( + `Riot enrichment failed (continuing with empty data): ${ + (err as Error)?.message ?? err + }`, + ); + } + return { user: params.user, riotAccount: params.riotAccount }; + } + + private async saveUserHandlingDuplicate( + user: UserDocument, + gameName: string, + tagLine: string, + ): Promise { + try { + await user.save(); + } catch (err) { + // 같은 communityId + puuid 중복은 다른 유저가 이미 등록한 케이스. + if ((err as { code?: number })?.code === 11000) { + throw new DakaoUserError( + 'riot_account_conflict', + `${gameName}#${tagLine}`, + ); + } + throw err; + } + } + + private clearRiotCache(account: RiotAccount): void { + account.profileIconId = 0; + account.revisionDate = 0; + account.summonerLevel = 0; + account.tiers = []; + account.tierHistory = []; + account.matchIds = []; + account.matchIdsFetchedAt = undefined; + account.recentStatsSummary = undefined; + account.recentStatsFetchedAt = undefined; + account.championMasteries = []; + account.championMasteriesFetchedAt = undefined; + account.championRecords = {}; + account.championRecordsFetchedAt = undefined; + } + + private toRiotPlatform(value: unknown): RiotPlatformRoute { + return typeof value === 'string' && + RIOT_PLATFORM_ROUTES.includes(value as RiotPlatformRoute) + ? (value as RiotPlatformRoute) + : DEFAULT_RIOT_PLATFORM; + } + + private toRiotRegion(value: unknown): RiotRegionalRoute { + return typeof value === 'string' && + RIOT_REGIONAL_ROUTES.includes(value as RiotRegionalRoute) + ? (value as RiotRegionalRoute) + : DEFAULT_RIOT_REGION; + } +} diff --git a/apps/api/src/modules/dakao/dakao.module.ts b/apps/api/src/modules/dakao/dakao.module.ts new file mode 100644 index 00000000..5626b745 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.module.ts @@ -0,0 +1,33 @@ +import { Module } from '@nestjs/common'; +import { MatchModule } from '../match/match.module'; +import { RiotModule } from '../riot/riot.module'; +import { + DAKAO_OPTIONS, + createDefaultDakaoOptions, +} from './dakao.options'; +import { DakaoPublisher } from './dakao.publisher'; +import { DakaoSubscriber } from './dakao.subscriber'; +import { DakaoUserService } from './dakao-user.service'; +import { IdempotencyCache } from './idempotency.cache'; +import { AccountRegisterHandler } from './handlers/account-register.handler'; +import { MatchJoinHandler } from './handlers/match-join.handler'; +import { MatchListHandler } from './handlers/match-list.handler'; + +@Module({ + imports: [RiotModule, MatchModule], + providers: [ + { + provide: DAKAO_OPTIONS, + useFactory: createDefaultDakaoOptions, + }, + DakaoPublisher, + DakaoSubscriber, + DakaoUserService, + IdempotencyCache, + AccountRegisterHandler, + MatchListHandler, + MatchJoinHandler, + ], + exports: [DakaoPublisher], +}) +export class DakaoModule {} diff --git a/apps/api/src/modules/dakao/dakao.options.ts b/apps/api/src/modules/dakao/dakao.options.ts new file mode 100644 index 00000000..98d724c4 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.options.ts @@ -0,0 +1,13 @@ +import { randomUUID } from 'crypto'; + +export const DAKAO_OPTIONS = Symbol('DAKAO_OPTIONS'); + +export interface DakaoOptions { + instanceId: string; +} + +export function createDefaultDakaoOptions(): DakaoOptions { + return { + instanceId: process.env.DAKAO_INSTANCE_ID || randomUUID(), + }; +} diff --git a/apps/api/src/modules/dakao/dakao.publisher.spec.ts b/apps/api/src/modules/dakao/dakao.publisher.spec.ts new file mode 100644 index 00000000..abc0e676 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.publisher.spec.ts @@ -0,0 +1,73 @@ +import { SecretService } from '../global/secret/secret.service'; +import { NatsService } from '../global/nats/nats.service'; +import { DakaoCommandEnvelope, DakaoSendMessagePayload } from './dakao.types'; +import { DakaoPublisher } from './dakao.publisher'; + +function makePublisher() { + const natsService = { + publish: jest.fn().mockResolvedValue(undefined), + subscribe: jest.fn(), + } as unknown as NatsService; + const secretService = {} as SecretService; + const publisher = new DakaoPublisher(natsService, secretService, { + instanceId: 'test', + }); + + return { publisher, natsService }; +} + +function getPublishedPayload(natsService: NatsService): DakaoSendMessagePayload { + const publish = natsService.publish as jest.Mock; + const envelope = publish.mock.calls[0][1] as DakaoCommandEnvelope< + DakaoSendMessagePayload + >; + return envelope.payload; +} + +describe('DakaoPublisher', () => { + it('keeps valid mention segments intact', async () => { + const { publisher, natsService } = makePublisher(); + + await publisher.sendMessage({ + chatroomId: '18474390111480678', + segments: [ + { + kind: 'mention', + userId: '6215844374579825921', + displayText: '날으는꼴뚜기/95/여/D', + }, + { kind: 'text', text: ' 신청 완료' }, + ], + }); + + expect(getPublishedPayload(natsService).segments).toEqual([ + { + kind: 'mention', + userId: '6215844374579825921', + displayText: '날으는꼴뚜기/95/여/D', + }, + { kind: 'text', text: ' 신청 완료' }, + ]); + }); + + it('downgrades invalid mention segments to text before publishing', async () => { + const { publisher, natsService } = makePublisher(); + + await publisher.sendMessage({ + chatroomId: '18474390111480678', + segments: [ + { + kind: 'mention', + userId: '-123', + displayText: '소쿠리', + }, + { kind: 'text', text: ' 신청 완료' }, + ], + }); + + expect(getPublishedPayload(natsService).segments).toEqual([ + { kind: 'text', text: '@소쿠리' }, + { kind: 'text', text: ' 신청 완료' }, + ]); + }); +}); diff --git a/apps/api/src/modules/dakao/dakao.publisher.ts b/apps/api/src/modules/dakao/dakao.publisher.ts new file mode 100644 index 00000000..21d49c99 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.publisher.ts @@ -0,0 +1,154 @@ +import { + Inject, + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import { SecretService } from '../global/secret/secret.service'; +import { NatsService } from '../global/nats/nats.service'; +import { + DakaoCommandEnvelope, + DakaoResultEnvelope, + DakaoSegment, + DakaoSendMessagePayload, +} from './dakao.types'; +import type { DakaoOptions } from './dakao.options'; +import { DAKAO_OPTIONS } from './dakao.options'; + +const SEND_MESSAGE_SUBJECT_DEFAULT = 'dakao.command.chat.send-message.v1'; +const COMMAND_SOURCE_DEFAULT = 'lolympus-tournament-support'; + +@Injectable() +export class DakaoPublisher implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(DakaoPublisher.name); + private replySubject = ''; + private sendMessageSubject = SEND_MESSAGE_SUBJECT_DEFAULT; + private source = COMMAND_SOURCE_DEFAULT; + + constructor( + private readonly natsService: NatsService, + private readonly secretService: SecretService, + @Inject(DAKAO_OPTIONS) private readonly options: DakaoOptions, + ) {} + + async onModuleInit() { + const replyOverride = await this.secretService + .get('DAKAO_REPLY_SUBJECT_PREFIX') + .catch(() => undefined); + const sendOverride = await this.secretService + .get('DAKAO_NATS_COMMAND_CHAT_SEND_MESSAGE_SUBJECT') + .catch(() => undefined); + const sourceOverride = await this.secretService + .get('DAKAO_COMMAND_SOURCE') + .catch(() => undefined); + + const replyPrefix = replyOverride || `dakao.result.${COMMAND_SOURCE_DEFAULT}`; + this.replySubject = `${replyPrefix}.${this.options.instanceId}`; + this.sendMessageSubject = sendOverride || SEND_MESSAGE_SUBJECT_DEFAULT; + this.source = sourceOverride || COMMAND_SOURCE_DEFAULT; + + this.natsService.subscribe( + this.replySubject, + (data) => this.handleReply(data), + ); + this.logger.log( + `Dakao reply subscriber ready on subject="${this.replySubject}"`, + ); + } + + async onModuleDestroy() { + // NatsService 가 subscription 정리한다. + } + + public async sendMessage(params: { + chatroomId: string; + segments: DakaoSegment[]; + correlationId?: string; + }): Promise { + const payload: DakaoSendMessagePayload = { + chatroomId: params.chatroomId, + segments: this.normalizeSegments(params.segments), + }; + const envelope: DakaoCommandEnvelope = { + schema: 'dakao.command.v1', + id: randomUUID(), + type: 'chat.send-message', + source: this.source, + correlationId: params.correlationId, + replySubject: this.replySubject, + payload, + }; + await this.natsService.publish(this.sendMessageSubject, envelope); + } + + private normalizeSegments(segments: DakaoSegment[]): DakaoSegment[] { + const normalized: DakaoSegment[] = []; + + for (const segment of segments) { + if (segment.kind === 'text') { + if (segment.text.length > 0) normalized.push(segment); + continue; + } + + if (segment.kind === 'mention') { + const userId = segment.userId.trim(); + const displayText = segment.displayText.trim(); + + if (this.isPositiveIntegerString(userId) && displayText.length > 0) { + normalized.push({ kind: 'mention', userId, displayText }); + continue; + } + + const fallbackText = this.renderMentionFallback(displayText, userId); + this.logger.warn( + `Dakao mention downgraded to text because userId/displayText is invalid: userId="${userId || '-'}" displayText="${displayText || '-'}"`, + ); + normalized.push({ kind: 'text', text: fallbackText }); + continue; + } + + const id = segment.id.trim(); + const altText = segment.altText.trim(); + if ( + id.length > 0 && + altText.length > 0 && + !/[()@]/.test(altText) + ) { + normalized.push({ kind: 'emoticon', id, altText }); + continue; + } + + this.logger.warn( + `Dakao emoticon downgraded to text because id/altText is invalid: id="${id || '-'}" altText="${altText || '-'}"`, + ); + normalized.push({ kind: 'text', text: `(${altText || '이모티콘'})` }); + } + + return normalized.length > 0 + ? normalized + : [{ kind: 'text', text: '명령 처리 결과를 보낼 수 없습니다.' }]; + } + + private isPositiveIntegerString(value: string): boolean { + return /^[1-9]\d*$/.test(value); + } + + private renderMentionFallback(displayText: string, userId: string): string { + const label = displayText || userId || '사용자'; + return label.startsWith('@') ? label : `@${label}`; + } + + private handleReply(reply: DakaoResultEnvelope): void { + if (reply.status === 'succeeded') { + this.logger.log( + `Dakao reply succeeded id=${reply.id} type=${reply.type} correlationId=${reply.correlationId ?? '-'}`, + ); + return; + } + this.logger.warn( + `Dakao reply failed id=${reply.id} type=${reply.type} code=${reply.error?.code ?? '-'} retryable=${reply.error?.retryable ?? false} message=${reply.error?.message ?? '-'}`, + ); + } +} diff --git a/apps/api/src/modules/dakao/dakao.subscriber.ts b/apps/api/src/modules/dakao/dakao.subscriber.ts new file mode 100644 index 00000000..9a42d8e5 --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.subscriber.ts @@ -0,0 +1,212 @@ +import { Injectable, Logger, OnModuleInit } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { NatsService } from '../global/nats/nats.service'; +import { SecretService } from '../global/secret/secret.service'; +import { CommandParseError, parseCommand } from './parsers/command.parser'; +import { DakaoInboundEvent, DakaoLong, DakaoSegment } from './dakao.types'; +import { DakaoPublisher } from './dakao.publisher'; +import { DakaoUserError, DakaoUserService } from './dakao-user.service'; +import { IdempotencyCache } from './idempotency.cache'; +import { AccountRegisterHandler } from './handlers/account-register.handler'; +import { MatchJoinHandler } from './handlers/match-join.handler'; +import { MatchListHandler } from './handlers/match-list.handler'; + +const INBOUND_SUBJECT_DEFAULT = 'lolympus-tournament-support.kakaotalk.command'; + +@Injectable() +export class DakaoSubscriber implements OnModuleInit { + private readonly logger = new Logger(DakaoSubscriber.name); + private inboundSubject = INBOUND_SUBJECT_DEFAULT; + private botUserId: string | undefined; + + constructor( + private readonly natsService: NatsService, + private readonly secretService: SecretService, + private readonly dakaoUserService: DakaoUserService, + private readonly publisher: DakaoPublisher, + private readonly idempotency: IdempotencyCache, + private readonly accountRegisterHandler: AccountRegisterHandler, + private readonly matchListHandler: MatchListHandler, + private readonly matchJoinHandler: MatchJoinHandler, + ) {} + + async onModuleInit() { + const subjectOverride = await this.secretService + .get('DAKAO_INBOUND_SUBJECT') + .catch(() => undefined); + this.inboundSubject = subjectOverride || INBOUND_SUBJECT_DEFAULT; + + this.botUserId = await this.secretService + .get('DAKAO_BOT_USER_ID') + .catch(() => undefined); + + this.natsService.subscribe( + this.inboundSubject, + (event) => this.handleEvent(event), + ); + this.logger.log( + `Dakao inbound subscriber ready on subject="${this.inboundSubject}"`, + ); + } + + private async handleEvent(event: DakaoInboundEvent): Promise { + if (!this.validate(event)) return; + + if (this.botUserId && event.userId === this.botUserId) { + return; + } + + const logIdKey = this.deriveLogIdKey(event); + if (logIdKey && this.idempotency.has(logIdKey)) { + return; + } + if (logIdKey) this.idempotency.remember(logIdKey); + + let communityId: mongoose.Types.ObjectId; + try { + communityId = await this.dakaoUserService.resolveCommunityIdByDakaoProjectId( + event.projectId, + ); + } catch (err) { + if (err instanceof DakaoUserError) { + if (err.code === 'invalid_project_id') { + this.logger.warn(`Invalid dakao projectId format: ${event.projectId}`); + return; + } + if (err.code === 'community_not_found') { + // 우리 쪽이 모르는 projectId. 메시지를 보내봤자 컨텍스트가 없으므로 로그만. + this.logger.warn(`Unknown dakao projectId: ${event.projectId}`); + return; + } + } + throw err; + } + + let segments: DakaoSegment[]; + const senderNickname = this.resolveSenderNickname(event); + const correlationId = this.serializeDakaoLong(event.origin.chatLog.logId); + try { + const command = parseCommand(event.origin.chatLog.message); + + switch (command.kind) { + case 'match-list': + segments = await this.matchListHandler.handle({ + communityId, + senderUserId: event.userId, + senderNickname, + }); + break; + case 'account-register': + segments = await this.accountRegisterHandler.handle({ + communityId, + senderUserId: event.userId, + senderNickname, + gameName: command.gameName, + tagLine: command.tagLine, + }); + break; + case 'match-join': + segments = await this.matchJoinHandler.handle({ + communityId, + matchId: command.matchId, + senderUserId: event.userId, + senderNickname, + gameName: command.gameName, + tagLine: command.tagLine, + positions: command.positions.positions, + }); + break; + } + + await this.publisher.sendMessage({ + chatroomId: event.chatroomId, + segments, + correlationId, + }); + } catch (err) { + if (err instanceof CommandParseError) { + // not_a_command 는 명령이 아닌 일반 메시지 → 무시. + if (err.code === 'not_a_command') return; + await this.publisher.sendMessage({ + chatroomId: event.chatroomId, + segments: this.parseErrorReply(event, senderNickname, err), + correlationId, + }); + return; + } + this.logger.error( + `Unhandled dakao event error: ${(err as Error)?.stack ?? err}`, + ); + } + } + + private validate(event: unknown): event is DakaoInboundEvent { + if (!event || typeof event !== 'object') return false; + const e = event as Partial; + if (typeof e.projectId !== 'string' || e.projectId.length === 0) return false; + if (typeof e.chatroomId !== 'string' || e.chatroomId.length === 0) + return false; + if (typeof e.nickname !== 'string') return false; + if (typeof e.userId !== 'string' || e.userId.length === 0) return false; + if (!e.origin || typeof e.origin !== 'object') return false; + const chatLog = (e.origin as { chatLog?: unknown }).chatLog; + if (!chatLog || typeof chatLog !== 'object') return false; + if (typeof (chatLog as { message?: unknown }).message !== 'string') + return false; + return true; + } + + private deriveLogIdKey(event: DakaoInboundEvent): string | null { + const serialized = this.serializeDakaoLong(event.origin.chatLog.logId); + return serialized ? `${event.projectId}:${serialized}` : null; + } + + private serializeDakaoLong(value: DakaoLong | string | undefined): string { + if (typeof value === 'string') return value; + if (!value || typeof value !== 'object') return ''; + const high = BigInt(value.high ?? 0); + const low = BigInt.asUintN(32, BigInt(value.low ?? 0)); + const combined = (high << 32n) | low; + return value.unsigned + ? BigInt.asUintN(64, combined).toString() + : BigInt.asIntN(64, combined).toString(); + } + + private resolveSenderNickname(event: DakaoInboundEvent): string { + const primary = event.nickname?.trim(); + if (primary) return primary; + const fallback = event.origin.authorNickname?.trim(); + return fallback ?? ''; + } + + private parseErrorReply( + event: DakaoInboundEvent, + senderNickname: string, + err: CommandParseError, + ): DakaoSegment[] { + const head: DakaoSegment[] = [ + { + kind: 'mention', + userId: event.userId, + displayText: senderNickname, + }, + ]; + const text = ((): string => { + switch (err.code) { + case 'unknown_command': + return ` 알 수 없는 명령어입니다. 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>`; + case 'usage': + return ` 사용법: !내전 목록, !내전 계정등록 <게임명>#<태그>, !내전 신청 <게임명>#<태그> <포지션1>,<포지션2>`; + case 'invalid_match_id': + return ` 매치 ID 형식이 올바르지 않습니다 (${err.detail ?? ''}).`; + case 'invalid_riot_id': + return ` 라이엇 ID 형식이 올바르지 않습니다 (예: 프리리#KR1).`; + case 'invalid_position': + return ` 포지션 입력이 올바르지 않습니다. 최소 2개, 중복 없이, 인식되는 별칭(탑/정글/미드/원딜/서폿) 사용.`; + default: + return ` 명령을 처리할 수 없습니다.`; + } + })(); + return [...head, { kind: 'text', text }]; + } +} diff --git a/apps/api/src/modules/dakao/dakao.types.ts b/apps/api/src/modules/dakao/dakao.types.ts new file mode 100644 index 00000000..554b3bed --- /dev/null +++ b/apps/api/src/modules/dakao/dakao.types.ts @@ -0,0 +1,102 @@ +// dakao NATS contracts +// inbound: dakao 가 lolympus-tournament-support.kakaotalk.command 로 발행하는 이벤트 +// outbound: 우리가 dakao.command.chat.send-message.v1 로 발행하는 명령 +// reply: dakao 가 우리 envelope 의 replySubject 로 publish 하는 결과 + +// ===== Inbound ===== +export interface DakaoLong { + high?: number; + low?: number; + unsigned?: boolean; +} + +export interface DakaoOriginChatLog { + logId: DakaoLong | string; + chatId: DakaoLong | string; + authorId: DakaoLong | string; + type: number; + sendAt: number; + message: string; + prevId?: DakaoLong | string; + msgId?: number; + revision?: number; + scope?: number; +} + +export interface DakaoOrigin { + chatId: DakaoLong | string; + logId: DakaoLong | string; + authorNickname?: string; + chatLog: DakaoOriginChatLog; + noSeen?: boolean; + notiRead?: boolean; + li?: number; + status?: number; +} + +export interface DakaoInboundEvent { + projectId: string; + chatroomId: string; + nickname: string; + userId: string; + origin: DakaoOrigin; +} + +// ===== Outbound: chat.send-message ===== +export interface DakaoTextSegment { + kind: 'text'; + text: string; +} + +export interface DakaoMentionSegment { + kind: 'mention'; + userId: string; + displayText: string; +} + +export interface DakaoEmoticonSegment { + kind: 'emoticon'; + id: string; + altText: string; +} + +export type DakaoSegment = + | DakaoTextSegment + | DakaoMentionSegment + | DakaoEmoticonSegment; + +export interface DakaoSendMessagePayload { + chatroomId: string; + segments: DakaoSegment[]; + attachment?: string | Record; + type?: number; + noSeen?: boolean; + scope?: number; + silence?: boolean; +} + +export interface DakaoCommandEnvelope { + schema: 'dakao.command.v1'; + id: string; + type: string; + source: string; + correlationId?: string; + replySubject?: string; + payload: TPayload; +} + +// ===== Reply ===== +export interface DakaoResultEnvelope { + schema: 'dakao.result.v1'; + id: string; + type: string; + status: 'succeeded' | 'failed'; + handledAt: string; + correlationId?: string; + result?: Record; + error?: { + code: string; + message: string; + retryable: boolean; + }; +} diff --git a/apps/api/src/modules/dakao/handlers/account-register.handler.spec.ts b/apps/api/src/modules/dakao/handlers/account-register.handler.spec.ts new file mode 100644 index 00000000..bd9a3d87 --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/account-register.handler.spec.ts @@ -0,0 +1,49 @@ +import mongoose from 'mongoose'; +import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; +import { AccountRegisterHandler } from './account-register.handler'; + +const objectId = (hex: string) => new mongoose.Types.ObjectId(hex); + +function makeHandler(dakaoUserService?: Partial) { + return new AccountRegisterHandler({ + registerPrimaryRiotAccount: jest.fn(), + ...dakaoUserService, + } as unknown as DakaoUserService); +} + +const baseParams = { + communityId: objectId('111111111111111111111111'), + senderUserId: 'kakao-user-1', + senderNickname: '프리리', + gameName: '프리리', + tagLine: 'KR1', +}; + +describe('AccountRegisterHandler', () => { + it('translates already-registered Riot account errors', async () => { + const handler = makeHandler({ + registerPrimaryRiotAccount: jest + .fn() + .mockRejectedValue( + new DakaoUserError( + 'riot_account_already_registered', + '기존소환사#KR1', + ), + ), + }); + + const segments = await handler.handle(baseParams); + + expect(segments).toEqual([ + expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }), + expect.objectContaining({ + kind: 'text', + text: expect.stringContaining('이미 등록된 라이엇 계정'), + }), + ]); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('기존소환사#KR1'), + }); + }); +}); diff --git a/apps/api/src/modules/dakao/handlers/account-register.handler.ts b/apps/api/src/modules/dakao/handlers/account-register.handler.ts new file mode 100644 index 00000000..26739b62 --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/account-register.handler.ts @@ -0,0 +1,81 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { DakaoSegment } from '../dakao.types'; +import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; + +interface AccountRegisterHandlerParams { + communityId: mongoose.Types.ObjectId; + senderUserId: string; + senderNickname: string; + gameName: string; + tagLine: string; +} + +@Injectable() +export class AccountRegisterHandler { + constructor(private readonly dakaoUserService: DakaoUserService) {} + + public async handle( + params: AccountRegisterHandlerParams, + ): Promise { + try { + const resolved = await this.dakaoUserService.registerPrimaryRiotAccount({ + communityId: params.communityId, + kakaoTalkId: params.senderUserId, + kakaoTalkNickname: params.senderNickname, + gameName: params.gameName, + tagLine: params.tagLine, + }); + + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { + kind: 'text', + text: + ` 계정 등록 완료` + + `\n대표 계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`, + }, + ]; + } catch (err) { + if (err instanceof DakaoUserError) { + return this.errorReply(params, this.translateUserError(err)); + } + throw err; + } + } + + private errorReply( + params: AccountRegisterHandlerParams, + message: string, + ): DakaoSegment[] { + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { kind: 'text', text: ` ${message}` }, + ]; + } + + private translateUserError(err: DakaoUserError): string { + switch (err.code) { + case 'invalid_project_id': + return '커뮤니티 식별자가 올바르지 않습니다.'; + case 'community_not_found': + return '연결된 커뮤니티를 찾을 수 없습니다.'; + case 'riot_account_not_found': + return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`; + case 'riot_account_already_registered': + return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}). 변경이 필요하면 운영자에게 문의해주세요.`; + case 'riot_account_conflict': + return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`; + case 'riot_account_lookup_failed': + return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'; + } + } +} diff --git a/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts b/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts new file mode 100644 index 00000000..5ad7235a --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts @@ -0,0 +1,138 @@ +import { BadRequestException } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { MatchService } from '../../match/match.service'; +import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; +import { MatchJoinHandler } from './match-join.handler'; + +const objectId = (hex: string) => new mongoose.Types.ObjectId(hex); + +function makeHandler(overrides?: { + matchService?: Partial; + dakaoUserService?: Partial; +}): MatchJoinHandler { + const matchService = { + join: jest.fn(), + ...overrides?.matchService, + } as unknown as MatchService; + const dakaoUserService = { + resolveRiotAccount: jest.fn(), + ...overrides?.dakaoUserService, + } as unknown as DakaoUserService; + return new MatchJoinHandler(matchService, dakaoUserService); +} + +const baseParams = { + communityId: objectId('111111111111111111111111'), + matchId: '69b63bc96da18dfdb218ee8c', + senderUserId: 'kakao-user-1', + senderNickname: '프리리', + gameName: '프리리', + tagLine: 'KR1', + positions: ['MID', 'TOP'] as const, +}; + +describe('MatchJoinHandler', () => { + it('rejects invalid match id without touching services', async () => { + const handler = makeHandler(); + const segments = await handler.handle({ + ...baseParams, + matchId: 'not-an-id', + positions: [...baseParams.positions], + }); + expect(segments).toEqual([ + expect.objectContaining({ kind: 'mention', userId: 'kakao-user-1' }), + expect.objectContaining({ + kind: 'text', + text: expect.stringContaining('유효하지 않은 내전 ID'), + }), + ]); + }); + + it('replies with success and uses input position priority', async () => { + const join = jest.fn().mockResolvedValue({ + title: '저녁 내전', + participants: [{}, {}, {}], + maxParticipants: 10, + }); + const resolveRiotAccount = jest.fn().mockResolvedValue({ + user: { _id: objectId('222222222222222222222222') }, + riotAccount: { puuid: 'puuid-1', gameName: '프리리', tagLine: 'KR1' }, + }); + const handler = makeHandler({ + matchService: { join } as Partial, + dakaoUserService: { + resolveRiotAccount, + } as Partial, + }); + + const segments = await handler.handle({ + ...baseParams, + positions: [...baseParams.positions], + }); + + expect(resolveRiotAccount).toHaveBeenCalledWith({ + communityId: baseParams.communityId, + kakaoTalkId: 'kakao-user-1', + kakaoTalkNickname: '프리리', + gameName: '프리리', + tagLine: 'KR1', + }); + expect(join).toHaveBeenCalledWith({ + matchId: expect.any(mongoose.Types.ObjectId), + userId: expect.any(mongoose.Types.ObjectId), + preferredPositions: [ + { position: 'MID', priority: 1 }, + { position: 'TOP', priority: 2 }, + ], + riotPuuid: 'puuid-1', + }); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('신청 완료 (3/10)'), + }); + }); + + it('translates riot_account_not_found errors', async () => { + const handler = makeHandler({ + dakaoUserService: { + resolveRiotAccount: jest + .fn() + .mockRejectedValue( + new DakaoUserError('riot_account_not_found', '프리리#KR1'), + ), + } as Partial, + }); + const segments = await handler.handle({ + ...baseParams, + positions: [...baseParams.positions], + }); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('라이엇 계정을 찾을 수 없습니다'), + }); + }); + + it('translates match BadRequest into korean', async () => { + const handler = makeHandler({ + matchService: { + join: jest + .fn() + .mockRejectedValue(new BadRequestException('Match is full.')), + } as Partial, + dakaoUserService: { + resolveRiotAccount: jest.fn().mockResolvedValue({ + user: { _id: objectId('222222222222222222222222') }, + riotAccount: { puuid: 'p', gameName: 'g', tagLine: 't' }, + }), + } as Partial, + }); + const segments = await handler.handle({ + ...baseParams, + positions: [...baseParams.positions], + }); + expect(segments[1]).toMatchObject({ + kind: 'text', + text: expect.stringContaining('정원이 가득'), + }); + }); +}); diff --git a/apps/api/src/modules/dakao/handlers/match-join.handler.ts b/apps/api/src/modules/dakao/handlers/match-join.handler.ts new file mode 100644 index 00000000..08ebb6d9 --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/match-join.handler.ts @@ -0,0 +1,128 @@ +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { MatchService } from '../../match/match.service'; +import { Position, PositionPreference } from '../../global/database/schema'; +import { DakaoSegment } from '../dakao.types'; +import { DakaoUserError, DakaoUserService } from '../dakao-user.service'; + +interface JoinHandlerParams { + communityId: mongoose.Types.ObjectId; + matchId: string; + senderUserId: string; // kakaoTalkId + senderNickname: string; // kakaoTalkNickname + gameName: string; + tagLine: string; + positions: Position[]; +} + +@Injectable() +export class MatchJoinHandler { + constructor( + private readonly matchService: MatchService, + private readonly dakaoUserService: DakaoUserService, + ) {} + + public async handle(params: JoinHandlerParams): Promise { + if (!mongoose.isValidObjectId(params.matchId)) { + return this.errorReply(params, '유효하지 않은 내전 ID 입니다.'); + } + const matchObjectId = new mongoose.Types.ObjectId(params.matchId); + + let resolved; + try { + resolved = await this.dakaoUserService.resolveRiotAccount({ + communityId: params.communityId, + kakaoTalkId: params.senderUserId, + kakaoTalkNickname: params.senderNickname, + gameName: params.gameName, + tagLine: params.tagLine, + }); + } catch (err) { + if (err instanceof DakaoUserError) { + return this.errorReply(params, this.translateUserError(err)); + } + throw err; + } + + const preferredPositions: PositionPreference[] = params.positions.map( + (position, index) => ({ position, priority: index + 1 }), + ); + + try { + const match = await this.matchService.join({ + matchId: matchObjectId, + userId: resolved.user._id, + preferredPositions, + riotPuuid: resolved.riotAccount.puuid, + }); + + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { + kind: 'text', + text: + ` 신청 완료 (${match.participants.length}/${match.maxParticipants})` + + `\n내전: ${match.title}` + + `\n계정: ${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}` + + `\n포지션: ${params.positions.join(', ')}`, + }, + ]; + } catch (err) { + if (err instanceof NotFoundException) { + return this.errorReply(params, '내전을 찾을 수 없습니다.'); + } + if (err instanceof BadRequestException) { + return this.errorReply(params, this.translateBadRequest(err.message)); + } + throw err; + } + } + + private errorReply( + params: JoinHandlerParams, + message: string, + ): DakaoSegment[] { + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { kind: 'text', text: ` ${message}` }, + ]; + } + + private translateUserError(err: DakaoUserError): string { + switch (err.code) { + case 'invalid_project_id': + return '커뮤니티 식별자가 올바르지 않습니다.'; + case 'community_not_found': + return '연결된 커뮤니티를 찾을 수 없습니다.'; + case 'riot_account_not_found': + return `라이엇 계정을 찾을 수 없습니다 (${err.detail ?? ''}).`; + case 'riot_account_already_registered': + return `이미 등록된 라이엇 계정이 있습니다 (${err.detail ?? ''}).`; + case 'riot_account_conflict': + return `이미 다른 사용자가 등록한 라이엇 계정입니다 (${err.detail ?? ''}).`; + case 'riot_account_lookup_failed': + return '라이엇 계정 조회 중 오류가 발생했습니다. 잠시 후 다시 시도해주세요.'; + } + } + + private translateBadRequest(raw: string): string { + if (raw.includes('different communities')) + return '이 내전은 현재 채팅방의 커뮤니티 소속이 아닙니다.'; + if (raw.includes('not recruiting')) return '모집 중인 내전이 아닙니다.'; + if (raw.includes('full')) return '정원이 가득 찼습니다.'; + if (raw.includes('already joined')) return '이미 신청한 내전입니다.'; + return raw; + } +} diff --git a/apps/api/src/modules/dakao/handlers/match-list.handler.ts b/apps/api/src/modules/dakao/handlers/match-list.handler.ts new file mode 100644 index 00000000..23746ed6 --- /dev/null +++ b/apps/api/src/modules/dakao/handlers/match-list.handler.ts @@ -0,0 +1,63 @@ +import { Injectable } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { MatchService } from '../../match/match.service'; +import { DakaoSegment } from '../dakao.types'; + +@Injectable() +export class MatchListHandler { + constructor(private readonly matchService: MatchService) {} + + public async handle(params: { + communityId: mongoose.Types.ObjectId; + senderUserId: string; + senderNickname: string; + }): Promise { + const matches = await this.matchService.list({ + communityId: params.communityId, + status: 'recruiting', + limit: 10, + }); + + if (matches.length === 0) { + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { kind: 'text', text: ' 모집 중인 내전이 없습니다.' }, + ]; + } + + const lines = matches.map((m, i) => { + const id = (m._id as mongoose.Types.ObjectId).toString(); + const filled = m.participants.length; + const cap = m.maxParticipants; + const time = formatScheduledAt(m.scheduledAt); + return `\n${i + 1}. ${m.title} (${filled}/${cap}) ${time}\n ID: ${id}`; + }); + + return [ + { + kind: 'mention', + userId: params.senderUserId, + displayText: params.senderNickname, + }, + { + kind: 'text', + text: ` 모집 중인 내전 ${matches.length}건${lines.join('')}\n계정등록: !내전 계정등록 <닉네임>#<태그>\n신청: !내전 신청 <닉네임>#<태그> <포지션1>,<포지션2>`, + }, + ]; + } +} + +function formatScheduledAt(date: Date): string { + // YYYY-MM-DD HH:mm (KST 표기) + const kst = new Date(date.getTime() + 9 * 60 * 60 * 1000); + const yyyy = kst.getUTCFullYear(); + const mm = String(kst.getUTCMonth() + 1).padStart(2, '0'); + const dd = String(kst.getUTCDate()).padStart(2, '0'); + const hh = String(kst.getUTCHours()).padStart(2, '0'); + const mi = String(kst.getUTCMinutes()).padStart(2, '0'); + return `${yyyy}-${mm}-${dd} ${hh}:${mi}`; +} diff --git a/apps/api/src/modules/dakao/idempotency.cache.ts b/apps/api/src/modules/dakao/idempotency.cache.ts new file mode 100644 index 00000000..01dffeca --- /dev/null +++ b/apps/api/src/modules/dakao/idempotency.cache.ts @@ -0,0 +1,35 @@ +import { Injectable } from '@nestjs/common'; + +const TTL_MS = 5 * 60 * 1000; +const MAX_ENTRIES = 5000; + +@Injectable() +export class IdempotencyCache { + private readonly entries = new Map(); + + public has(key: string): boolean { + const expiresAt = this.entries.get(key); + if (expiresAt === undefined) return false; + if (expiresAt < Date.now()) { + this.entries.delete(key); + return false; + } + return true; + } + + public remember(key: string): void { + this.evictExpired(); + if (this.entries.size >= MAX_ENTRIES) { + const oldestKey = this.entries.keys().next().value; + if (oldestKey !== undefined) this.entries.delete(oldestKey); + } + this.entries.set(key, Date.now() + TTL_MS); + } + + private evictExpired(): void { + const now = Date.now(); + for (const [key, expiresAt] of this.entries) { + if (expiresAt < now) this.entries.delete(key); + } + } +} diff --git a/apps/api/src/modules/dakao/parsers/command.parser.spec.ts b/apps/api/src/modules/dakao/parsers/command.parser.spec.ts new file mode 100644 index 00000000..2b11818c --- /dev/null +++ b/apps/api/src/modules/dakao/parsers/command.parser.spec.ts @@ -0,0 +1,95 @@ +import { CommandParseError, parseCommand } from './command.parser'; + +describe('parseCommand', () => { + it('parses match-list command (목록)', () => { + expect(parseCommand('!내전 목록')).toEqual({ kind: 'match-list' }); + }); + + it('parses match-list command (리스트)', () => { + expect(parseCommand('!내전 리스트')).toEqual({ kind: 'match-list' }); + }); + + it('parses match-join command with simple riot id', () => { + const result = parseCommand( + '!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드,탑', + ); + expect(result).toMatchObject({ + kind: 'match-join', + matchId: '69b63bc96da18dfdb218ee8c', + gameName: '프리리', + tagLine: 'KR1', + }); + if (result.kind === 'match-join') { + expect(result.positions.positions).toEqual(['MID', 'TOP']); + } + }); + + it('handles riot game name with spaces', () => { + const result = parseCommand( + '!내전 신청 69b63bc96da18dfdb218ee8c hello world#KR1 미드,서폿', + ); + expect(result).toMatchObject({ + kind: 'match-join', + gameName: 'hello world', + tagLine: 'KR1', + }); + }); + + it('normalizes hidden unicode differences in riot id', () => { + const decomposedGameName = '프리리'.normalize('NFD'); + const result = parseCommand( + `!내전 신청 69b63bc96da18dfdb218ee8c ${decomposedGameName}\u200B#KR1\uFEFF 미드,탑`, + ); + + expect(result).toMatchObject({ + kind: 'match-join', + gameName: '프리리', + tagLine: 'KR1', + }); + }); + + it('parses account register command', () => { + expect(parseCommand('!내전 계정등록 hello world#KR1')).toEqual({ + kind: 'account-register', + gameName: 'hello world', + tagLine: 'KR1', + }); + }); + + it('normalizes account register riot id', () => { + const decomposedGameName = '프리리'.normalize('NFD'); + expect( + parseCommand(`!내전 계정등록 ${decomposedGameName}\u200B#KR1\uFEFF`), + ).toEqual({ + kind: 'account-register', + gameName: '프리리', + tagLine: 'KR1', + }); + }); + + it('throws not_a_command for non-prefix messages', () => { + expect(() => parseCommand('안녕하세요')).toThrow(/not_a_command/); + }); + + it('throws unknown_command for unrecognized subcommands', () => { + expect(() => parseCommand('!내전 폭파')).toThrow(/unknown_command/); + }); + + it('throws invalid_match_id for non-objectid match', () => { + expect(() => + parseCommand('!내전 신청 not-an-id 프리리#KR1 미드,탑'), + ).toThrow(/invalid_match_id/); + }); + + it('throws invalid_riot_id when # missing', () => { + expect(() => + parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리 미드,탑'), + ).toThrow(/invalid_riot_id/); + }); + + it('throws invalid_position for too few positions', () => { + expect(() => { + parseCommand('!내전 신청 69b63bc96da18dfdb218ee8c 프리리#KR1 미드'); + }).toThrow(CommandParseError); + }); +}); diff --git a/apps/api/src/modules/dakao/parsers/command.parser.ts b/apps/api/src/modules/dakao/parsers/command.parser.ts new file mode 100644 index 00000000..5bc9bd04 --- /dev/null +++ b/apps/api/src/modules/dakao/parsers/command.parser.ts @@ -0,0 +1,147 @@ +import { ParsedPositions, parsePositionList } from './position.parser'; +import { normalizeRiotIdPart } from '../riot-id.util'; + +export type DakaoCommand = + | { kind: 'match-list' } + | { + kind: 'account-register'; + gameName: string; + tagLine: string; + } + | { + kind: 'match-join'; + matchId: string; + gameName: string; + tagLine: string; + positions: ParsedPositions; + }; + +export class CommandParseError extends Error { + constructor( + public readonly code: + | 'not_a_command' + | 'unknown_command' + | 'usage' + | 'invalid_riot_id' + | 'invalid_position' + | 'invalid_match_id', + public readonly detail?: string, + ) { + super(`Command parse error: ${code}${detail ? ` (${detail})` : ''}`); + } +} + +const COMMAND_PREFIX = '!내전'; + +export function parseCommand(rawMessage: string): DakaoCommand { + const message = rawMessage.trim(); + if (!message.startsWith(COMMAND_PREFIX)) { + throw new CommandParseError('not_a_command'); + } + + const rest = message.slice(COMMAND_PREFIX.length).trim(); + if (rest.length === 0) { + throw new CommandParseError('usage'); + } + + const firstSpace = rest.search(/\s/); + const subCommand = firstSpace === -1 ? rest : rest.slice(0, firstSpace); + const args = firstSpace === -1 ? '' : rest.slice(firstSpace + 1).trim(); + + switch (subCommand) { + case '목록': + case '리스트': + return { kind: 'match-list' }; + case '신청': + return parseJoinArgs(args); + case '계정등록': + return parseAccountRegisterArgs(args); + default: + throw new CommandParseError('unknown_command', subCommand); + } +} + +function parseAccountRegisterArgs(args: string): DakaoCommand { + if (args.length === 0) { + throw new CommandParseError('usage'); + } + + const hashIndex = args.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === args.length - 1) { + throw new CommandParseError('invalid_riot_id', args); + } + + const gameName = normalizeRiotIdPart(args.slice(0, hashIndex)); + const tagLine = normalizeRiotIdPart(args.slice(hashIndex + 1)); + if (gameName.length === 0 || tagLine.length === 0) { + throw new CommandParseError('invalid_riot_id', args); + } + + return { + kind: 'account-register', + gameName, + tagLine, + }; +} + +function parseJoinArgs(args: string): DakaoCommand { + if (args.length === 0) { + throw new CommandParseError('usage'); + } + + // 마지막 토큰이 포지션 리스트(쉼표 포함). 그 앞이 라이엇 ID(공백 포함 가능). 그 앞이 matchId. + // 형식: # ,... + // 끝에서부터 토큰을 분리해 안정적으로 파싱한다. + const lastSpace = args.lastIndexOf(' '); + if (lastSpace === -1) { + throw new CommandParseError('usage'); + } + const positionPart = args.slice(lastSpace + 1).trim(); + const head = args.slice(0, lastSpace).trim(); + if (positionPart.length === 0 || head.length === 0) { + throw new CommandParseError('usage'); + } + + const headSpace = head.indexOf(' '); + if (headSpace === -1) { + throw new CommandParseError('usage'); + } + const matchId = head.slice(0, headSpace).trim(); + const riotId = head.slice(headSpace + 1).trim(); + + if (!isObjectIdHex(matchId)) { + throw new CommandParseError('invalid_match_id', matchId); + } + + const hashIndex = riotId.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === riotId.length - 1) { + throw new CommandParseError('invalid_riot_id', riotId); + } + const gameName = normalizeRiotIdPart(riotId.slice(0, hashIndex)); + const tagLine = normalizeRiotIdPart(riotId.slice(hashIndex + 1)); + if (gameName.length === 0 || tagLine.length === 0) { + throw new CommandParseError('invalid_riot_id', riotId); + } + + let positions: ParsedPositions; + try { + positions = parsePositionList(positionPart); + } catch (err) { + throw new CommandParseError( + 'invalid_position', + (err as Error)?.message ?? positionPart, + ); + } + + return { + kind: 'match-join', + matchId, + gameName, + tagLine, + positions, + }; +} + +function isObjectIdHex(value: string): boolean { + return /^[a-f0-9]{24}$/i.test(value); +} diff --git a/apps/api/src/modules/dakao/parsers/position.parser.spec.ts b/apps/api/src/modules/dakao/parsers/position.parser.spec.ts new file mode 100644 index 00000000..0a808b57 --- /dev/null +++ b/apps/api/src/modules/dakao/parsers/position.parser.spec.ts @@ -0,0 +1,41 @@ +import { parsePositionList, PositionParseError } from './position.parser'; + +describe('parsePositionList', () => { + it('parses two korean positions in priority order', () => { + const result = parsePositionList('미드,탑'); + expect(result.positions).toEqual(['MID', 'TOP']); + }); + + it('parses english aliases case-insensitively', () => { + const result = parsePositionList('JGL, sup'); + expect(result.positions).toEqual(['JGL', 'SUP']); + }); + + it('accepts up to 5 distinct positions', () => { + const result = parsePositionList('탑,정글,미드,원딜,서폿'); + expect(result.positions).toEqual(['TOP', 'JGL', 'MID', 'ADC', 'SUP']); + }); + + it('rejects when fewer than 2 positions', () => { + expect(() => parsePositionList('미드')).toThrow(PositionParseError); + expect(() => parsePositionList('미드')).toThrow(/too_few/); + }); + + it('rejects when more than 5 positions', () => { + expect(() => parsePositionList('탑,정글,미드,원딜,서폿,바텀')).toThrow( + /too_many/, + ); + }); + + it('rejects duplicates after alias normalization', () => { + expect(() => parsePositionList('미드,mid')).toThrow(/duplicate/); + }); + + it('rejects unknown tokens', () => { + expect(() => parsePositionList('미드,캐리')).toThrow(/unknown/); + }); + + it('rejects empty input', () => { + expect(() => parsePositionList('')).toThrow(/empty/); + }); +}); diff --git a/apps/api/src/modules/dakao/parsers/position.parser.ts b/apps/api/src/modules/dakao/parsers/position.parser.ts new file mode 100644 index 00000000..8d62acce --- /dev/null +++ b/apps/api/src/modules/dakao/parsers/position.parser.ts @@ -0,0 +1,87 @@ +import { Position } from '../../global/database/schema'; + +const POSITION_ALIASES: Record = { + // TOP + top: 'TOP', + 탑: 'TOP', + top레인: 'TOP', + // JUNGLE + jgl: 'JGL', + jungle: 'JGL', + jng: 'JGL', + jg: 'JGL', + 정글: 'JGL', + 정글러: 'JGL', + // MID + mid: 'MID', + middle: 'MID', + 미드: 'MID', + // ADC (BOTTOM) + adc: 'ADC', + ad: 'ADC', + bot: 'ADC', + bottom: 'ADC', + 원딜: 'ADC', + 바텀: 'ADC', + // SUP + sup: 'SUP', + supp: 'SUP', + support: 'SUP', + 서폿: 'SUP', + 서포터: 'SUP', +}; + +export interface ParsedPositions { + positions: Position[]; +} + +export class PositionParseError extends Error { + constructor( + public readonly reason: + | 'too_few' + | 'too_many' + | 'duplicate' + | 'unknown' + | 'empty', + public readonly token?: string, + ) { + super(`Position parse error: ${reason}${token ? ` (${token})` : ''}`); + } +} + +export function parsePositionList(input: string): ParsedPositions { + const trimmed = input.trim(); + if (trimmed.length === 0) { + throw new PositionParseError('empty'); + } + + const tokens = trimmed + .split(',') + .map((t) => t.trim()) + .filter((t) => t.length > 0); + + if (tokens.length < 2) { + throw new PositionParseError('too_few'); + } + if (tokens.length > 5) { + throw new PositionParseError('too_many'); + } + + const positions: Position[] = []; + const seen = new Set(); + + for (const token of tokens) { + const key = token.toLowerCase().replace(/\s+/g, ''); + const mapped = POSITION_ALIASES[key]; + if (!mapped) { + throw new PositionParseError('unknown', token); + } + if (seen.has(mapped)) { + throw new PositionParseError('duplicate', token); + } + seen.add(mapped); + positions.push(mapped); + } + + return { positions }; +} diff --git a/apps/api/src/modules/dakao/riot-id.util.ts b/apps/api/src/modules/dakao/riot-id.util.ts new file mode 100644 index 00000000..2a54240b --- /dev/null +++ b/apps/api/src/modules/dakao/riot-id.util.ts @@ -0,0 +1,14 @@ +const ZERO_WIDTH_CHARACTERS = /[\u200B-\u200D\uFEFF]/g; + +export function normalizeRiotIdPart(value: string): string { + return value.replace(ZERO_WIDTH_CHARACTERS, '').trim().normalize('NFC'); +} + +export function formatCodePoints(value: string): string { + return Array.from(value) + .map((char) => { + const codePoint = char.codePointAt(0); + return `U+${codePoint?.toString(16).toUpperCase().padStart(4, '0')}`; + }) + .join(' '); +} 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(); + } +} diff --git a/apps/api/src/modules/legacy-import/legacy-import.controller.ts b/apps/api/src/modules/legacy-import/legacy-import.controller.ts new file mode 100644 index 00000000..6df3f88b --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.controller.ts @@ -0,0 +1,150 @@ +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, + }); + } + + @Post('legacy-matches/rebuild') + public rebuildLegacyMatches( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.legacyImportService.rebuildLegacyMatches({ communityId }); + } + + 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; + } +} diff --git a/apps/api/src/modules/legacy-import/legacy-import.module.ts b/apps/api/src/modules/legacy-import/legacy-import.module.ts new file mode 100644 index 00000000..9bd9ad80 --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.module.ts @@ -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 {} diff --git a/apps/api/src/modules/legacy-import/legacy-import.service.ts b/apps/api/src/modules/legacy-import/legacy-import.service.ts new file mode 100644 index 00000000..a56c3210 --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.service.ts @@ -0,0 +1,775 @@ +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 RebuildLegacyMatchesResponse, + 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 { + 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 { + 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 { + 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() } }, + { returnDocument: 'after' }, + ).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 { + 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 { + const MatchModel = await this.connectionService.getModel('match'); + const limit = Math.max(1, Math.min(params.limit ?? 30, 100)); + const filter: Record = { + 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 }; + } + + public async rebuildLegacyMatches(params: { + communityId: mongoose.Types.ObjectId; + }): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const matches = await MatchModel.find({ + communityId: params.communityId, + legacyImported: true, + }).exec(); + const riotMatchIds = matches + .map( + (match) => + match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0], + ) + .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(); + for (const doc of rawDocs) { + if (isRiotMatchDto(doc.raw)) rawById.set(doc.matchId, doc.raw); + } + + const userByPuuid = await this.buildUserByPuuidMap(params.communityId); + const result: RebuildLegacyMatchesResponse = { + scanned: matches.length, + rebuilt: 0, + normalizedTitles: 0, + skippedMissingRaw: 0, + skippedNoKnownParticipants: 0, + }; + + for (const match of matches) { + const riotMatchId = + match.result?.games[0]?.riotMatchId ?? match.result?.riotMatchIds?.[0]; + const raw = riotMatchId ? rawById.get(riotMatchId) : undefined; + const title = this.normalizeLegacyTitle( + match.title, + raw?.info.gameCreation ?? match.scheduledAt.getTime(), + ); + const update: Partial = {}; + if (title !== match.title) { + update.title = title; + result.normalizedTitles += 1; + } + + if (!raw || !riotMatchId) { + result.skippedMissingRaw += 1; + if (Object.keys(update).length > 0) { + await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec(); + } + continue; + } + + const team100IsBlue = resolveTeam100IsBlue(raw, userByPuuid); + const participants = buildParticipantsSnapshot(raw, userByPuuid); + const gameResult = buildGameResult(raw, userByPuuid, team100IsBlue, 1); + if (!gameResult || participants.length === 0) { + result.skippedNoKnownParticipants += 1; + if (Object.keys(update).length > 0) { + await MatchModel.updateOne({ _id: match._id }, { $set: update }).exec(); + } + continue; + } + + const winnerSide = gameResult.winnerSide; + update.mapId = raw.info.mapId ?? match.mapId; + update.participants = participants; + update.teams = buildTeams(raw, userByPuuid, team100IsBlue); + update.result = { + winnerSide, + blueScore: winnerSide === 'blue' ? 1 : 0, + redScore: winnerSide === 'red' ? 1 : 0, + riotMatchIds: [riotMatchId], + games: [gameResult], + }; + + await MatchModel.updateOne( + { + _id: match._id, + communityId: params.communityId, + legacyImported: true, + }, + { $set: update }, + ).exec(); + result.rebuilt += 1; + } + + if (result.rebuilt > 0 || result.normalizedTitles > 0) { + await this.communityStatsService.invalidateCommunity(params.communityId); + } + + return result; + } + + private async collectMatchIds(job: LegacyImportMemberJob): Promise> { + const matchIds = new Set(); + 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 { + 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 = { + communityId: new mongoose.Types.ObjectId(job.communityId), + title: 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 { + 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 = { + 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, + 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 { + 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 { + 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 { + 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 { + 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 { + const users = await this.findImportableUsers(communityId); + return buildUserByPuuidMap(users); + } + + private async findImportableUsers( + communityId: mongoose.Types.ObjectId, + ): Promise { + 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, + ) { + 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 = overrideStart ?? windowStart; + 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 minDate(...values: Array): Date { + return new Date(Math.min(...values.filter(Boolean).map((date) => date!.getTime()))); + } + + private normalizeLegacyTitle(title: string, gameCreation: number): string { + const stripped = title.replace(/^\[(?:legacy|lagacy)\]\s*/i, '').trim(); + return stripped || this.formatLegacyDate(gameCreation); + } + + 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, + ); +} diff --git a/apps/api/src/modules/legacy-import/legacy-import.types.ts b/apps/api/src/modules/legacy-import/legacy-import.types.ts new file mode 100644 index 00000000..e1559b30 --- /dev/null +++ b/apps/api/src/modules/legacy-import/legacy-import.types.ts @@ -0,0 +1,75 @@ +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[]; +} + +export interface RebuildLegacyMatchesResponse { + scanned: number; + rebuilt: number; + normalizedTitles: number; + skippedMissingRaw: number; + skippedNoKnownParticipants: number; +} diff --git a/apps/api/src/modules/legacy-import/match-builder.util.ts b/apps/api/src/modules/legacy-import/match-builder.util.ts new file mode 100644 index 00000000..e60d67d6 --- /dev/null +++ b/apps/api/src/modules/legacy-import/match-builder.util.ts @@ -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; + +export function buildUserByPuuidMap(users: UserDocument[]): UserByPuuidMap { + const entries = new Map(); + 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 => 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 => + 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'; +} diff --git a/apps/api/src/modules/match-history/match-history.controller.ts b/apps/api/src/modules/match-history/match-history.controller.ts new file mode 100644 index 00000000..29d142ca --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.controller.ts @@ -0,0 +1,123 @@ +import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { ParseObjectIdPipe } from '../common/parse-object-id.pipe'; +import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service'; +import type { + RiotJobPriority, +} from '../riot-job-queue/riot-job-queue.types'; +import { MatchHistoryService } from './match-history.service'; + +interface RefreshBody { + queueGroups?: string[]; + priority?: RiotJobPriority; +} + +@Controller('communities/:communityId/users/:userId') +export class MatchHistoryController { + constructor( + private readonly matchHistoryService: MatchHistoryService, + private readonly riotJobQueueService: RiotJobQueueService, + ) {} + + @Get('history-profile') + @AllowPublicAccess() + public getProfile( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + ) { + return this.matchHistoryService.getProfile({ communityId, userId }); + } + + @Get('champion-stats') + @AllowPublicAccess() + public getChampionStats( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Query('queueGroup') queueGroup?: string, + @Query('rank') rank?: string, + @Query('seasonId') seasonId?: string, + ) { + return this.matchHistoryService.getChampionStats({ + communityId, + userId, + filters: { queueGroup, rank, seasonId }, + }); + } + + @Get('recent-summary') + @AllowPublicAccess() + public getRecentSummary( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Query('queueGroup') queueGroup?: string, + @Query('rank') rank?: string, + @Query('seasonId') seasonId?: string, + @Query('championId') championId?: string, + @Query('limit') limit?: string, + ) { + return this.matchHistoryService.getRecentSummary({ + communityId, + userId, + filters: { + queueGroup, + rank, + seasonId, + championId: this.toNumber(championId), + limit: this.toNumber(limit), + }, + }); + } + + @Get('recent-matches') + @AllowPublicAccess() + public getRecentMatches( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Query('queueGroup') queueGroup?: string, + @Query('rank') rank?: string, + @Query('seasonId') seasonId?: string, + @Query('championId') championId?: string, + @Query('limit') limit?: string, + @Query('cursor') cursor?: string, + ) { + return this.matchHistoryService.getRecentMatches({ + communityId, + userId, + filters: { + queueGroup, + rank, + seasonId, + championId: this.toNumber(championId), + limit: this.toNumber(limit), + cursor: this.toNumber(cursor), + }, + }); + } + + @Post('refresh') + @AllowPublicAccess() + public refresh( + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('userId', ParseObjectIdPipe) userId: mongoose.Types.ObjectId, + @Body() body: RefreshBody, + ) { + return this.riotJobQueueService.enqueueRefresh({ + communityId, + userId, + queueGroups: body.queueGroups ?? ['summoners-rift'], + priority: body.priority ?? 'high', + }); + } + + private toNumber(value: string | undefined): number | undefined { + if (!value) return undefined; + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : undefined; + } +} diff --git a/apps/api/src/modules/match-history/match-history.module.ts b/apps/api/src/modules/match-history/match-history.module.ts new file mode 100644 index 00000000..062b1286 --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.module.ts @@ -0,0 +1,12 @@ +import { Module } from '@nestjs/common'; +import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module'; +import { MatchHistoryController } from './match-history.controller'; +import { MatchHistoryService } from './match-history.service'; + +@Module({ + imports: [RiotJobQueueModule], + controllers: [MatchHistoryController], + providers: [MatchHistoryService], + exports: [MatchHistoryService], +}) +export class MatchHistoryModule {} diff --git a/apps/api/src/modules/match-history/match-history.service.ts b/apps/api/src/modules/match-history/match-history.service.ts new file mode 100644 index 00000000..43a9644c --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.service.ts @@ -0,0 +1,753 @@ +import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + CommunityDocument, + RiotAccount, + RiotLane, + RiotMatchDocument, + UserDocument, +} from '../global/database/schema'; +import { + isRiotQueueGroup, + isRiotRankFilter, + RIOT_QUEUE_LABELS, + resolveRiotQueueIds, + type RiotQueueGroup, + type RiotRankFilter, +} from '../riot/riot-queue.constants'; +import type { + RiotMatchDto, + RiotMatchParticipantDto, +} from '../riot/riot.types'; +import type { + ChampionStatsResponse, + ChampionStatsRow, + HistorySeasonDto, + RecentMatchesResponse, + RecentMatchView, + RecentSummaryResponse, + UserHistoryProfileResponse, +} from './match-history.types'; + +const DEFAULT_QUEUE_GROUP: RiotQueueGroup = 'summoners-rift'; +const DEFAULT_RANK: RiotRankFilter = 'all'; +const DEFAULT_RECENT_LIMIT = 10; +const DEFAULT_SUMMARY_LIMIT = 20; +const MAX_AGGREGATE_MATCHES = 500; +const MAX_RECENT_SCAN = 120; + +interface HistoryContext { + community: CommunityDocument; + user: UserDocument; + account: RiotAccount; + season: HistorySeasonDto; + seasonStartedAt: Date | null; +} + +interface MatchFilters { + queueGroup?: string; + rank?: string; + seasonId?: string; + championId?: number; + limit?: number; + cursor?: number; +} + +interface AggregatedChampion { + championId: number; + games: number; + wins: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + totalCs: number; + totalGameMinutes: number; + doubleKills: number; + tripleKills: number; + quadraKills: number; + pentaKills: number; +} + +@Injectable() +export class MatchHistoryService { + constructor(private readonly connectionService: ConnectionService) {} + + public async getProfile(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + }): Promise { + const context = await this.resolveContext(params); + const lastFetchedAt = + context.account.recentStatsFetchedAt ?? + context.account.matchIdsFetchedAt ?? + null; + + return { + userId: context.user._id.toString(), + puuid: context.account.puuid, + gameName: context.account.gameName, + tagLine: context.account.tagLine, + profileIconId: context.account.profileIconId, + summonerLevel: context.account.summonerLevel, + tiers: context.account.tiers.map((tier) => ({ + queueType: tier.queueType, + tier: tier.tier, + rank: tier.rank, + leaguePoints: tier.leaguePoints, + wins: tier.wins, + losses: tier.losses, + fetchedAt: tier.fetchedAt.toISOString(), + })), + season: context.season, + seasons: this.resolveSeasons(context.community), + lastFetchedAt: lastFetchedAt?.toISOString() ?? null, + }; + } + + public async getChampionStats(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: MatchFilters; + }): Promise { + const context = await this.resolveContext({ + ...params, + seasonId: params.filters.seasonId, + }); + const { queueGroup, rank, queueIds } = this.resolveQueueFilters( + params.filters, + ); + const docs = await this.findStoredMatches({ + context, + queueIds, + limit: MAX_AGGREGATE_MATCHES, + }); + const aggregates = new Map(); + + for (const doc of docs) { + const dto = doc.raw as unknown as RiotMatchDto; + const participant = this.findParticipant(dto, context.account.puuid); + if (!participant) continue; + const aggregate = + aggregates.get(participant.championId) ?? + this.createChampionAggregate(participant.championId); + this.addParticipantToChampionAggregate(aggregate, participant, dto); + aggregates.set(participant.championId, aggregate); + } + + const champions = [...aggregates.values()] + .map((aggregate) => this.toChampionStatsRow(aggregate)) + .sort((a, b) => b.games - a.games || b.winRate - a.winRate); + const totals = this.toChampionStatsRow( + [...aggregates.values()].reduce( + (acc, aggregate) => this.mergeChampionAggregate(acc, aggregate), + this.createChampionAggregate(0), + ), + ); + + return { + queueGroup, + rank, + queueIds, + season: context.season, + lastFetchedAt: this.resolveLastFetchedAt(docs, context), + champions, + totals, + }; + } + + public async getRecentSummary(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: MatchFilters; + }): Promise { + const context = await this.resolveContext({ + ...params, + seasonId: params.filters.seasonId, + }); + const { queueIds } = this.resolveQueueFilters(params.filters); + const limit = this.clampLimit(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50); + const docs = await this.findStoredMatches({ + context, + queueIds, + championId: params.filters.championId, + limit, + scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined, + }); + const views = docs + .map((doc) => this.toRecentMatchView(doc, context.account.puuid)) + .filter((view): view is RecentMatchView => Boolean(view)) + .slice(0, limit); + + return this.createRecentSummary(views, docs, context, limit); + } + + public async getRecentMatches(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + filters: MatchFilters; + }): Promise { + const context = await this.resolveContext({ + ...params, + seasonId: params.filters.seasonId, + }); + const { queueIds } = this.resolveQueueFilters(params.filters); + const limit = this.clampLimit(params.filters.limit, DEFAULT_RECENT_LIMIT, 30); + const docs = await this.findStoredMatches({ + context, + queueIds, + championId: params.filters.championId, + limit: limit + 1, + cursor: params.filters.cursor, + scanLimit: params.filters.championId ? MAX_RECENT_SCAN : undefined, + }); + const views = docs + .map((doc) => this.toRecentMatchView(doc, context.account.puuid)) + .filter((view): view is RecentMatchView => Boolean(view)); + const page = views.slice(0, limit); + + return { + matches: page, + nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null, + lastFetchedAt: this.resolveLastFetchedAt(docs, context), + season: context.season, + }; + } + + private async resolveContext(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + seasonId?: string; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const CommunityModel = await this.connectionService.getModel('community'); + const [user, community] = await Promise.all([ + UserModel.findById(params.userId).exec(), + CommunityModel.findById(params.communityId).exec(), + ]); + + if (!community) throw new NotFoundException('Community not found.'); + if (!user || !user.communityId.equals(params.communityId)) { + throw new NotFoundException('User not found.'); + } + + const account = + user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ?? + user.riotAccounts[0]; + if (!account) { + throw new NotFoundException('Riot account not found.'); + } + + const season = this.resolveSeason(community, params.seasonId); + const seasonStartedAt = season.startedAt + ? new Date(season.startedAt) + : (community.seasonStartedAt ?? null); + return { community, user, account, season, seasonStartedAt }; + } + + private resolveSeason( + community: CommunityDocument, + seasonId?: string, + ): HistorySeasonDto { + const seasons = this.resolveSeasons(community); + if (seasonId && seasonId !== 'current') { + const selected = seasons.find((season) => season.id === seasonId); + if (!selected) throw new BadRequestException('Invalid seasonId.'); + return selected; + } + + const configured = + seasons.find((season) => !season.endedAt) ?? + [...seasons].sort((left, right) => + (right.startedAt ?? '').localeCompare(left.startedAt ?? ''), + )[0]; + + if (configured) return configured; + + return { + id: 'current', + label: '현재 시즌', + startedAt: community.seasonStartedAt?.toISOString() ?? null, + endedAt: null, + }; + } + + private resolveSeasons(community: CommunityDocument): HistorySeasonDto[] { + const configured = community.seasons?.map((season) => ({ + id: season.id, + label: season.label, + startedAt: season.startedAt.toISOString(), + endedAt: season.endedAt?.toISOString() ?? null, + })); + + if (configured?.length) return configured; + + return [ + { + id: 'current', + label: '현재 시즌', + startedAt: community.seasonStartedAt?.toISOString() ?? null, + endedAt: null, + }, + ]; + } + + private resolveQueueFilters(filters: MatchFilters): { + queueGroup: RiotQueueGroup; + rank: RiotRankFilter; + queueIds: number[]; + } { + const queueGroup = filters.queueGroup ?? DEFAULT_QUEUE_GROUP; + const rank = filters.rank ?? DEFAULT_RANK; + if (!isRiotQueueGroup(queueGroup)) { + throw new BadRequestException('Invalid queueGroup.'); + } + if (!isRiotRankFilter(rank)) { + throw new BadRequestException('Invalid rank filter.'); + } + return { + queueGroup, + rank, + queueIds: resolveRiotQueueIds(queueGroup, rank), + }; + } + + private async findStoredMatches(params: { + context: HistoryContext; + queueIds: number[]; + limit: number; + cursor?: number; + championId?: number; + scanLimit?: number; + }): Promise { + if (params.queueIds.length === 0) return []; + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const gameCreation: Record = {}; + if (params.context.seasonStartedAt) { + gameCreation.$gte = params.context.seasonStartedAt.getTime(); + } + if (params.cursor) gameCreation.$lt = params.cursor; + + const query: Record = { + participantPuuids: params.context.account.puuid, + queueId: { $in: params.queueIds }, + }; + if (Object.keys(gameCreation).length > 0) query.gameCreation = gameCreation; + + const docs = await RiotMatchModel.find(query) + .sort({ gameCreation: -1 }) + .limit(params.scanLimit ?? params.limit) + .exec(); + + if (!params.championId) return docs.slice(0, params.limit); + return docs + .filter((doc) => { + const participant = this.findParticipant( + doc.raw as unknown as RiotMatchDto, + params.context.account.puuid, + ); + return participant?.championId === params.championId; + }) + .slice(0, params.limit); + } + + private findParticipant( + match: RiotMatchDto, + puuid: string, + ): RiotMatchParticipantDto | null { + return ( + match.info.participants.find((participant) => participant.puuid === puuid) ?? + null + ); + } + + private createChampionAggregate(championId: number): AggregatedChampion { + return { + championId, + games: 0, + wins: 0, + totalKills: 0, + totalDeaths: 0, + totalAssists: 0, + totalCs: 0, + totalGameMinutes: 0, + doubleKills: 0, + tripleKills: 0, + quadraKills: 0, + pentaKills: 0, + }; + } + + private addParticipantToChampionAggregate( + aggregate: AggregatedChampion, + participant: RiotMatchParticipantDto, + match: RiotMatchDto, + ): void { + const minutes = this.resolveGameMinutes(match, participant); + aggregate.games += 1; + aggregate.wins += participant.win ? 1 : 0; + aggregate.totalKills += participant.kills; + aggregate.totalDeaths += participant.deaths; + aggregate.totalAssists += participant.assists; + aggregate.totalCs += this.resolveTotalCs(participant); + aggregate.totalGameMinutes += minutes; + aggregate.doubleKills += this.numberField(participant, 'doubleKills'); + aggregate.tripleKills += this.numberField(participant, 'tripleKills'); + aggregate.quadraKills += this.numberField(participant, 'quadraKills'); + aggregate.pentaKills += this.numberField(participant, 'pentaKills'); + } + + private mergeChampionAggregate( + acc: AggregatedChampion, + aggregate: AggregatedChampion, + ): AggregatedChampion { + acc.games += aggregate.games; + acc.wins += aggregate.wins; + acc.totalKills += aggregate.totalKills; + acc.totalDeaths += aggregate.totalDeaths; + acc.totalAssists += aggregate.totalAssists; + acc.totalCs += aggregate.totalCs; + acc.totalGameMinutes += aggregate.totalGameMinutes; + acc.doubleKills += aggregate.doubleKills; + acc.tripleKills += aggregate.tripleKills; + acc.quadraKills += aggregate.quadraKills; + acc.pentaKills += aggregate.pentaKills; + return acc; + } + + private toChampionStatsRow(aggregate: AggregatedChampion): ChampionStatsRow { + const losses = aggregate.games - aggregate.wins; + return { + championId: aggregate.championId, + games: aggregate.games, + wins: aggregate.wins, + losses, + winRate: this.percent(aggregate.wins, aggregate.games), + avgKills: this.average(aggregate.totalKills, aggregate.games), + avgDeaths: this.average(aggregate.totalDeaths, aggregate.games), + avgAssists: this.average(aggregate.totalAssists, aggregate.games), + kda: this.resolveKda( + aggregate.totalKills, + aggregate.totalDeaths, + aggregate.totalAssists, + ), + totalKills: aggregate.totalKills, + totalDeaths: aggregate.totalDeaths, + totalAssists: aggregate.totalAssists, + doubleKills: aggregate.doubleKills, + tripleKills: aggregate.tripleKills, + quadraKills: aggregate.quadraKills, + pentaKills: aggregate.pentaKills, + avgCs: this.average(aggregate.totalCs, aggregate.games), + avgCsPerMin: this.average(aggregate.totalCs, aggregate.totalGameMinutes), + }; + } + + private toRecentMatchView( + doc: RiotMatchDocument, + puuid: string, + ): RecentMatchView | null { + const dto = doc.raw as unknown as RiotMatchDto; + const participant = this.findParticipant(dto, puuid); + if (!participant) return null; + + const teamParticipants = dto.info.participants.filter( + (candidate) => candidate.teamId === participant.teamId, + ); + const teamKills = teamParticipants.reduce( + (sum, candidate) => sum + candidate.kills, + 0, + ); + const minutes = this.resolveGameMinutes(dto, participant); + const totalCs = this.resolveTotalCs(participant); + const damageShare = this.resolveDamageShare(dto, participant); + const rating = this.resolveRating({ + participant, + teamKills, + minutes, + damageShare, + }); + + return { + matchId: dto.metadata.matchId, + queueId: dto.info.queueId, + queueLabel: RIOT_QUEUE_LABELS[dto.info.queueId] ?? `큐 ${dto.info.queueId}`, + gameCreation: dto.info.gameCreation, + gameDuration: dto.info.gameDuration, + win: participant.win, + remake: + this.booleanField(participant, 'gameEndedInEarlySurrender') || + dto.info.gameDuration < 240, + championId: participant.championId, + championLevel: participant.champLevel, + teamPosition: participant.teamPosition || participant.individualPosition, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + kda: this.resolveKda( + participant.kills, + participant.deaths, + participant.assists, + ), + rating, + totalCs, + csPerMin: this.average(totalCs, minutes), + killParticipation: this.percent( + participant.kills + participant.assists, + teamKills, + ), + visionScore: participant.visionScore, + controlWardsBought: this.numberField( + participant, + 'visionWardsBoughtInGame', + ), + wardsPlaced: participant.wardsPlaced, + wardsKilled: participant.wardsKilled, + damageDealtToChampions: participant.totalDamageDealtToChampions, + damageTaken: participant.totalDamageTaken, + goldEarned: participant.goldEarned, + items: [ + participant.item0, + participant.item1, + participant.item2, + participant.item3, + participant.item4, + participant.item5, + ], + trinket: participant.item6, + summonerSpells: [participant.summoner1Id, participant.summoner2Id], + perks: this.resolvePerks(participant), + teams: this.resolveTeams(dto), + }; + } + + private createRecentSummary( + views: RecentMatchView[], + docs: RiotMatchDocument[], + context: HistoryContext, + requestedLimit: number, + ): RecentSummaryResponse { + const totals = views.reduce( + (acc, view) => { + acc.wins += view.win ? 1 : 0; + acc.kills += view.kills; + acc.deaths += view.deaths; + acc.assists += view.assists; + return acc; + }, + { wins: 0, kills: 0, deaths: 0, assists: 0 }, + ); + const losses = views.length - totals.wins; + const best = views.reduce((acc, view) => { + if (!acc) return view; + return view.deaths === 0 || view.rating > acc.rating ? view : acc; + }, null); + + return { + windowSize: Math.min(views.length, requestedLimit), + winRate: this.percent(totals.wins, views.length), + wins: totals.wins, + losses, + streak: this.resolveStreak(views), + kda: this.resolveKda(totals.kills, totals.deaths, totals.assists), + avgKills: this.average(totals.kills, views.length), + avgDeaths: this.average(totals.deaths, views.length), + avgAssists: this.average(totals.assists, views.length), + bestRating: best + ? { + rating: best.deaths === 0 ? 'Perfect' : best.rating, + kills: best.kills, + deaths: best.deaths, + assists: best.assists, + matchId: best.matchId, + } + : null, + positionRates: this.resolvePositionRates(views), + topChampions: this.resolveTopChampions(views), + lastFetchedAt: this.resolveLastFetchedAt(docs, context), + }; + } + + private resolveTeams(match: RiotMatchDto): RecentMatchView['teams'] { + return match.info.teams.map((team) => ({ + side: team.teamId as 100 | 200, + win: team.win, + objectives: { + baron: team.objectives?.baron?.kills, + dragon: team.objectives?.dragon?.kills, + tower: team.objectives?.tower?.kills, + }, + participants: match.info.participants + .filter((participant) => participant.teamId === team.teamId) + .map((participant) => ({ + puuid: participant.puuid, + gameName: participant.riotIdGameName || participant.summonerName || 'Unknown', + tagLine: participant.riotIdTagLine || '', + championId: participant.championId, + teamPosition: participant.teamPosition || participant.individualPosition, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + })), + })); + } + + private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] { + const primary = participant.perks.styles.find( + (style) => style.description === 'primaryStyle', + ); + const sub = participant.perks.styles.find( + (style) => style.description === 'subStyle', + ); + return { + primaryStyle: primary?.style, + subStyle: sub?.style, + keystone: primary?.selections[0]?.perk, + }; + } + + private resolvePositionRates( + views: RecentMatchView[], + ): Partial> { + const counts = new Map(); + for (const view of views) { + if (!view.teamPosition) continue; + counts.set(view.teamPosition, (counts.get(view.teamPosition) ?? 0) + 1); + } + return Object.fromEntries( + [...counts.entries()].map(([lane, count]) => [ + lane, + this.percent(count, views.length), + ]), + ) as Partial>; + } + + private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] { + const byChampion = new Map(); + for (const view of views) { + const stat = + byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 }; + stat.games += 1; + stat.wins += view.win ? 1 : 0; + stat.rating += view.rating; + byChampion.set(view.championId, stat); + } + return [...byChampion.entries()] + .map(([championId, stat]) => ({ + championId, + games: stat.games, + winRate: this.percent(stat.wins, stat.games), + pickRate: this.percent(stat.games, views.length), + avgRating: this.average(stat.rating, stat.games), + })) + .sort((a, b) => b.games - a.games || b.winRate - a.winRate) + .slice(0, 3); + } + + private resolveStreak( + views: RecentMatchView[], + ): RecentSummaryResponse['streak'] { + if (views.length === 0) return null; + const firstWin = views[0].win; + let count = 0; + for (const view of views) { + if (view.win !== firstWin) break; + count += 1; + } + return { type: firstWin ? 'win' : 'loss', count }; + } + + private resolveRating(params: { + participant: RiotMatchParticipantDto; + teamKills: number; + minutes: number; + damageShare: number; + }): number { + const { participant, teamKills, minutes, damageShare } = params; + const kda = this.resolveKda( + participant.kills, + participant.deaths, + participant.assists, + ); + const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0; + const csPerMin = this.resolveTotalCs(participant) / Math.max(minutes, 1); + const visionPerMin = participant.visionScore / Math.max(minutes, 1); + const score = + Math.min(kda / 6, 1) * 4 + + Math.min(kp, 1) * 2 + + Math.min(csPerMin / 9, 1) * 2 + + Math.min(damageShare / 0.35, 1) + + Math.min(visionPerMin / 2, 1); + return this.round(score); + } + + private resolveDamageShare( + match: RiotMatchDto, + participant: RiotMatchParticipantDto, + ): number { + const teamDamage = match.info.participants + .filter((candidate) => candidate.teamId === participant.teamId) + .reduce((sum, candidate) => sum + candidate.totalDamageDealtToChampions, 0); + return teamDamage > 0 ? participant.totalDamageDealtToChampions / teamDamage : 0; + } + + private resolveTotalCs(participant: RiotMatchParticipantDto): number { + return participant.totalMinionsKilled + participant.neutralMinionsKilled; + } + + private resolveGameMinutes( + match: RiotMatchDto, + participant: RiotMatchParticipantDto, + ): number { + return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1); + } + + private resolveKda(kills: number, deaths: number, assists: number): number { + return deaths === 0 ? kills + assists : this.round((kills + assists) / deaths); + } + + private resolveLastFetchedAt( + docs: RiotMatchDocument[], + context: HistoryContext, + ): string | null { + if (docs.length === 0) { + return context.account.recentStatsFetchedAt?.toISOString() ?? null; + } + const oldest = docs.reduce((acc, doc) => + doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc, + docs[0].fetchedAt); + return oldest.toISOString(); + } + + private clampLimit(value: number | undefined, fallback: number, max: number): number { + if (!value || !Number.isFinite(value)) return fallback; + return Math.max(1, Math.min(Math.floor(value), max)); + } + + private percent(value: number, total: number): number { + return total > 0 ? Math.round((value / total) * 100) : 0; + } + + private average(value: number, total: number): number { + return total > 0 ? this.round(value / total) : 0; + } + + private round(value: number): number { + return Math.round(value * 10) / 10; + } + + private numberField( + value: RiotMatchParticipantDto, + key: string, + ): number { + const field = value[key]; + return typeof field === 'number' && Number.isFinite(field) ? field : 0; + } + + private booleanField( + value: RiotMatchParticipantDto, + key: string, + ): boolean { + return value[key] === true; + } +} diff --git a/apps/api/src/modules/match-history/match-history.types.ts b/apps/api/src/modules/match-history/match-history.types.ts new file mode 100644 index 00000000..d553c1ca --- /dev/null +++ b/apps/api/src/modules/match-history/match-history.types.ts @@ -0,0 +1,146 @@ +import type { RiotLane } from '../global/database/schema'; +import type { + RiotQueueGroup, + RiotRankFilter, +} from '../riot/riot-queue.constants'; + +export interface HistorySeasonDto { + id: string; + label: string; + startedAt: string | null; + endedAt: string | null; +} + +export interface UserHistoryProfileResponse { + userId: string; + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + summonerLevel: number; + tiers: Array<{ + queueType: string; + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + fetchedAt: string; + }>; + season: HistorySeasonDto; + seasons: HistorySeasonDto[]; + lastFetchedAt: string | null; +} + +export interface ChampionStatsRow { + championId: number; + games: number; + wins: number; + losses: number; + winRate: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + kda: number; + totalKills: number; + totalDeaths: number; + totalAssists: number; + doubleKills: number; + tripleKills: number; + quadraKills: number; + pentaKills: number; + avgCs: number; + avgCsPerMin: number; +} + +export interface ChampionStatsResponse { + queueGroup: RiotQueueGroup; + rank: RiotRankFilter; + queueIds: number[]; + season: HistorySeasonDto; + lastFetchedAt: string | null; + champions: ChampionStatsRow[]; + totals: ChampionStatsRow; +} + +export interface RecentSummaryResponse { + windowSize: number; + winRate: number; + wins: number; + losses: number; + streak: { type: 'win' | 'loss'; count: number } | null; + kda: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + bestRating: { + rating: number | 'Perfect'; + kills: number; + deaths: number; + assists: number; + matchId: string; + } | null; + positionRates: Partial>; + topChampions: Array<{ + championId: number; + games: number; + winRate: number; + pickRate: number; + avgRating: number; + }>; + lastFetchedAt: string | null; +} + +export interface RecentMatchesResponse { + matches: RecentMatchView[]; + nextCursor: number | null; + lastFetchedAt: string | null; + season: HistorySeasonDto; +} + +export interface RecentMatchView { + matchId: string; + queueId: number; + queueLabel: string; + gameCreation: number; + gameDuration: number; + win: boolean; + remake: boolean; + championId: number; + championLevel: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + kda: number; + rating: number; + totalCs: number; + csPerMin: number; + killParticipation: number; + visionScore: number; + controlWardsBought: number; + wardsPlaced: number; + wardsKilled: number; + damageDealtToChampions: number; + damageTaken: number; + goldEarned: number; + items: number[]; + trinket: number; + summonerSpells: [number, number]; + perks: { primaryStyle?: number; subStyle?: number; keystone?: number }; + teams: Array<{ + side: 100 | 200; + win: boolean; + objectives?: { baron?: number; dragon?: number; tower?: number }; + participants: Array<{ + puuid: string; + gameName: string; + tagLine: string; + championId: number; + teamPosition: string; + kills: number; + deaths: number; + assists: number; + }>; + }>; +} diff --git a/apps/api/src/modules/match/dto/create-match.dto.ts b/apps/api/src/modules/match/dto/create-match.dto.ts new file mode 100644 index 00000000..63989d96 --- /dev/null +++ b/apps/api/src/modules/match/dto/create-match.dto.ts @@ -0,0 +1,145 @@ +import { Type } from 'class-transformer'; +import { + ArrayMaxSize, + ArrayMinSize, + IsArray, + IsDate, + IsEnum, + IsInt, + IsOptional, + IsString, + MaxLength, + Min, + MinLength, + ValidateNested, +} from 'class-validator'; +import { POSITIONS } from '../../global/database/schema'; +import type { Position } from '../../global/database/schema'; + +export class PositionPreferenceDto { + @IsEnum(POSITIONS) + position!: Position; + + @IsInt() + @Min(1) + priority!: number; +} + +class MatchScheduleItemDto { + @IsString() + @MaxLength(32) + time!: string; + + @IsString() + @MaxLength(128) + label!: string; +} + +export class CreateMatchDto { + @IsString() + @MinLength(1) + @MaxLength(128) + title!: string; + + @IsOptional() + @IsString() + @MaxLength(2048) + description?: string; + + @IsOptional() + @IsInt() + mapId?: number; + + @IsDate() + @Type(() => Date) + scheduledAt!: Date; + + @IsOptional() + @IsInt() + @Min(2) + maxParticipants?: number; + + @IsOptional() + @IsInt() + @Min(1) + gameCount?: number; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + @ArrayMaxSize(32) + prizes?: string[]; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + @ArrayMaxSize(32) + notices?: string[]; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => MatchScheduleItemDto) + @ArrayMaxSize(32) + schedule?: MatchScheduleItemDto[]; +} + +export class UpdateMatchDto { + @IsOptional() + @IsString() + @MaxLength(128) + title?: string; + + @IsOptional() + @IsString() + @MaxLength(2048) + description?: string; + + @IsOptional() + @IsInt() + mapId?: number; + + @IsOptional() + @IsDate() + @Type(() => Date) + scheduledAt?: Date; + + @IsOptional() + @IsInt() + @Min(2) + maxParticipants?: number; + + @IsOptional() + @IsInt() + @Min(1) + gameCount?: number; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + prizes?: string[]; + + @IsOptional() + @IsArray() + @IsString({ each: true }) + notices?: string[]; + + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => MatchScheduleItemDto) + schedule?: MatchScheduleItemDto[]; +} + +export class JoinMatchDto { + @IsArray() + @ArrayMinSize(1) + @ArrayMaxSize(5) + @ValidateNested({ each: true }) + @Type(() => PositionPreferenceDto) + preferredPositions!: PositionPreferenceDto[]; + + @IsOptional() + @IsString() + userId?: string; +} diff --git a/apps/api/src/modules/match/match.controller.ts b/apps/api/src/modules/match/match.controller.ts new file mode 100644 index 00000000..d3c71af0 --- /dev/null +++ b/apps/api/src/modules/match/match.controller.ts @@ -0,0 +1,169 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + Param, + Patch, + Post, + Query, + UseGuards, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +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 { + MatchDocument, + MatchStatus, + UserDocument, +} from '../global/database/schema'; +import { + CreateMatchDto, + JoinMatchDto, + UpdateMatchDto, +} from './dto/create-match.dto'; +import { MatchService } from './match.service'; + +@Controller('communities/:communityId/matches') +export class MatchController { + constructor(private readonly matchService: MatchService) {} + + @Post() + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async createMatch( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Body() body: CreateMatchDto, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.matchService.create({ + communityId, + hostUserId: currentUser._id, + data: { + title: body.title, + description: body.description ?? '', + mapId: body.mapId ?? 11, + scheduledAt: body.scheduledAt, + maxParticipants: body.maxParticipants ?? 10, + gameCount: body.gameCount, + prizes: body.prizes ?? [], + notices: body.notices ?? [], + schedule: body.schedule ?? [], + }, + }); + } + + // 공개 — 커뮤니티 내 매치 리스트. 로그인 시 본인 참여 여부를 함께 반환. + @Get() + @AllowPublicAccess() + public async listMatches( + @CurrentUser() currentUser: UserDocument | undefined, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('status') status?: MatchStatus, + @Query('limit') limit?: string, + ) { + const matches = await this.matchService.list({ + communityId, + status, + limit: limit ? Number(limit) : undefined, + }); + if (!currentUser) return { matches }; + const myId = currentUser._id; + return { + matches: matches.map((m) => this.annotateJoined(m, myId)), + }; + } + + @Get(':matchId') + @AllowPublicAccess() + public async getMatch( + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + const match = await this.matchService.getById(matchId); + return this.matchService.serialize(match); + } + + @Patch(':matchId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + public async updateMatch( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: UpdateMatchDto, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.matchService.update({ matchId, communityId, patch: body }); + } + + @Delete(':matchId') + @Roles('admin', 'owner') + @UseGuards(RolesGuard) + @HttpCode(HttpStatus.NO_CONTENT) + public async deleteMatch( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.matchService.remove({ matchId, communityId }); + } + + // 공개 — 참여 (로그인된 유저는 자기 자신, 비로그인은 body.userId 사용). + @Post(':matchId/participants') + @AllowPublicAccess() + public async joinMatch( + @CurrentUser() currentUser: UserDocument | undefined, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + @Body() body: JoinMatchDto, + ) { + const userId = this.resolveJoinerUserId(currentUser, body.userId); + return this.matchService.join({ + matchId, + userId, + preferredPositions: body.preferredPositions, + }); + } + + private resolveJoinerUserId( + currentUser: UserDocument | undefined, + bodyUserId?: string, + ): mongoose.Types.ObjectId { + if (currentUser) return currentUser._id; + if (!bodyUserId || !mongoose.isValidObjectId(bodyUserId)) { + throw new BadRequestException( + 'userId is required when not authenticated.', + ); + } + return new mongoose.Types.ObjectId(bodyUserId); + } + + private annotateJoined( + match: MatchDocument, + userId: mongoose.Types.ObjectId, + ) { + const obj = match.toObject(); + const joined = match.participants.some((p) => p.userId.equals(userId)); + return { ...obj, joined }; + } + + private assertSameCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + } +} diff --git a/apps/api/src/modules/match/match.module.ts b/apps/api/src/modules/match/match.module.ts new file mode 100644 index 00000000..54997369 --- /dev/null +++ b/apps/api/src/modules/match/match.module.ts @@ -0,0 +1,13 @@ +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, CommunityStatsModule], + controllers: [MatchController], + providers: [MatchService], + exports: [MatchService], +}) +export class MatchModule {} diff --git a/apps/api/src/modules/match/match.service.ts b/apps/api/src/modules/match/match.service.ts new file mode 100644 index 00000000..6bdce5cf --- /dev/null +++ b/apps/api/src/modules/match/match.service.ts @@ -0,0 +1,213 @@ +import { + BadRequestException, + Injectable, + 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, + MatchDocument, + MatchStatus, + PositionPreference, + TierInfo, +} from '../global/database/schema'; +import { DEFAULT_TOURNAMENT_GAME_COUNT } from '../tournament-code/tournament-code.constants'; +import { TournamentCodeService } from '../tournament-code/tournament-code.service'; + +interface CreateMatchParams { + communityId: mongoose.Types.ObjectId; + hostUserId?: mongoose.Types.ObjectId; + data: Partial & Pick; +} + +interface UpdateMatchParams { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + patch: Partial; +} + +interface ListMatchesQuery { + communityId: mongoose.Types.ObjectId; + status?: MatchStatus; + limit?: number; +} + +interface JoinMatchParams { + matchId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + preferredPositions: PositionPreference[]; + // 특정 RiotAccount(puuid)로 참가하고 싶을 때 지정. 없으면 primary 사용. + riotPuuid?: string; +} + +@Injectable() +export class MatchService { + constructor( + private readonly connectionService: ConnectionService, + private readonly tournamentCodeService: TournamentCodeService, + private readonly communityStatsService: CommunityStatsService, + ) {} + + public async create(params: CreateMatchParams): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(params.communityId) + .select({ matchGameCount: 1 }) + .lean() + .exec(); + return MatchModel.create({ + ...params.data, + gameCount: + params.data.gameCount ?? + community?.matchGameCount ?? + DEFAULT_TOURNAMENT_GAME_COUNT, + communityId: params.communityId, + hostUserId: params.hostUserId, + }); + } + + public async list(query: ListMatchesQuery): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const filter: { + communityId: mongoose.Types.ObjectId; + status?: MatchStatus; + } = { + communityId: query.communityId, + }; + if (query.status) filter.status = query.status; + return MatchModel.find(filter) + .sort({ scheduledAt: -1 }) + .limit(Math.min(query.limit ?? 50, 200)) + .exec(); + } + + public async getById( + matchId: mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(matchId); + if (!match) throw new NotFoundException('Match not found.'); + return match; + } + + public async serialize(match: MatchDocument) { + const obj = match.toObject(); + if (obj.result?.games) { + obj.result.games = [...obj.result.games].sort( + (left, right) => left.gameNumber - right.gameNumber, + ); + } + return { + ...obj, + gameCount: match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT, + tournamentCodes: await this.tournamentCodeService.buildSlots(match), + }; + } + + public async update(params: UpdateMatchParams): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(params.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + const previousStatus = match.status; + match.set(params.patch); + if ( + previousStatus !== 'recruiting' && + match.status === 'recruiting' && + match.tournamentCodeIds.length > 0 + ) { + await this.tournamentCodeService.releaseFromMatch(match); + match.tournamentCodeIds = []; + match.teamBuiltAt = undefined; + match.result = undefined; + match.resultPollState = undefined; + } + await match.save(); + return match; + } + + public async remove(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = await MatchModel.findById(params.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + await this.tournamentCodeService.releaseFromMatch(match); + await match.deleteOne(); + await this.communityStatsService.invalidateCommunity(params.communityId); + } + + public async join(params: JoinMatchParams): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const UserModel = await this.connectionService.getModel('user'); + + const user = await UserModel.findById(params.userId); + if (!user) throw new NotFoundException('User not found.'); + + const match = await MatchModel.findById(params.matchId); + if (!match) throw new NotFoundException('Match not found.'); + if (!match.communityId.equals(user.communityId)) { + throw new BadRequestException( + 'User and match belong to different communities.', + ); + } + if (match.status !== 'recruiting') { + throw new BadRequestException('Match is not recruiting.'); + } + if (match.participants.length >= match.maxParticipants) { + throw new BadRequestException('Match is full.'); + } + const alreadyIn = match.participants.some((p) => p.userId.equals(user._id)); + if (alreadyIn) { + throw new BadRequestException('User already joined this match.'); + } + + const selectedRiot = params.riotPuuid + ? user.riotAccounts.find((a) => a.puuid === params.riotPuuid) + : user.riotAccounts.find((a) => a.isPrimary); + const selectedTier = this.selectParticipantTier(selectedRiot?.tiers ?? []); + match.participants.push({ + userId: user._id, + puuid: selectedRiot?.puuid, + gameName: selectedRiot?.gameName, + tagLine: selectedRiot?.tagLine, + profileIconId: selectedRiot?.profileIconId, + tier: selectedTier, + preferredPositions: params.preferredPositions, + joinedAt: new Date(), + }); + await match.save(); + return match; + } + + private selectParticipantTier(tiers: TierInfo[]): TierInfo | undefined { + const tier = + tiers.find((entry) => entry.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; + if (!tier) return undefined; + + return { + leagueId: tier.leagueId, + queueType: tier.queueType, + tier: tier.tier, + rank: tier.rank, + puuid: tier.puuid, + leaguePoints: tier.leaguePoints, + wins: tier.wins, + losses: tier.losses, + veteran: tier.veteran, + inactive: tier.inactive, + freshBlood: tier.freshBlood, + hotStreak: tier.hotStreak, + miniSeries: tier.miniSeries, + fetchedAt: tier.fetchedAt, + }; + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts new file mode 100644 index 00000000..3caa1162 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.controller.ts @@ -0,0 +1,24 @@ +import { Controller, Get, NotFoundException, Param } from '@nestjs/common'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { RiotJobQueueService } from './riot-job-queue.service'; + +@Controller('riot/jobs') +export class RiotJobQueueController { + constructor(private readonly jobQueueService: RiotJobQueueService) {} + + @Get('parents/:parentJobId') + @AllowPublicAccess() + public async getParent(@Param('parentJobId') parentJobId: string) { + const status = await this.jobQueueService.getParentStatus(parentJobId); + if (!status) throw new NotFoundException('Riot parent job not found.'); + return status; + } + + @Get(':jobId') + @AllowPublicAccess() + public async getJob(@Param('jobId') jobId: string) { + const status = await this.jobQueueService.getStatus(jobId); + if (!status) throw new NotFoundException('Riot job not found.'); + return status; + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts new file mode 100644 index 00000000..1bfcae9d --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.module.ts @@ -0,0 +1,16 @@ +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'; +import { RiotJobQueueService } from './riot-job-queue.service'; +import { RiotJobWorkerService } from './riot-job-worker.service'; +import { RiotRefreshGateway } from './riot-refresh.gateway'; + +@Module({ + imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)], + controllers: [RiotJobQueueController], + providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway], + exports: [RiotJobQueueService], +}) +export class RiotJobQueueModule {} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts new file mode 100644 index 00000000..ecacef15 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.service.ts @@ -0,0 +1,482 @@ +import { + BadRequestException, + HttpException, + HttpStatus, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import { randomUUID } from 'crypto'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + CommunityDocument, + RiotAccount, + UserDocument, +} from '../global/database/schema'; +import { GarnetService } from '../global/garnet/garnet.service'; +import { + isRiotQueueGroup, + resolveRiotQueueIds, + type RiotQueueGroup, +} from '../riot/riot-queue.constants'; +import { + EnqueueRefreshResult, + RIOT_JOB_AVG_SECONDS, + RIOT_JOB_DEDUP_TTL_SECONDS, + RIOT_JOB_HIGH_COOLDOWN_SECONDS, + RIOT_JOB_HIGH_STREAM, + RIOT_JOB_LOW_COOLDOWN_SECONDS, + RIOT_JOB_LOW_STREAM, + RIOT_JOB_SCHEDULED_ZSET, + RIOT_JOB_STATUS_TTL_SECONDS, + RiotJobPriority, + RiotJobState, + RiotJobStatus, + RiotParentJobStatus, + RiotRefreshEvent, + RiotRefreshSubJob, +} from './riot-job-queue.types'; +import type { + EnqueueTournamentResultPollResult, + PollTournamentResultJob, +} from '../tournament-result/tournament-result.types'; + +interface RefreshContext { + community: CommunityDocument; + user: UserDocument; + account: RiotAccount; +} + +@Injectable() +export class RiotJobQueueService { + constructor( + private readonly connectionService: ConnectionService, + private readonly garnetService: GarnetService, + ) {} + + public async enqueueRefresh(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + queueGroups: string[]; + priority: RiotJobPriority; + requestedBy?: string; + }): Promise { + const context = await this.resolveContext(params); + const queueGroups = this.normalizeQueueGroups(params.queueGroups); + const stream = this.resolveStream(params.priority); + const streamLength = await this.garnetService.streamLength(stream); + const dedupKeys = queueGroups.map((queueGroup) => + this.dedupKey(context.account.puuid, queueGroup), + ); + const existingJobIds = await Promise.all( + dedupKeys.map((key) => this.garnetService.getString(key)), + ); + const needsNewJob = existingJobIds.some((jobId) => !jobId); + + if (params.priority === 'high' && needsNewJob) { + this.assertHighQueueAccepting(streamLength); + this.assertRefreshBudget(context.account.lastRefreshRequestedAt, 'high'); + } + if (params.priority === 'low' && needsNewJob) { + this.assertRefreshBudget(context.account.lastRefreshRequestedAt, 'low'); + } + + const parentJobId = randomUUID(); + const subJobs: EnqueueRefreshResult['subJobs'] = []; + + for (let index = 0; index < queueGroups.length; index += 1) { + const queueGroup = queueGroups[index]; + const existingJobId = existingJobIds[index]; + const queuePosition = streamLength + subJobs.length + 1; + + if (existingJobId) { + const existingStatus = await this.getStatus(existingJobId); + subJobs.push({ + jobId: existingJobId, + queueGroup, + alreadyQueued: true, + etaSeconds: existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, + queuePosition: existingStatus?.queuePosition ?? queuePosition, + }); + continue; + } + + const job: RiotRefreshSubJob = { + jobId: randomUUID(), + parentJobId, + userId: context.user._id.toString(), + puuid: context.account.puuid, + region: context.community.riotRegion ?? 'asia', + platform: context.community.riotPlatform ?? 'kr', + queueGroup, + queueIds: resolveRiotQueueIds(queueGroup, 'all'), + requestedAt: Date.now(), + requestedBy: params.requestedBy, + priority: params.priority, + }; + const acquired = await this.garnetService.setStringIfAbsent( + dedupKeys[index], + job.jobId, + RIOT_JOB_DEDUP_TTL_SECONDS, + ); + if (!acquired) { + const jobId = await this.garnetService.getString(dedupKeys[index]); + if (!jobId) continue; + const status = await this.getStatus(jobId); + subJobs.push({ + jobId, + queueGroup, + alreadyQueued: true, + etaSeconds: status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, + queuePosition: status?.queuePosition ?? queuePosition, + }); + continue; + } + + const status: RiotJobStatus = { + jobId: job.jobId, + parentJobId, + state: 'queued', + priority: params.priority, + queueGroup, + queueIds: job.queueIds, + puuid: job.puuid, + userId: job.userId, + enqueuedAt: new Date(job.requestedAt).toISOString(), + etaSeconds: queuePosition * RIOT_JOB_AVG_SECONDS, + queuePosition, + }; + + await Promise.all([ + this.setStatus(status), + this.garnetService.appendStream( + stream, + { job: JSON.stringify(job) }, + { maxLen: 10_000 }, + ), + ]); + subJobs.push({ + jobId: job.jobId, + queueGroup, + alreadyQueued: false, + etaSeconds: status.etaSeconds, + queuePosition, + }); + } + + await this.setParent(parentJobId, subJobs.map((job) => job.jobId)); + if (params.priority === 'high' && needsNewJob) { + await this.markRefreshRequested(context.user._id, context.account.puuid); + } + + return { + parentJobId, + subJobs, + totalEtaSeconds: subJobs.reduce((sum, job) => sum + job.etaSeconds, 0), + }; + } + + public async enqueueTournamentResultPoll(params: { + matchId: string; + attempt: number; + expandedToAllPuuids: boolean; + priority: RiotJobPriority; + deferUntilMs?: number; + }): Promise { + const job: PollTournamentResultJob = { + kind: 'poll-tournament-result', + jobId: randomUUID(), + matchId: params.matchId, + attempt: params.attempt, + expandedToAllPuuids: params.expandedToAllPuuids, + enqueuedAt: Date.now(), + priority: params.priority, + }; + + if (params.deferUntilMs && params.deferUntilMs > Date.now()) { + await this.scheduleJob(job, params.deferUntilMs); + } else { + await this.appendJob(job); + } + + return { + jobId: job.jobId, + matchId: job.matchId, + priority: job.priority, + attempt: job.attempt, + expandedToAllPuuids: job.expandedToAllPuuids, + }; + } + + public async promoteDueScheduledJobs(limit = 100): Promise { + const client = this.garnetService.raw(); + const raw = (await client.sendCommand([ + 'ZRANGEBYSCORE', + RIOT_JOB_SCHEDULED_ZSET, + '-inf', + String(Date.now()), + 'LIMIT', + '0', + String(limit), + ])) as string[] | null; + const entries = raw ?? []; + let promoted = 0; + + for (const entry of entries) { + const removed = (await client.sendCommand([ + 'ZREM', + RIOT_JOB_SCHEDULED_ZSET, + entry, + ])) as number; + if (removed !== 1) continue; + const job = this.parseScheduledJob(entry); + if (!job) continue; + await this.appendJob(job); + promoted += 1; + } + + return promoted; + } + + public async getStatus(jobId: string): Promise { + return this.garnetService.getJson(this.statusKey(jobId)); + } + + public async getParentStatus( + parentJobId: string, + ): Promise { + const jobIds = await this.garnetService.getJson( + this.parentKey(parentJobId), + ); + if (!jobIds) return null; + + const subJobs = ( + await Promise.all(jobIds.map((jobId) => this.getStatus(jobId))) + ).filter((status): status is RiotJobStatus => Boolean(status)); + const done = subJobs.filter((job) => + job.state === 'completed' || job.state === 'failed', + ).length; + const state = this.resolveParentState(subJobs); + + return { + parentJobId, + state, + done, + total: subJobs.length, + etaSeconds: subJobs + .filter((job) => job.state === 'queued' || job.state === 'processing') + .reduce((sum, job) => sum + job.etaSeconds, 0), + subJobs, + }; + } + + public async markProcessing(job: RiotRefreshSubJob): Promise { + const status = await this.requireStatus(job.jobId); + const next: RiotJobStatus = { + ...status, + state: 'processing', + startedAt: new Date().toISOString(), + etaSeconds: RIOT_JOB_AVG_SECONDS, + queuePosition: 0, + }; + await this.setStatus(next); + return next; + } + + public async markCompleted( + job: RiotRefreshSubJob, + ): Promise { + const status = await this.requireStatus(job.jobId); + const next: RiotJobStatus = { + ...status, + state: 'completed', + finishedAt: new Date().toISOString(), + etaSeconds: 0, + queuePosition: 0, + }; + await Promise.all([ + this.setStatus(next), + this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)), + ]); + return this.toEvent(next); + } + + public async markFailed( + job: RiotRefreshSubJob, + error: unknown, + ): Promise { + const message = error instanceof Error ? error.message : String(error); + const status = await this.requireStatus(job.jobId); + const next: RiotJobStatus = { + ...status, + state: 'failed', + finishedAt: new Date().toISOString(), + error: message, + etaSeconds: 0, + queuePosition: 0, + }; + await Promise.all([ + this.setStatus(next), + this.garnetService.delete(this.dedupKey(job.puuid, job.queueGroup)), + ]); + return this.toEvent(next); + } + + private async resolveContext(params: { + communityId: mongoose.Types.ObjectId; + userId: mongoose.Types.ObjectId; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const CommunityModel = await this.connectionService.getModel('community'); + const [user, community] = await Promise.all([ + UserModel.findById(params.userId).exec(), + CommunityModel.findById(params.communityId).exec(), + ]); + if (!community) throw new NotFoundException('Community not found.'); + if (!user || !user.communityId.equals(params.communityId)) { + throw new NotFoundException('User not found.'); + } + + const account = + user.riotAccounts.find((riotAccount) => riotAccount.isPrimary) ?? + user.riotAccounts[0]; + if (!account) throw new NotFoundException('Riot account not found.'); + return { community, user, account }; + } + + private normalizeQueueGroups(queueGroups: string[]): RiotQueueGroup[] { + const values = queueGroups.length > 0 ? queueGroups : ['summoners-rift']; + const unique = [...new Set(values)]; + if (!unique.every(isRiotQueueGroup)) { + throw new BadRequestException('Invalid queueGroups.'); + } + return unique; + } + + private assertHighQueueAccepting(streamLength: number): void { + if (streamLength <= 50) return; + throw new HttpException( + { + reason: 'queue-full', + retryAfterSeconds: RIOT_JOB_AVG_SECONDS * streamLength, + }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + + private assertRefreshBudget( + lastRequestedAt: Date | undefined, + priority: RiotJobPriority, + ): void { + if (!lastRequestedAt) return; + const cooldownSeconds = + priority === 'high' + ? RIOT_JOB_HIGH_COOLDOWN_SECONDS + : RIOT_JOB_LOW_COOLDOWN_SECONDS; + const elapsedSeconds = (Date.now() - lastRequestedAt.getTime()) / 1000; + if (elapsedSeconds >= cooldownSeconds) return; + throw new HttpException( + { + reason: 'cooldown', + retryAfterSeconds: Math.ceil(cooldownSeconds - elapsedSeconds), + }, + HttpStatus.TOO_MANY_REQUESTS, + ); + } + + private async markRefreshRequested( + userId: mongoose.Types.ObjectId, + puuid: string, + ): Promise { + const UserModel = await this.connectionService.getModel('user'); + await UserModel.updateOne( + { _id: userId, 'riotAccounts.puuid': puuid }, + { $set: { 'riotAccounts.$.lastRefreshRequestedAt': new Date() } }, + ).exec(); + } + + private resolveStream(priority: RiotJobPriority): string { + return priority === 'high' ? RIOT_JOB_HIGH_STREAM : RIOT_JOB_LOW_STREAM; + } + + private async appendJob(job: RiotRefreshSubJob | PollTournamentResultJob) { + await this.garnetService.appendStream( + this.resolveStream(job.priority), + { job: JSON.stringify(job) }, + { maxLen: 10_000 }, + ); + } + + private async scheduleJob( + job: PollTournamentResultJob, + deferUntilMs: number, + ): Promise { + await this.garnetService.raw().sendCommand([ + 'ZADD', + RIOT_JOB_SCHEDULED_ZSET, + String(deferUntilMs), + JSON.stringify(job), + ]); + } + + private parseScheduledJob(value: string): PollTournamentResultJob | null { + try { + const parsed = JSON.parse(value) as PollTournamentResultJob; + return parsed.kind === 'poll-tournament-result' ? parsed : null; + } catch { + return null; + } + } + + private resolveParentState(subJobs: RiotJobStatus[]): RiotJobState { + if (subJobs.some((job) => job.state === 'processing')) return 'processing'; + if (subJobs.some((job) => job.state === 'queued')) return 'queued'; + if (subJobs.some((job) => job.state === 'failed')) return 'failed'; + return 'completed'; + } + + private async requireStatus(jobId: string): Promise { + const status = await this.getStatus(jobId); + if (!status) throw new Error(`Missing riot job status: ${jobId}`); + return status; + } + + private async setStatus(status: RiotJobStatus): Promise { + await this.garnetService.setJson( + this.statusKey(status.jobId), + status, + RIOT_JOB_STATUS_TTL_SECONDS, + ); + } + + private async setParent(parentJobId: string, jobIds: string[]): Promise { + await this.garnetService.setJson( + this.parentKey(parentJobId), + jobIds, + RIOT_JOB_STATUS_TTL_SECONDS, + ); + } + + private toEvent(status: RiotJobStatus): RiotRefreshEvent { + return { + parentJobId: status.parentJobId, + jobId: status.jobId, + queueGroup: status.queueGroup, + puuid: status.puuid, + state: status.state, + error: status.error, + }; + } + + private statusKey(jobId: string): string { + return `riot:job:status:${jobId}`; + } + + private parentKey(parentJobId: string): string { + return `riot:job:parent:${parentJobId}`; + } + + private dedupKey(puuid: string, queueGroup: RiotQueueGroup): string { + return `riot:job:dedup:${puuid}:${queueGroup}`; + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts b/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts new file mode 100644 index 00000000..45968dd0 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-queue.types.ts @@ -0,0 +1,88 @@ +import type { + RiotPlatformRoute, + RiotRegionalRoute, +} 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'; +export const RIOT_JOB_SCHEDULED_ZSET = 'riot:queue:scheduled'; +export const RIOT_JOB_GROUP = 'riot-refresh-worker'; +export const RIOT_JOB_STATUS_TTL_SECONDS = 24 * 60 * 60; +export const RIOT_JOB_DEDUP_TTL_SECONDS = 5 * 60; +export const RIOT_JOB_HIGH_COOLDOWN_SECONDS = 5 * 60; +export const RIOT_JOB_LOW_COOLDOWN_SECONDS = 60 * 60; +export const RIOT_JOB_AVG_SECONDS = 20; + +export type RiotJobPriority = 'high' | 'low'; +export type RiotJobState = 'queued' | 'processing' | 'completed' | 'failed'; + +export interface RiotRefreshSubJob { + kind?: 'refresh-account'; + jobId: string; + parentJobId: string; + userId: string; + puuid: string; + region: RiotRegionalRoute; + platform: RiotPlatformRoute; + queueGroup: RiotQueueGroup; + queueIds: number[]; + requestedAt: number; + requestedBy?: string; + priority: RiotJobPriority; +} + +export type RiotJobPayload = + | RiotRefreshSubJob + | PollTournamentResultJob + | LegacyImportMemberJob; + +export interface RiotJobStatus { + jobId: string; + parentJobId: string; + state: RiotJobState; + priority: RiotJobPriority; + queueGroup: RiotQueueGroup; + queueIds: number[]; + puuid: string; + userId: string; + enqueuedAt: string; + startedAt?: string; + finishedAt?: string; + error?: string; + etaSeconds: number; + queuePosition: number; + alreadyQueued?: boolean; +} + +export interface RiotParentJobStatus { + parentJobId: string; + state: RiotJobState; + done: number; + total: number; + etaSeconds: number; + subJobs: RiotJobStatus[]; +} + +export interface RiotRefreshEvent { + parentJobId: string; + jobId: string; + queueGroup: RiotQueueGroup; + puuid: string; + state: RiotJobState; + error?: string; +} + +export interface EnqueueRefreshResult { + parentJobId: string; + subJobs: Array<{ + jobId: string; + queueGroup: RiotQueueGroup; + alreadyQueued: boolean; + etaSeconds: number; + queuePosition: number; + }>; + totalEtaSeconds: number; +} diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts new file mode 100644 index 00000000..a543d8cb --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.ts @@ -0,0 +1,227 @@ +import { + Injectable, + Logger, + OnModuleDestroy, + OnModuleInit, +} from '@nestjs/common'; +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, + RIOT_JOB_HIGH_STREAM, + RIOT_JOB_LOW_STREAM, + RiotJobPayload, + RiotRefreshSubJob, +} from './riot-job-queue.types'; +import { RiotJobQueueService } from './riot-job-queue.service'; +import { RiotRefreshGateway } from './riot-refresh.gateway'; +import { TournamentResultService } from '../tournament-result/tournament-result.service'; +import type { PollTournamentResultJob } from '../tournament-result/tournament-result.types'; + +const LEADER_KEY = 'riot:worker:leader'; +const LEADER_TTL_SECONDS = 60; + +@Injectable() +export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(RiotJobWorkerService.name); + private readonly consumer = `${process.pid}:${Math.random().toString(36).slice(2)}`; + private stopped = false; + + constructor( + private readonly garnetService: GarnetService, + private readonly jobQueueService: RiotJobQueueService, + private readonly recentMatchesService: RiotRecentMatchesService, + private readonly connectionService: ConnectionService, + private readonly refreshGateway: RiotRefreshGateway, + private readonly tournamentResultService: TournamentResultService, + private readonly legacyImportService: LegacyImportService, + ) {} + + public async onModuleInit() { + await this.ensureConsumerGroups(); + void this.loop(); + } + + public onModuleDestroy() { + this.stopped = true; + } + + private async loop(): Promise { + while (!this.stopped) { + try { + const isLeader = await this.tryBecomeLeader(); + if (!isLeader) { + await this.sleep(1_000); + continue; + } + + await this.jobQueueService.promoteDueScheduledJobs(); + const entry = + (await this.readOne(RIOT_JOB_HIGH_STREAM, 100)) ?? + (await this.readOne(RIOT_JOB_LOW_STREAM, 1_000)); + if (!entry) continue; + + await this.processEntry(entry.stream, entry.message); + } catch (error) { + this.logger.warn( + `Riot job worker loop failed: ${ + error instanceof Error ? error.message : error + }`, + ); + await this.sleep(1_000); + } + } + } + + private async processEntry(stream: string, entry: StreamEntry): Promise { + const job = this.parseJob(entry); + if (!job) { + await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id); + return; + } + + try { + if (this.isTournamentResultJob(job)) { + 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) { + await this.recentMatchesService.ensureFreshForQueue({ + puuid: job.puuid, + region: job.region, + queueId, + }); + } + await this.markUserFetchedAt(job); + const event = await this.jobQueueService.markCompleted(job); + this.refreshGateway.broadcastRefreshEvent(event); + } catch (error) { + if (this.isTournamentResultJob(job)) { + this.logger.warn( + `Tournament result poll job failed ${job.jobId}: ${ + error instanceof Error ? error.message : error + }`, + ); + 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); + this.logger.warn( + `Riot refresh job failed ${job.jobId}: ${ + error instanceof Error ? error.message : error + }`, + ); + } finally { + await this.garnetService.acknowledgeStream(stream, RIOT_JOB_GROUP, entry.id); + } + } + + private async markUserFetchedAt(job: RiotRefreshSubJob): Promise { + const UserModel = await this.connectionService.getModel('user'); + const now = new Date(); + const $set: Record = { + 'riotAccounts.$.matchIdsFetchedAt': now, + }; + for (const queueId of job.queueIds) { + $set[`riotAccounts.$.matchIdsByQueueFetchedAt.${queueId}`] = now; + } + await UserModel.updateOne( + { + _id: new mongoose.Types.ObjectId(job.userId), + 'riotAccounts.puuid': job.puuid, + }, + { $set }, + ).exec(); + } + + private parseJob(entry: StreamEntry): RiotJobPayload | null { + const raw = entry.message.job; + if (!raw) return null; + try { + return JSON.parse(raw) as RiotJobPayload; + } catch { + return null; + } + } + + private isTournamentResultJob( + job: RiotJobPayload, + ): job is PollTournamentResultJob { + 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, + ): Promise<{ stream: string; message: StreamEntry } | null> { + const result = await this.garnetService.readGroup( + stream, + RIOT_JOB_GROUP, + this.consumer, + '>', + { count: 1, blockMs }, + ); + const message = result?.[0]?.messages[0]; + return message ? { stream, message } : null; + } + + private async ensureConsumerGroups(): Promise { + await Promise.all( + [RIOT_JOB_HIGH_STREAM, RIOT_JOB_LOW_STREAM].map(async (stream) => { + try { + await this.garnetService.createConsumerGroup(stream, RIOT_JOB_GROUP); + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + if (!message.includes('BUSYGROUP')) throw error; + } + }), + ); + } + + private async tryBecomeLeader(): Promise { + const current = await this.garnetService.getString(LEADER_KEY); + if (current === this.consumer) { + await this.garnetService.setString( + LEADER_KEY, + this.consumer, + LEADER_TTL_SECONDS, + ); + return true; + } + if (current) return false; + return this.garnetService.setStringIfAbsent( + LEADER_KEY, + this.consumer, + LEADER_TTL_SECONDS, + ); + } + + private sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); + } +} diff --git a/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts new file mode 100644 index 00000000..477fd717 --- /dev/null +++ b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts @@ -0,0 +1,78 @@ +import { Logger } from '@nestjs/common'; +import { + ConnectedSocket, + MessageBody, + SubscribeMessage, + WebSocketGateway, + WebSocketServer, +} from '@nestjs/websockets'; +import type { Namespace, Socket } from 'socket.io'; +import type { RiotRefreshEvent } from './riot-job-queue.types'; + +interface SubscribePayload { + puuid?: string; + parentJobId?: string; +} + +const MAX_ROOMS_PER_SOCKET = 5; + +@WebSocketGateway({ + namespace: '/riot-refresh', + cors: { + origin: true, + credentials: true, + allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], + }, +}) +export class RiotRefreshGateway { + @WebSocketServer() + private server!: Namespace; + + private readonly logger = new Logger(RiotRefreshGateway.name); + + @SubscribeMessage('subscribe') + public async handleSubscribe( + @ConnectedSocket() socket: Socket, + @MessageBody() payload: SubscribePayload, + ) { + const rooms = this.resolveRooms(payload); + if (rooms.length === 0) { + socket.emit('error', { message: 'Invalid riot refresh subscription.' }); + return; + } + + const currentRooms = [...socket.rooms].filter((room) => room !== socket.id); + if (currentRooms.length + rooms.length > MAX_ROOMS_PER_SOCKET) { + socket.emit('error', { message: 'Too many riot refresh subscriptions.' }); + return; + } + + await Promise.all(rooms.map((room) => socket.join(room))); + socket.emit('subscribed', { rooms }); + } + + public broadcastRefreshEvent(event: RiotRefreshEvent): void { + const rooms = [ + `puuid:${event.puuid}`, + `parent:${event.parentJobId}`, + `job:${event.jobId}`, + ]; + this.logger.debug( + `Broadcast riot refresh ${event.state}: ${event.jobId} (${event.queueGroup})`, + ); + for (const room of rooms) { + this.server.to(room).emit('riot-refresh', event); + } + } + + private resolveRooms(payload: SubscribePayload): string[] { + const rooms: string[] = []; + if (typeof payload?.puuid === 'string' && payload.puuid.trim()) { + rooms.push(`puuid:${payload.puuid.trim()}`); + } + if (typeof payload?.parentJobId === 'string' && payload.parentJobId.trim()) { + rooms.push(`parent:${payload.parentJobId.trim()}`); + } + return rooms; + } +} diff --git a/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts b/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts new file mode 100644 index 00000000..7dc5035e --- /dev/null +++ b/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts @@ -0,0 +1,494 @@ +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + createEmptyRiotRecentStatsSummary, + type RiotRecentStatsSummary, +} from '../global/database/schema'; +import { RiotAccountEnrichmentService } from './riot-account-enrichment.service'; +import { RiotAccountService } from './riot-account.service'; +import { RiotChampionMasteryService } from './riot-champion-mastery.service'; +import { RiotApiError } from './riot.client.service'; +import { RiotLeagueService } from './riot-league.service'; +import { RiotRecentMatchesService } from './riot-recent-matches.service'; +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import { RiotSummonerService } from './riot-summoner.service'; + +interface FakeAccount { + puuid: string; + profileIconId: number; + revisionDate: number; + summonerLevel: number; + matchIds: string[]; + matchIdsFetchedAt?: Date; + recentStatsSummary?: RiotRecentStatsSummary; + recentStatsFetchedAt?: Date; + tiers: Array<{ + leagueId: string; + queueType: string; + tier: string; + rank: string; + puuid: string; + leaguePoints: number; + wins: number; + losses: number; + fetchedAt: Date; + }>; + tierHistory: Array<{ + queueType: string; + tier: string; + rank?: string; + leaguePoints?: number; + wins?: number; + losses?: number; + recordedAt: Date; + }>; + championMasteries: Array<{ + puuid: string; + championId: number; + championLevel: number; + championPoints: number; + }>; + championMasteriesFetchedAt?: Date; + championRecords: Record; + championRecordsFetchedAt?: Date; +} + +function makeAccount(overrides: Partial = {}): FakeAccount { + return { + puuid: 'puuid-1', + profileIconId: 0, + revisionDate: 0, + summonerLevel: 0, + matchIds: [], + tiers: [], + tierHistory: [], + championMasteries: [], + championRecords: {}, + ...overrides, + }; +} + +function makeUser(account: FakeAccount) { + const _id = new mongoose.Types.ObjectId(); + const save = jest.fn().mockResolvedValue(undefined); + return { + _id, + riotAccounts: [account], + save, + }; +} + +function makeService(overrides?: { + user?: any; + account?: Partial; + summoner?: Partial; + league?: Partial; + mastery?: Partial; + recentMatches?: Partial; + recentStats?: Partial; +}) { + const user = overrides?.user; + const userFindById = jest.fn().mockReturnValue({ + exec: () => Promise.resolve(user ?? null), + }); + const communityFindById = jest.fn().mockReturnValue({ + select: () => ({ + lean: () => ({ + exec: () => + Promise.resolve({ + riotPlatform: 'kr', + riotRegion: 'asia', + }), + }), + }), + }); + const connectionService = { + getModel: jest.fn().mockImplementation(async (modelName: string) => { + if (modelName === 'user') { + return { findById: userFindById }; + } + if (modelName === 'community') { + return { findById: communityFindById }; + } + throw new Error(`Unexpected model: ${modelName}`); + }), + } as unknown as ConnectionService; + + const summonerService = { + getByPuuid: jest.fn(), + ...overrides?.summoner, + } as unknown as RiotSummonerService; + const accountService = { + getRegionByPuuid: jest.fn(), + ...overrides?.account, + } as unknown as RiotAccountService; + const leagueService = { + getEntriesByPuuid: jest.fn(), + ...overrides?.league, + } as unknown as RiotLeagueService; + const masteryService = { + getTopByPuuid: jest.fn(), + ...overrides?.mastery, + } as unknown as RiotChampionMasteryService; + const recentMatchesService = { + syncRecentMatches: jest.fn().mockResolvedValue([]), + loadFromDb: jest.fn().mockResolvedValue([]), + ...overrides?.recentMatches, + } as unknown as RiotRecentMatchesService; + const recentStatsService = { + computeSummary: jest + .fn() + .mockReturnValue(createEmptyRiotRecentStatsSummary()), + ...overrides?.recentStats, + } as unknown as RiotRecentStatsService; + + const service = new RiotAccountEnrichmentService( + connectionService, + accountService, + summonerService, + leagueService, + masteryService, + recentMatchesService, + recentStatsService, + ); + return { + service, + user, + accountService, + summonerService, + leagueService, + masteryService, + recentMatchesService, + recentStatsService, + }; +} + +describe('RiotAccountEnrichmentService', () => { + it('returns failed for unknown user', async () => { + const { service } = makeService(); + const result = await service.enrichRiotAccount({ + userId: new mongoose.Types.ObjectId(), + puuid: 'puuid-1', + }); + expect(result.summoner).toBe('failed'); + expect(result.recentMatches).toBe('failed'); + expect(result.account).toBeNull(); + }); + + it('fills summoner / league / mastery on first attach (force)', async () => { + const account = makeAccount(); + const user = makeUser(account); + const { + service, + summonerService, + leagueService, + masteryService, + recentMatchesService, + recentStatsService, + } = + makeService({ + user, + summoner: { + getByPuuid: jest.fn().mockResolvedValue({ + puuid: 'puuid-1', + profileIconId: 588, + revisionDate: 1776977597000, + summonerLevel: 529, + }), + } as Partial, + league: { + getEntriesByPuuid: jest.fn().mockResolvedValue([ + { + leagueId: 'L1', + queueType: 'RANKED_SOLO_5x5', + tier: 'EMERALD', + rank: 'I', + puuid: 'puuid-1', + leaguePoints: 75, + wins: 160, + losses: 148, + }, + ]), + } as Partial, + mastery: { + getTopByPuuid: jest.fn().mockResolvedValue([ + { + puuid: 'puuid-1', + championId: 7, + championLevel: 70, + championPoints: 742560, + }, + ]), + } as Partial, + recentMatches: { + syncRecentMatches: jest.fn().mockResolvedValue([]), + loadFromDb: jest.fn().mockResolvedValue([ + { matchId: 'KR_1', raw: {} }, + { matchId: 'KR_2', raw: {} }, + ]), + } as Partial, + recentStats: { + computeSummary: jest.fn().mockReturnValue({ + overall: { + games: 2, + wins: 1, + losses: 1, + avgKills: 5.5, + avgDeaths: 2.5, + avgAssists: 7, + avgCs: 175, + avgCsPerMin: 6.4, + mostPlayedChampionIds: [7, 103], + }, + byLane: {}, + }), + } as Partial, + }); + + const result = await service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true }, + }); + + expect(result.summoner).toBe('updated'); + expect(result.league).toBe('updated'); + expect(result.masteries).toBe('updated'); + expect(result.recentMatches).toBe('updated'); + expect(account.profileIconId).toBe(588); + expect(account.summonerLevel).toBe(529); + expect(account.matchIds).toEqual(['KR_1', 'KR_2']); + expect(account.recentStatsSummary).toMatchObject({ + overall: { + games: 2, + wins: 1, + losses: 1, + avgKills: 5.5, + avgDeaths: 2.5, + avgAssists: 7, + avgCs: 175, + avgCsPerMin: 6.4, + mostPlayedChampionIds: [7, 103], + }, + }); + expect(account.tiers).toHaveLength(1); + expect(account.tiers[0]).toMatchObject({ + leagueId: 'L1', + queueType: 'RANKED_SOLO_5x5', + tier: 'EMERALD', + rank: 'I', + puuid: 'puuid-1', + leaguePoints: 75, + }); + expect(account.tierHistory).toHaveLength(1); + expect(account.tierHistory[0]).toMatchObject({ + queueType: 'RANKED_SOLO_5x5', + tier: 'EMERALD', + rank: 'I', + leaguePoints: 75, + wins: 160, + losses: 148, + }); + expect(account.championMasteries).toEqual([ + { + puuid: 'puuid-1', + championId: 7, + championLevel: 70, + championPoints: 742560, + }, + ]); + expect(account.championRecords).toEqual({}); + expect(user.save).toHaveBeenCalledTimes(1); + expect(summonerService.getByPuuid).toHaveBeenCalledWith('puuid-1', { + platform: 'kr', + }); + expect(leagueService.getEntriesByPuuid).toHaveBeenCalledWith('puuid-1', { + platform: 'kr', + }); + expect(masteryService.getTopByPuuid).toHaveBeenCalledWith('puuid-1', { + platform: 'kr', + count: 10, + }); + expect(recentMatchesService.syncRecentMatches).toHaveBeenCalledWith({ + puuid: 'puuid-1', + region: 'asia', + limit: 20, + }); + expect(recentStatsService.computeSummary).toHaveBeenCalled(); + }); + + it('skips fresh data when within TTL and not forced', async () => { + const recent = new Date(Date.now() - 60_000); + const account = makeAccount({ + profileIconId: 1, + revisionDate: Date.now() - 60_000, + summonerLevel: 100, + tiers: [ + { + leagueId: 'L1', + queueType: 'RANKED_SOLO_5x5', + tier: 'GOLD', + rank: 'II', + puuid: 'puuid-1', + leaguePoints: 1, + wins: 1, + losses: 1, + fetchedAt: recent, + }, + ], + championMasteriesFetchedAt: recent, + recentStatsFetchedAt: recent, + recentStatsSummary: createEmptyRiotRecentStatsSummary(), + }); + const user = makeUser(account); + const summoner = jest.fn(); + const league = jest.fn(); + const mastery = jest.fn(); + const { service } = makeService({ + user, + summoner: { getByPuuid: summoner } as Partial, + league: { + getEntriesByPuuid: league, + } as Partial, + mastery: { + getTopByPuuid: mastery, + } as Partial, + }); + + const result = await service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + }); + + expect(result.summoner).toBe('fresh'); + expect(result.league).toBe('fresh'); + expect(result.masteries).toBe('fresh'); + expect(result.recentMatches).toBe('fresh'); + expect(summoner).not.toHaveBeenCalled(); + expect(league).not.toHaveBeenCalled(); + expect(mastery).not.toHaveBeenCalled(); + expect(user.save).not.toHaveBeenCalled(); + }); + + it('records failed for individual failing fetches but updates the rest', async () => { + const account = makeAccount(); + const user = makeUser(account); + const { service } = makeService({ + user, + summoner: { + getByPuuid: jest.fn().mockRejectedValue(new Error('boom')), + } as Partial, + league: { + getEntriesByPuuid: jest.fn().mockResolvedValue([]), + } as Partial, + mastery: { + getTopByPuuid: jest.fn().mockResolvedValue([]), + } as Partial, + }); + + const result = await service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true }, + }); + expect(result.summoner).toBe('failed'); + expect(result.league).toBe('updated'); + expect(result.masteries).toBe('updated'); + expect(result.recentMatches).toBe('updated'); + expect(user.save).toHaveBeenCalled(); + }); + + it('retries summoner lookup with region/by-puuid platform on 404', async () => { + const account = makeAccount(); + const user = makeUser(account); + const summoner = jest + .fn() + .mockRejectedValueOnce(new RiotApiError('not found', 404, 'url')) + .mockResolvedValueOnce({ + puuid: 'puuid-1', + profileIconId: 100, + revisionDate: 1776977597000, + summonerLevel: 30, + }); + const region = jest.fn().mockResolvedValue({ + puuid: 'puuid-1', + game: 'lol', + region: 'jp1', + }); + const league = jest.fn().mockResolvedValue([]); + const mastery = jest.fn().mockResolvedValue([]); + const { service } = makeService({ + user, + account: { getRegionByPuuid: region } as Partial, + summoner: { getByPuuid: summoner } as Partial, + league: { + getEntriesByPuuid: league, + } as Partial, + mastery: { + getTopByPuuid: mastery, + } as Partial, + }); + + const result = await service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true, platform: 'kr' }, + }); + + expect(result.summoner).toBe('updated'); + expect(region).toHaveBeenCalledWith('puuid-1', { region: 'asia' }); + expect(summoner).toHaveBeenNthCalledWith(1, 'puuid-1', { + platform: 'kr', + }); + expect(summoner).toHaveBeenNthCalledWith(2, 'puuid-1', { + platform: 'jp1', + }); + expect(league).toHaveBeenCalledWith('puuid-1', { platform: 'jp1' }); + expect(mastery).toHaveBeenCalledWith('puuid-1', { + platform: 'jp1', + count: 10, + }); + }); + + it('deduplicates concurrent enrichment for the same user and puuid', async () => { + const account = makeAccount(); + const user = makeUser(account); + let resolveSummoner: (value: unknown) => void; + const summonerPromise = new Promise((resolve) => { + resolveSummoner = resolve; + }); + const summoner = jest.fn().mockReturnValue(summonerPromise); + const { service } = makeService({ + user, + summoner: { getByPuuid: summoner } as Partial, + league: { + getEntriesByPuuid: jest.fn().mockResolvedValue([]), + } as Partial, + mastery: { + getTopByPuuid: jest.fn().mockResolvedValue([]), + } as Partial, + }); + + const first = service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true }, + }); + const second = service.enrichRiotAccount({ + userId: user._id, + puuid: 'puuid-1', + options: { force: true }, + }); + + resolveSummoner!({ + puuid: 'puuid-1', + profileIconId: 100, + revisionDate: 1776977597000, + summonerLevel: 30, + }); + await Promise.all([first, second]); + + expect(summoner).toHaveBeenCalledTimes(1); + expect(user.save).toHaveBeenCalledTimes(1); + }); +}); diff --git a/apps/api/src/modules/riot/riot-account-enrichment.service.ts b/apps/api/src/modules/riot/riot-account-enrichment.service.ts new file mode 100644 index 00000000..85079ad1 --- /dev/null +++ b/apps/api/src/modules/riot/riot-account-enrichment.service.ts @@ -0,0 +1,437 @@ +import { Injectable, Logger } from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import { + ChampionMasteryEntry, + RiotAccount, + TierInfo, +} from '../global/database/schema'; +import { RiotAccountService } from './riot-account.service'; +import { RiotChampionMasteryService } from './riot-champion-mastery.service'; +import { RiotApiError } from './riot.client.service'; +import { RiotLeagueService } from './riot-league.service'; +import { + RIOT_RECENT_MATCH_LIMIT, + RiotRecentMatchesService, +} from './riot-recent-matches.service'; +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import { RiotSummonerService } from './riot-summoner.service'; +import { + RiotChampionMasteryDto, + RiotLeagueEntryDto, + RiotMatchDto, + RiotPlatformRoute, + RiotRegionalRoute, + RiotSummonerDto, +} from './riot.types'; + +const DEFAULT_PLATFORM: RiotPlatformRoute = 'kr'; +const DEFAULT_REGION: RiotRegionalRoute = 'asia'; +const MASTERY_LIMIT = 10; + +const DEFAULT_SUMMONER_TTL_MS = 24 * 60 * 60 * 1000; // 24h +const DEFAULT_LEAGUE_TTL_MS = 60 * 60 * 1000; // 1h +const DEFAULT_MASTERY_TTL_MS = 6 * 60 * 60 * 1000; // 6h +const DEFAULT_RECENT_MATCHES_TTL_MS = 6 * 60 * 60 * 1000; // 6h + +export interface EnrichOptions { + platform?: RiotPlatformRoute; + region?: RiotRegionalRoute; + force?: boolean; + summonerTtlMs?: number; + leagueTtlMs?: number; + masteryTtlMs?: number; + recentMatchesTtlMs?: number; +} + +export interface EnrichResult { + summoner: 'updated' | 'fresh' | 'failed'; + league: 'updated' | 'fresh' | 'failed'; + masteries: 'updated' | 'fresh' | 'failed'; + recentMatches: 'updated' | 'fresh' | 'failed'; + account: RiotAccount | null; +} + +@Injectable() +export class RiotAccountEnrichmentService { + private readonly logger = new Logger(RiotAccountEnrichmentService.name); + private readonly inFlight = new Map>(); + + constructor( + private readonly connectionService: ConnectionService, + private readonly accountService: RiotAccountService, + private readonly summonerService: RiotSummonerService, + private readonly leagueService: RiotLeagueService, + private readonly masteryService: RiotChampionMasteryService, + private readonly recentMatchesService: RiotRecentMatchesService, + private readonly recentStatsService: RiotRecentStatsService, + ) {} + + public async enrichRiotAccount(params: { + userId: mongoose.Types.ObjectId; + puuid: string; + options?: EnrichOptions; + }): Promise { + const key = `${params.userId.toString()}:${params.puuid}`; + const existing = this.inFlight.get(key); + if (existing) return existing; + + const promise = this.doEnrichRiotAccount(params).finally(() => { + this.inFlight.delete(key); + }); + this.inFlight.set(key, promise); + return promise; + } + + private async doEnrichRiotAccount(params: { + userId: mongoose.Types.ObjectId; + puuid: string; + options?: EnrichOptions; + }): Promise { + const UserModel = await this.connectionService.getModel('user'); + const user = await UserModel.findById(params.userId).exec(); + if (!user) { + return { + summoner: 'failed', + league: 'failed', + masteries: 'failed', + recentMatches: 'failed', + account: null, + }; + } + const account = user.riotAccounts.find((a) => a.puuid === params.puuid); + if (!account) { + return { + summoner: 'failed', + league: 'failed', + masteries: 'failed', + recentMatches: 'failed', + account: null, + }; + } + + const CommunityModel = await this.connectionService.getModel('community'); + const community = await CommunityModel.findById(user.communityId) + .select({ riotPlatform: 1, riotRegion: 1, seasonStartedAt: 1 }) + .lean() + .exec(); + + const opts = params.options ?? {}; + const platform = opts.platform ?? community?.riotPlatform ?? DEFAULT_PLATFORM; + const region = opts.region ?? community?.riotRegion ?? DEFAULT_REGION; + const now = Date.now(); + + const summonerTtl = opts.summonerTtlMs ?? DEFAULT_SUMMONER_TTL_MS; + const leagueTtl = opts.leagueTtlMs ?? DEFAULT_LEAGUE_TTL_MS; + const masteryTtl = opts.masteryTtlMs ?? DEFAULT_MASTERY_TTL_MS; + const recentMatchesTtl = + opts.recentMatchesTtlMs ?? DEFAULT_RECENT_MATCHES_TTL_MS; + const force = opts.force === true; + const seasonStartedAt = community?.seasonStartedAt + ? new Date(community.seasonStartedAt) + : undefined; + const seasonInvalidatesRecentStats = + seasonStartedAt !== undefined && + (!account.recentStatsFetchedAt || + account.recentStatsFetchedAt.getTime() < seasonStartedAt.getTime()); + + const summonerStale = + force || + account.revisionDate === 0 || + now - account.revisionDate > summonerTtl; + const leagueStale = + force || + account.tiers.length === 0 || + this.tiersOldestAt(account.tiers) < now - leagueTtl; + const masteryStale = + force || + !account.championMasteriesFetchedAt || + now - account.championMasteriesFetchedAt.getTime() > masteryTtl; + const recentMatchesStale = + force || + seasonInvalidatesRecentStats || + !account.recentStatsFetchedAt || + !account.recentStatsSummary || + now - account.recentStatsFetchedAt.getTime() > recentMatchesTtl; + + const summonerOutcome = summonerStale + ? await this.fetchSummonerSafe(params.puuid, platform, region) + : { status: 'fresh' as const, dto: null, platform }; + const effectivePlatform = summonerOutcome.platform ?? platform; + + const [leagueOutcome, masteryOutcome, recentMatchesOutcome] = + await Promise.all([ + leagueStale + ? this.fetchLeagueSafe(params.puuid, effectivePlatform) + : Promise.resolve({ status: 'fresh' as const, dto: null }), + masteryStale + ? this.fetchMasteriesSafe(params.puuid, effectivePlatform) + : Promise.resolve({ status: 'fresh' as const, dto: null }), + recentMatchesStale + ? this.fetchRecentMatchesSafe(params.puuid, region, seasonStartedAt) + : Promise.resolve({ + status: 'fresh' as const, + summary: null, + matchIds: null, + }), + ]); + + if (summonerOutcome.status === 'updated' && summonerOutcome.dto) { + this.applySummoner(account, summonerOutcome.dto); + } + if (leagueOutcome.status === 'updated' && leagueOutcome.dto) { + this.applyLeagueEntries(account, leagueOutcome.dto); + } + if (masteryOutcome.status === 'updated' && masteryOutcome.dto) { + this.applyMasteries(account, masteryOutcome.dto); + } + if ( + recentMatchesOutcome.status === 'updated' && + recentMatchesOutcome.summary && + recentMatchesOutcome.matchIds + ) { + this.applyRecentMatches( + account, + recentMatchesOutcome.summary, + recentMatchesOutcome.matchIds, + ); + } + + if ( + summonerOutcome.status === 'updated' || + leagueOutcome.status === 'updated' || + masteryOutcome.status === 'updated' || + recentMatchesOutcome.status === 'updated' + ) { + await user.save(); + } + + return { + summoner: summonerOutcome.status, + league: leagueOutcome.status, + masteries: masteryOutcome.status, + recentMatches: recentMatchesOutcome.status, + account, + }; + } + + private async fetchSummonerSafe( + puuid: string, + platform: RiotPlatformRoute, + region: RiotRegionalRoute, + ): Promise< + | { status: 'updated'; dto: RiotSummonerDto; platform: RiotPlatformRoute } + | { status: 'failed'; dto: null; platform: RiotPlatformRoute } + > { + try { + const dto = await this.summonerService.getByPuuid(puuid, { platform }); + return { status: 'updated', dto, platform }; + } catch (err) { + if (err instanceof RiotApiError && err.status === 404) { + try { + const regionDto = await this.accountService.getRegionByPuuid(puuid, { + region, + }); + if (regionDto.region !== platform) { + this.logger.warn( + `Summoner platform corrected for ${puuid}: ${platform} -> ${regionDto.region}`, + ); + } + const dto = await this.summonerService.getByPuuid(puuid, { + platform: regionDto.region, + }); + return { status: 'updated', dto, platform: regionDto.region }; + } catch (fallbackErr) { + this.logger.warn( + `Summoner fallback fetch failed for ${puuid}: ${ + (fallbackErr as Error)?.message ?? fallbackErr + }`, + ); + return { status: 'failed', dto: null, platform }; + } + } + this.logger.warn( + `Summoner fetch failed for ${puuid}: ${(err as Error)?.message ?? err}`, + ); + return { status: 'failed', dto: null, platform }; + } + } + + private async fetchLeagueSafe( + puuid: string, + platform: RiotPlatformRoute, + ): Promise< + | { status: 'updated'; dto: RiotLeagueEntryDto[] } + | { status: 'failed'; dto: null } + > { + try { + const dto = await this.leagueService.getEntriesByPuuid(puuid, { + platform, + }); + return { status: 'updated', dto }; + } catch (err) { + this.logger.warn( + `League entries fetch failed for ${puuid}: ${ + (err as Error)?.message ?? err + }`, + ); + return { status: 'failed', dto: null }; + } + } + + private async fetchMasteriesSafe( + puuid: string, + platform: RiotPlatformRoute, + ): Promise< + | { status: 'updated'; dto: RiotChampionMasteryDto[] } + | { status: 'failed'; dto: null } + > { + try { + const dto = await this.masteryService.getTopByPuuid(puuid, { + platform, + count: MASTERY_LIMIT, + }); + return { status: 'updated', dto }; + } catch (err) { + this.logger.warn( + `Champion masteries fetch failed for ${puuid}: ${ + (err as Error)?.message ?? err + }`, + ); + return { status: 'failed', dto: null }; + } + } + + private async fetchRecentMatchesSafe( + puuid: string, + region: RiotRegionalRoute, + seasonStartedAt?: Date, + ): Promise< + | { + status: 'updated'; + summary: RiotAccount['recentStatsSummary']; + matchIds: string[]; + } + | { status: 'failed'; summary: null; matchIds: null } + > { + try { + await this.recentMatchesService.syncRecentMatches({ + puuid, + region, + limit: RIOT_RECENT_MATCH_LIMIT, + }); + const matches = await this.recentMatchesService.loadFromDb({ + puuid, + limit: RIOT_RECENT_MATCH_LIMIT, + }); + const summary = this.recentStatsService.computeSummary( + matches.map((match) => match.raw as unknown as RiotMatchDto), + puuid, + { seasonStartedAt }, + ); + return { + status: 'updated', + summary, + matchIds: matches.map((match) => match.matchId), + }; + } catch (err) { + this.logger.warn( + `Recent matches fetch failed for ${puuid}: ${ + (err as Error)?.message ?? err + }`, + ); + return { status: 'failed', summary: null, matchIds: null }; + } + } + + private applySummoner(account: RiotAccount, dto: RiotSummonerDto): void { + account.profileIconId = dto.profileIconId; + account.revisionDate = dto.revisionDate; + account.summonerLevel = dto.summonerLevel; + } + + private applyLeagueEntries( + account: RiotAccount, + entries: RiotLeagueEntryDto[], + ): void { + const fetchedAt = new Date(); + this.appendTierHistoryIfChanged(account, entries, fetchedAt); + const next: TierInfo[] = entries.map((e) => ({ + leagueId: e.leagueId, + queueType: e.queueType, + tier: e.tier, + rank: e.rank, + puuid: e.puuid, + leaguePoints: e.leaguePoints, + wins: e.wins, + losses: e.losses, + veteran: e.veteran, + inactive: e.inactive, + freshBlood: e.freshBlood, + hotStreak: e.hotStreak, + miniSeries: e.miniSeries, + fetchedAt, + })); + account.tiers = next; + } + + private appendTierHistoryIfChanged( + account: RiotAccount, + entries: RiotLeagueEntryDto[], + recordedAt: Date, + ): void { + for (const entry of entries) { + const last = [...account.tierHistory] + .reverse() + .find((history) => history.queueType === entry.queueType); + const changed = + !last || + last.tier !== entry.tier || + (last.rank ?? '') !== (entry.rank ?? ''); + if (!changed) continue; + + account.tierHistory.push({ + queueType: entry.queueType, + tier: entry.tier, + rank: entry.rank, + leaguePoints: entry.leaguePoints, + wins: entry.wins, + losses: entry.losses, + recordedAt, + }); + } + } + + private applyMasteries( + account: RiotAccount, + masteries: RiotChampionMasteryDto[], + ): void { + const summary: ChampionMasteryEntry[] = masteries + .slice(0, MASTERY_LIMIT) + .map((m) => ({ ...m })); + account.championMasteries = summary; + account.championMasteriesFetchedAt = new Date(); + } + + private applyRecentMatches( + account: RiotAccount, + summary: NonNullable, + matchIds: string[], + ): void { + const fetchedAt = new Date(); + account.recentStatsSummary = summary; + account.recentStatsFetchedAt = fetchedAt; + account.matchIds = matchIds; + account.matchIdsFetchedAt = fetchedAt; + } + + private tiersOldestAt(tiers: TierInfo[]): number { + if (tiers.length === 0) return 0; + let oldest = Infinity; + for (const t of tiers) { + const at = t.fetchedAt instanceof Date ? t.fetchedAt.getTime() : 0; + if (at < oldest) oldest = at; + } + return oldest === Infinity ? 0 : oldest; + } +} diff --git a/apps/api/src/modules/riot/riot-account.service.ts b/apps/api/src/modules/riot/riot-account.service.ts new file mode 100644 index 00000000..58970308 --- /dev/null +++ b/apps/api/src/modules/riot/riot-account.service.ts @@ -0,0 +1,128 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RIOT_PLATFORM_ROUTES, + RiotAccountDto, + RiotAccountLookupOptions, + RiotAccountRegionDto, +} from './riot.types'; + +@Injectable() +export class RiotAccountService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getByRiotId( + gameName: string, + tagLine: string, + options: RiotAccountLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`, + { + region: options.region, + signal: options.signal, + }, + parseRiotAccountDto, + ); + } + + public async getByPuuid( + puuid: string, + options: RiotAccountLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/riot/account/v1/accounts/by-puuid/${encodeURIComponent(puuid)}`, + { + region: options.region, + signal: options.signal, + }, + parseRiotAccountDto, + ); + } + + public async getRegionByPuuid( + puuid: string, + options: RiotAccountLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/riot/account/v1/region/by-game/lol/by-puuid/${encodeURIComponent(puuid)}`, + { + region: options.region ?? 'asia', + signal: options.signal, + }, + parseRiotAccountRegionDto, + ); + } +} + +function parseRiotAccountDto(value: unknown): RiotAccountDto { + if (!isRecord(value)) { + throw new TypeError('Riot account response must be an object.'); + } + + const puuid = value.puuid; + const gameName = value.gameName; + const tagLine = value.tagLine; + + if (!isNonEmptyString(puuid)) { + throw new TypeError('Riot account response is missing a valid puuid.'); + } + + if (!isOptionalString(gameName)) { + throw new TypeError('Riot account response has an invalid gameName.'); + } + + if (!isOptionalString(tagLine)) { + throw new TypeError('Riot account response has an invalid tagLine.'); + } + + return { + puuid, + gameName: gameName ?? null, + tagLine: tagLine ?? null, + }; +} + +function parseRiotAccountRegionDto(value: unknown): RiotAccountRegionDto { + if (!isRecord(value)) { + throw new TypeError('Riot account region response must be an object.'); + } + + const puuid = value.puuid; + const game = value.game; + const region = value.region; + + if (!isNonEmptyString(puuid)) { + throw new TypeError( + 'Riot account region response is missing a valid puuid.', + ); + } + if (!isNonEmptyString(game)) { + throw new TypeError( + 'Riot account region response is missing a valid game.', + ); + } + const platformRegion = region as (typeof RIOT_PLATFORM_ROUTES)[number]; + if ( + !isNonEmptyString(region) || + !RIOT_PLATFORM_ROUTES.includes(platformRegion) + ) { + throw new TypeError( + 'Riot account region response is missing a valid region.', + ); + } + + return { puuid, game, region: platformRegion }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} + +function isOptionalString(value: unknown): value is string | undefined { + return value === undefined || typeof value === 'string'; +} diff --git a/apps/api/src/modules/riot/riot-champion-mastery.service.ts b/apps/api/src/modules/riot/riot-champion-mastery.service.ts new file mode 100644 index 00000000..abfc58c2 --- /dev/null +++ b/apps/api/src/modules/riot/riot-champion-mastery.service.ts @@ -0,0 +1,129 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RiotChampionMasteryDto, + RiotPlatformLookupOptions, +} from './riot.types'; + +interface MasteriesByPuuidOptions extends RiotPlatformLookupOptions { + count?: number; +} + +const DEFAULT_TOP_MASTERY_COUNT = 10; +const MAX_TOP_MASTERY_COUNT = 10; + +@Injectable() +export class RiotChampionMasteryService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getByPuuid( + puuid: string, + options: RiotPlatformLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}`, + { + platform: options.platform ?? 'kr', + signal: options.signal, + }, + parseMasteries, + ); + } + + public async getTopByPuuid( + puuid: string, + options: MasteriesByPuuidOptions = {}, + ): Promise { + const count = options.count ?? DEFAULT_TOP_MASTERY_COUNT; + if ( + !Number.isInteger(count) || + count <= 0 || + count > MAX_TOP_MASTERY_COUNT + ) { + throw new RangeError('count must be an integer between 1 and 10.'); + } + return this.riotClientService.get( + `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`, + { + platform: options.platform ?? 'kr', + signal: options.signal, + query: { count }, + }, + parseMasteries, + ); + } +} + +function parseMasteries(value: unknown): RiotChampionMasteryDto[] { + if (!Array.isArray(value)) { + throw new TypeError('Champion masteries response must be an array.'); + } + return value.map((entry, index) => parseEntry(entry, index)); +} + +function parseEntry(value: unknown, index: number): RiotChampionMasteryDto { + if (!isRecord(value)) { + throw new TypeError(`championMasteries[${index}] must be an object.`); + } + const puuid = value.puuid; + const championId = value.championId; + const championLevel = value.championLevel; + const championPoints = value.championPoints; + if (typeof puuid !== 'string') { + throw new TypeError(`championMasteries[${index}].puuid must be a string.`); + } + if (typeof championId !== 'number' || !Number.isFinite(championId)) { + throw new TypeError( + `championMasteries[${index}].championId must be a number.`, + ); + } + if (typeof championLevel !== 'number' || !Number.isFinite(championLevel)) { + throw new TypeError( + `championMasteries[${index}].championLevel must be a number.`, + ); + } + if (typeof championPoints !== 'number' || !Number.isFinite(championPoints)) { + throw new TypeError( + `championMasteries[${index}].championPoints must be a number.`, + ); + } + return { + ...value, + puuid, + championId, + championLevel, + championPoints, + lastPlayTime: + typeof value.lastPlayTime === 'number' ? value.lastPlayTime : undefined, + championPointsSinceLastLevel: + typeof value.championPointsSinceLastLevel === 'number' + ? value.championPointsSinceLastLevel + : undefined, + championPointsUntilNextLevel: + typeof value.championPointsUntilNextLevel === 'number' + ? value.championPointsUntilNextLevel + : undefined, + markRequiredForNextLevel: + typeof value.markRequiredForNextLevel === 'number' + ? value.markRequiredForNextLevel + : undefined, + tokensEarned: + typeof value.tokensEarned === 'number' ? value.tokensEarned : undefined, + championSeasonMilestone: + typeof value.championSeasonMilestone === 'number' + ? value.championSeasonMilestone + : undefined, + milestoneGrades: Array.isArray(value.milestoneGrades) + ? (value.milestoneGrades as unknown[]).filter( + (v): v is string => typeof v === 'string', + ) + : undefined, + nextSeasonMilestone: isRecord(value.nextSeasonMilestone) + ? value.nextSeasonMilestone + : undefined, + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} diff --git a/apps/api/src/modules/riot/riot-ddragon.controller.ts b/apps/api/src/modules/riot/riot-ddragon.controller.ts new file mode 100644 index 00000000..4dbd58a0 --- /dev/null +++ b/apps/api/src/modules/riot/riot-ddragon.controller.ts @@ -0,0 +1,19 @@ +import { Controller, Get, Query } from '@nestjs/common'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import { + RiotDdragonService, + type DdragonManifest, +} from './riot-ddragon.service'; + +@Controller('riot/ddragon') +export class RiotDdragonController { + constructor(private readonly ddragonService: RiotDdragonService) {} + + @Get('manifest') + @AllowPublicAccess() + public async getManifest( + @Query('locale') locale?: string, + ): Promise { + return this.ddragonService.getManifest(locale ?? 'ko_KR'); + } +} diff --git a/apps/api/src/modules/riot/riot-ddragon.service.ts b/apps/api/src/modules/riot/riot-ddragon.service.ts new file mode 100644 index 00000000..218e87ca --- /dev/null +++ b/apps/api/src/modules/riot/riot-ddragon.service.ts @@ -0,0 +1,142 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { GarnetService } from '../global/garnet/garnet.service'; + +const DDRAGON_BASE = 'https://ddragon.leagueoflegends.com'; +const DDRAGON_CDN = `${DDRAGON_BASE}/cdn`; +const DEFAULT_LOCALE = 'ko_KR'; +const CACHE_TTL_SECONDS = 24 * 60 * 60; +const CACHE_VERSION = 'v2'; +const FETCH_TIMEOUT_MS = 10_000; + +export interface DdragonChampionEntry { + key: string; + name: string; +} + +export interface DdragonManifest { + version: string; + cdn: string; + locale: string; + champions: Record; + fetchedAt: string; +} + +interface ChampionDataEntry { + key: string; + id: string; + name: string; +} + +interface ChampionDataResponse { + data: Record; +} + +@Injectable() +export class RiotDdragonService { + private readonly logger = new Logger(RiotDdragonService.name); + private inflight = new Map>(); + + constructor(private readonly garnetService: GarnetService) {} + + public async getManifest(locale: string = DEFAULT_LOCALE): Promise { + const normalizedLocale = normalizeLocale(locale); + const cacheKey = manifestCacheKey(normalizedLocale); + + const cached = await this.garnetService.getJson(cacheKey); + if (cached) return cached; + + const pending = this.inflight.get(cacheKey); + if (pending) return pending; + + const promise = this.buildManifest(normalizedLocale) + .then(async (manifest) => { + await this.garnetService.setJson(cacheKey, manifest, CACHE_TTL_SECONDS); + return manifest; + }) + .finally(() => { + this.inflight.delete(cacheKey); + }); + + this.inflight.set(cacheKey, promise); + return promise; + } + + private async buildManifest(locale: string): Promise { + const version = await this.fetchLatestVersion(); + const champions = await this.fetchChampionMap(version, locale); + return { + version, + cdn: DDRAGON_CDN, + locale, + champions, + fetchedAt: new Date().toISOString(), + }; + } + + private async fetchLatestVersion(): Promise { + const versions = await this.fetchJson(`${DDRAGON_BASE}/api/versions.json`); + if (!Array.isArray(versions) || typeof versions[0] !== 'string') { + throw new Error('ddragon versions.json response is malformed.'); + } + return versions[0]; + } + + private async fetchChampionMap( + version: string, + locale: string, + ): Promise> { + const url = `${DDRAGON_CDN}/${version}/data/${locale}/champion.json`; + const payload = await this.fetchJson(url); + if (!payload || typeof payload !== 'object' || !payload.data) { + throw new Error(`ddragon champion.json response is malformed (${url}).`); + } + + const map: Record = {}; + for (const entry of Object.values(payload.data)) { + if (entry?.key && entry.id) { + map[entry.key] = { + key: entry.id, + name: typeof entry.name === 'string' ? entry.name : entry.id, + }; + } + } + return map; + } + + private async fetchJson(url: string): Promise { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS); + try { + const response = await fetch(url, { + method: 'GET', + headers: { Accept: 'application/json' }, + signal: controller.signal, + }); + if (!response.ok) { + throw new Error( + `ddragon request failed (${response.status}): ${url}`, + ); + } + return (await response.json()) as T; + } catch (err) { + this.logger.error( + `ddragon fetch error for ${url}: ${(err as Error)?.message ?? err}`, + ); + throw err; + } finally { + clearTimeout(timeout); + } + } +} + +function normalizeLocale(locale: string): string { + const trimmed = locale.trim(); + if (!/^[a-zA-Z]{2}_[a-zA-Z]{2}$/.test(trimmed)) { + return DEFAULT_LOCALE; + } + return `${trimmed.slice(0, 2).toLowerCase()}_${trimmed.slice(3).toUpperCase()}`; +} + +function manifestCacheKey(locale: string): string { + return `ddragon:manifest:${CACHE_VERSION}:${locale}`; +} diff --git a/apps/api/src/modules/riot/riot-league.service.ts b/apps/api/src/modules/riot/riot-league.service.ts new file mode 100644 index 00000000..a8c4614c --- /dev/null +++ b/apps/api/src/modules/riot/riot-league.service.ts @@ -0,0 +1,79 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RiotLeagueEntryDto, + RiotPlatformLookupOptions, +} from './riot.types'; + +@Injectable() +export class RiotLeagueService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getEntriesByPuuid( + puuid: string, + options: RiotPlatformLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`, + { + platform: options.platform ?? 'kr', + signal: options.signal, + }, + parseLeagueEntries, + ); + } +} + +function parseLeagueEntries(value: unknown): RiotLeagueEntryDto[] { + if (!Array.isArray(value)) { + throw new TypeError('League entries response must be an array.'); + } + return value.map((entry, index) => parseEntry(entry, index)); +} + +function parseEntry(value: unknown, index: number): RiotLeagueEntryDto { + if (!isRecord(value)) { + throw new TypeError(`leagueEntries[${index}] must be an object.`); + } + return { + leagueId: requireString(value.leagueId, `leagueEntries[${index}].leagueId`), + queueType: requireString( + value.queueType, + `leagueEntries[${index}].queueType`, + ), + tier: requireString(value.tier, `leagueEntries[${index}].tier`), + rank: requireString(value.rank, `leagueEntries[${index}].rank`), + puuid: requireString(value.puuid, `leagueEntries[${index}].puuid`), + leaguePoints: requireNumber( + value.leaguePoints, + `leagueEntries[${index}].leaguePoints`, + ), + wins: requireNumber(value.wins, `leagueEntries[${index}].wins`), + losses: requireNumber(value.losses, `leagueEntries[${index}].losses`), + veteran: typeof value.veteran === 'boolean' ? value.veteran : undefined, + inactive: typeof value.inactive === 'boolean' ? value.inactive : undefined, + freshBlood: + typeof value.freshBlood === 'boolean' ? value.freshBlood : undefined, + hotStreak: + typeof value.hotStreak === 'boolean' ? value.hotStreak : undefined, + miniSeries: isRecord(value.miniSeries) ? value.miniSeries : undefined, + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function requireString(value: unknown, path: string): string { + if (typeof value !== 'string' || value.length === 0) { + throw new TypeError(`${path} must be a non-empty string.`); + } + return value; +} + +function requireNumber(value: unknown, path: string): number { + if (typeof value !== 'number' || !Number.isFinite(value)) { + throw new TypeError(`${path} must be a finite number.`); + } + return value; +} diff --git a/apps/api/src/modules/riot/riot-match.service.spec.ts b/apps/api/src/modules/riot/riot-match.service.spec.ts new file mode 100644 index 00000000..6aef710b --- /dev/null +++ b/apps/api/src/modules/riot/riot-match.service.spec.ts @@ -0,0 +1,109 @@ +import { RiotClientService } from './riot.client.service'; +import { RiotMatchService } from './riot-match.service'; +import type { RiotResponseParser } from './riot.types'; + +function createMatchPayload() { + const participant = { + assists: 7, + champExperience: 12000, + champLevel: 16, + championId: 103, + championName: 'Ahri', + deaths: 2, + goldEarned: 12000, + goldSpent: 11000, + individualPosition: '', + item0: 0, + item1: 0, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 0, + kills: 8, + neutralMinionsKilled: 12, + participantId: 1, + perks: { + statPerks: { defense: 0, flex: 0, offense: 0 }, + styles: [], + }, + puuid: 'puuid-1', + riotIdGameName: '테스터', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 14, + summonerId: 'summoner-id-1', + summonerLevel: 100, + summonerName: '', + teamId: 100, + teamPosition: '', + timePlayed: 1800, + totalDamageDealtToChampions: 22000, + totalDamageTaken: 11000, + totalMinionsKilled: 180, + visionScore: 20, + wardsKilled: 2, + wardsPlaced: 10, + win: true, + }; + + return { + metadata: { + dataVersion: '2', + matchId: 'KR_8188913502', + participants: ['puuid-1'], + }, + info: { + gameCreation: 1777000000000, + gameDuration: 1800, + gameEndTimestamp: 1777001800000, + gameId: 8188913502, + gameMode: 'CLASSIC', + gameName: 'teambuilder-match-8188913502', + gameStartTimestamp: 1777000000000, + gameType: 'MATCHED_GAME', + gameVersion: '15.8.1', + mapId: 11, + participants: [participant], + platformId: 'KR', + queueId: 420, + teams: [ + { + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: true, kills: 25 }, + dragon: { first: true, kills: 3 }, + inhibitor: { first: false, kills: 1 }, + riftHerald: { first: true, kills: 1 }, + tower: { first: true, kills: 8 }, + }, + teamId: 100, + win: true, + }, + ], + }, + }; +} + +describe('RiotMatchService', () => { + it('accepts empty Riot display fields in match participants', async () => { + const payload = createMatchPayload(); + const riotClientService = { + get: jest.fn( + async ( + _path: string, + _options: unknown, + parser?: RiotResponseParser, + ) => (parser ? parser(payload) : (payload as T)), + ), + } as unknown as RiotClientService; + const service = new RiotMatchService(riotClientService); + + const match = await service.getMatch('KR_8188913502', { region: 'asia' }); + + expect(match.info.participants[0].summonerName).toBe(''); + expect(match.info.participants[0].teamPosition).toBe(''); + expect(match.info.participants[0].individualPosition).toBe(''); + }); +}); diff --git a/apps/api/src/modules/riot/riot-match.service.ts b/apps/api/src/modules/riot/riot-match.service.ts new file mode 100644 index 00000000..33aaeb86 --- /dev/null +++ b/apps/api/src/modules/riot/riot-match.service.ts @@ -0,0 +1,630 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RiotMatchBanDto, + RiotMatchDto, + RiotMatchIdsLookupOptions, + RiotMatchInfoDto, + RiotMatchLookupOptions, + RiotMatchMetadataDto, + RiotMatchObjectiveDto, + RiotMatchObjectivesDto, + RiotMatchParticipantDto, + RiotMatchPerksDto, + RiotMatchPerkStyleDto, + RiotMatchPerkStyleSelectionDto, + RiotMatchStatPerksDto, + RiotMatchTeamDto, + RiotMatchType, +} from './riot.types'; + +const RIOT_MATCH_TYPES: RiotMatchType[] = [ + 'ranked', + 'normal', + 'tourney', + 'tutorial', +]; + +@Injectable() +export class RiotMatchService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getMatchIdsByPuuid( + puuid: string, + options: RiotMatchIdsLookupOptions = {}, + ): Promise { + validateMatchIdsLookupOptions(options); + + return this.riotClientService.get( + `/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`, + { + region: options.region, + signal: options.signal, + query: { + start: options.start, + count: options.count, + queue: options.queue, + type: options.type, + startTime: options.startTime, + endTime: options.endTime, + }, + }, + parseMatchIdsResponse, + ); + } + + public async getMatch( + matchId: string, + options: RiotMatchLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/match/v5/matches/${encodeURIComponent(matchId)}`, + { + region: options.region, + signal: options.signal, + }, + parseMatchResponse, + ); + } +} + +function validateMatchIdsLookupOptions( + options: RiotMatchIdsLookupOptions, +): void { + assertOptionalNonNegativeInteger(options.start, 'start'); + assertOptionalRange(options.count, 'count', 0, 100); + assertOptionalNonNegativeInteger(options.queue, 'queue'); + assertOptionalNonNegativeInteger(options.startTime, 'startTime'); + assertOptionalNonNegativeInteger(options.endTime, 'endTime'); + + if (options.type !== undefined && !RIOT_MATCH_TYPES.includes(options.type)) { + throw new RangeError( + `type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`, + ); + } + + if ( + options.startTime !== undefined && + options.endTime !== undefined && + options.startTime > options.endTime + ) { + throw new RangeError('startTime must be less than or equal to endTime.'); + } +} + +function parseMatchIdsResponse(value: unknown): string[] { + if (!Array.isArray(value)) { + throw new TypeError('Riot match ids response must be an array.'); + } + + if (!value.every(isNonEmptyString)) { + throw new TypeError('Riot match ids response must contain only strings.'); + } + + return value; +} + +function parseMatchResponse(value: unknown): RiotMatchDto { + if (!isRecord(value)) { + throw new TypeError('Riot match response must be an object.'); + } + + return { + metadata: parseMatchMetadata(value.metadata), + info: parseMatchInfo(value.info), + }; +} + +function parseMatchMetadata(value: unknown): RiotMatchMetadataDto { + if (!isRecord(value)) { + throw new TypeError('Riot match metadata must be an object.'); + } + + const dataVersion = value.dataVersion; + const matchId = value.matchId; + const participants = value.participants; + + if (!isNonEmptyString(dataVersion)) { + throw new TypeError('Riot match metadata.dataVersion must be a string.'); + } + + if (!isNonEmptyString(matchId)) { + throw new TypeError('Riot match metadata.matchId must be a string.'); + } + + if (!Array.isArray(participants) || !participants.every(isNonEmptyString)) { + throw new TypeError( + 'Riot match metadata.participants must be an array of strings.', + ); + } + + return { + dataVersion, + matchId, + participants, + }; +} + +function parseMatchInfo(value: unknown): RiotMatchInfoDto { + if (!isRecord(value)) { + throw new TypeError('Riot match info must be an object.'); + } + + const participants = value.participants; + const teams = value.teams; + + if (!Array.isArray(participants)) { + throw new TypeError('Riot match info.participants must be an array.'); + } + + if (!Array.isArray(teams)) { + throw new TypeError('Riot match info.teams must be an array.'); + } + + const gameCreation = requireNumber(value.gameCreation, 'info.gameCreation'); + const gameDuration = requireNumber(value.gameDuration, 'info.gameDuration'); + const gameId = requireNumber(value.gameId, 'info.gameId'); + const gameMode = requireString(value.gameMode, 'info.gameMode'); + const gameName = requireString(value.gameName, 'info.gameName'); + const gameStartTimestamp = requireNumber( + value.gameStartTimestamp, + 'info.gameStartTimestamp', + ); + const gameType = requireString(value.gameType, 'info.gameType'); + const gameVersion = requireString(value.gameVersion, 'info.gameVersion'); + const mapId = requireNumber(value.mapId, 'info.mapId'); + const platformId = requireString(value.platformId, 'info.platformId'); + const queueId = requireNumber(value.queueId, 'info.queueId'); + const gameEndTimestamp = optionalNumber( + value.gameEndTimestamp, + 'info.gameEndTimestamp', + ); + const tournamentCode = optionalString( + value.tournamentCode, + 'info.tournamentCode', + ); + const endOfGameResult = optionalString( + value.endOfGameResult, + 'info.endOfGameResult', + ); + + return { + ...value, + endOfGameResult, + gameCreation, + gameDuration, + gameEndTimestamp, + gameId, + gameMode, + gameName, + gameStartTimestamp, + gameType, + gameVersion, + mapId, + participants: participants.map((participant, index) => + parseParticipant(participant, index), + ), + platformId, + queueId, + teams: teams.map((team, index) => parseTeam(team, index)), + tournamentCode, + }; +} + +function parseParticipant( + value: unknown, + index: number, +): RiotMatchParticipantDto { + if (!isRecord(value)) { + throw new TypeError(`participants[${index}] must be an object.`); + } + + return { + ...value, + assists: requireNumber(value.assists, `participants[${index}].assists`), + champExperience: requireNumber( + value.champExperience, + `participants[${index}].champExperience`, + ), + champLevel: requireNumber( + value.champLevel, + `participants[${index}].champLevel`, + ), + championId: requireNumber( + value.championId, + `participants[${index}].championId`, + ), + championName: requireString( + value.championName, + `participants[${index}].championName`, + ), + deaths: requireNumber(value.deaths, `participants[${index}].deaths`), + goldEarned: requireNumber( + value.goldEarned, + `participants[${index}].goldEarned`, + ), + goldSpent: requireNumber( + value.goldSpent, + `participants[${index}].goldSpent`, + ), + individualPosition: requireStringAllowEmpty( + value.individualPosition, + `participants[${index}].individualPosition`, + ), + item0: requireNumber(value.item0, `participants[${index}].item0`), + item1: requireNumber(value.item1, `participants[${index}].item1`), + item2: requireNumber(value.item2, `participants[${index}].item2`), + item3: requireNumber(value.item3, `participants[${index}].item3`), + item4: requireNumber(value.item4, `participants[${index}].item4`), + item5: requireNumber(value.item5, `participants[${index}].item5`), + item6: requireNumber(value.item6, `participants[${index}].item6`), + kills: requireNumber(value.kills, `participants[${index}].kills`), + neutralMinionsKilled: requireNumber( + value.neutralMinionsKilled, + `participants[${index}].neutralMinionsKilled`, + ), + participantId: requireNumber( + value.participantId, + `participants[${index}].participantId`, + ), + perks: parsePerks(value.perks, index), + puuid: requireString(value.puuid, `participants[${index}].puuid`), + riotIdGameName: optionalString( + value.riotIdGameName, + `participants[${index}].riotIdGameName`, + ), + riotIdTagLine: optionalString( + value.riotIdTagLine, + `participants[${index}].riotIdTagLine`, + ), + summoner1Id: requireNumber( + value.summoner1Id, + `participants[${index}].summoner1Id`, + ), + summoner2Id: requireNumber( + value.summoner2Id, + `participants[${index}].summoner2Id`, + ), + summonerId: requireString( + value.summonerId, + `participants[${index}].summonerId`, + ), + summonerLevel: requireNumber( + value.summonerLevel, + `participants[${index}].summonerLevel`, + ), + summonerName: requireStringAllowEmpty( + value.summonerName, + `participants[${index}].summonerName`, + ), + teamId: requireNumber(value.teamId, `participants[${index}].teamId`), + teamPosition: requireStringAllowEmpty( + value.teamPosition, + `participants[${index}].teamPosition`, + ), + timePlayed: requireNumber( + value.timePlayed, + `participants[${index}].timePlayed`, + ), + totalDamageDealtToChampions: requireNumber( + value.totalDamageDealtToChampions, + `participants[${index}].totalDamageDealtToChampions`, + ), + totalDamageTaken: requireNumber( + value.totalDamageTaken, + `participants[${index}].totalDamageTaken`, + ), + totalMinionsKilled: requireNumber( + value.totalMinionsKilled, + `participants[${index}].totalMinionsKilled`, + ), + visionScore: requireNumber( + value.visionScore, + `participants[${index}].visionScore`, + ), + wardsKilled: requireNumber( + value.wardsKilled, + `participants[${index}].wardsKilled`, + ), + wardsPlaced: requireNumber( + value.wardsPlaced, + `participants[${index}].wardsPlaced`, + ), + win: requireBoolean(value.win, `participants[${index}].win`), + }; +} + +function parsePerks(value: unknown, participantIndex: number): RiotMatchPerksDto { + if (!isRecord(value)) { + throw new TypeError( + `participants[${participantIndex}].perks must be an object.`, + ); + } + + const styles = value.styles; + if (!Array.isArray(styles)) { + throw new TypeError( + `participants[${participantIndex}].perks.styles must be an array.`, + ); + } + + return { + statPerks: parseStatPerks(value.statPerks, participantIndex), + styles: styles.map((style, styleIndex) => + parsePerkStyle(style, participantIndex, styleIndex), + ), + }; +} + +function parseStatPerks( + value: unknown, + participantIndex: number, +): RiotMatchStatPerksDto { + if (!isRecord(value)) { + throw new TypeError( + `participants[${participantIndex}].perks.statPerks must be an object.`, + ); + } + + return { + defense: requireNumber( + value.defense, + `participants[${participantIndex}].perks.statPerks.defense`, + ), + flex: requireNumber( + value.flex, + `participants[${participantIndex}].perks.statPerks.flex`, + ), + offense: requireNumber( + value.offense, + `participants[${participantIndex}].perks.statPerks.offense`, + ), + }; +} + +function parsePerkStyle( + value: unknown, + participantIndex: number, + styleIndex: number, +): RiotMatchPerkStyleDto { + if (!isRecord(value)) { + throw new TypeError( + `participants[${participantIndex}].perks.styles[${styleIndex}] must be an object.`, + ); + } + + const selections = value.selections; + if (!Array.isArray(selections)) { + throw new TypeError( + `participants[${participantIndex}].perks.styles[${styleIndex}].selections must be an array.`, + ); + } + + return { + description: requireString( + value.description, + `participants[${participantIndex}].perks.styles[${styleIndex}].description`, + ), + selections: selections.map((selection, selectionIndex) => + parsePerkSelection( + selection, + participantIndex, + styleIndex, + selectionIndex, + ), + ), + style: requireNumber( + value.style, + `participants[${participantIndex}].perks.styles[${styleIndex}].style`, + ), + }; +} + +function parsePerkSelection( + value: unknown, + participantIndex: number, + styleIndex: number, + selectionIndex: number, +): RiotMatchPerkStyleSelectionDto { + if (!isRecord(value)) { + throw new TypeError( + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}] must be an object.`, + ); + } + + return { + perk: requireNumber( + value.perk, + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].perk`, + ), + var1: requireNumber( + value.var1, + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var1`, + ), + var2: requireNumber( + value.var2, + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var2`, + ), + var3: requireNumber( + value.var3, + `participants[${participantIndex}].perks.styles[${styleIndex}].selections[${selectionIndex}].var3`, + ), + }; +} + +function parseTeam(value: unknown, index: number): RiotMatchTeamDto { + if (!isRecord(value)) { + throw new TypeError(`teams[${index}] must be an object.`); + } + + const bans = value.bans; + if (!Array.isArray(bans)) { + throw new TypeError(`teams[${index}].bans must be an array.`); + } + + return { + ...value, + bans: bans.map((ban, banIndex) => parseBan(ban, index, banIndex)), + objectives: parseObjectives(value.objectives, index), + teamId: requireNumber(value.teamId, `teams[${index}].teamId`), + win: requireBoolean(value.win, `teams[${index}].win`), + }; +} + +function parseBan( + value: unknown, + teamIndex: number, + banIndex: number, +): RiotMatchBanDto { + if (!isRecord(value)) { + throw new TypeError(`teams[${teamIndex}].bans[${banIndex}] must be an object.`); + } + + return { + championId: requireNumber( + value.championId, + `teams[${teamIndex}].bans[${banIndex}].championId`, + ), + pickTurn: requireNumber( + value.pickTurn, + `teams[${teamIndex}].bans[${banIndex}].pickTurn`, + ), + }; +} + +function parseObjectives( + value: unknown, + teamIndex: number, +): RiotMatchObjectivesDto { + if (!isRecord(value)) { + throw new TypeError(`teams[${teamIndex}].objectives must be an object.`); + } + + return { + baron: parseObjective(value.baron, teamIndex, 'baron'), + champion: parseObjective(value.champion, teamIndex, 'champion'), + dragon: parseObjective(value.dragon, teamIndex, 'dragon'), + inhibitor: parseObjective(value.inhibitor, teamIndex, 'inhibitor'), + riftHerald: parseObjective(value.riftHerald, teamIndex, 'riftHerald'), + tower: parseObjective(value.tower, teamIndex, 'tower'), + }; +} + +function parseObjective( + value: unknown, + teamIndex: number, + key: keyof RiotMatchObjectivesDto, +): RiotMatchObjectiveDto { + if (!isRecord(value)) { + throw new TypeError(`teams[${teamIndex}].objectives.${key} must be an object.`); + } + + return { + first: requireBoolean( + value.first, + `teams[${teamIndex}].objectives.${key}.first`, + ), + kills: requireNumber( + value.kills, + `teams[${teamIndex}].objectives.${key}.kills`, + ), + }; +} + +function requireString(value: unknown, path: string): string { + if (!isNonEmptyString(value)) { + throw new TypeError(`${path} must be a non-empty string.`); + } + + return value; +} + +function requireStringAllowEmpty(value: unknown, path: string): string { + if (typeof value !== 'string') { + throw new TypeError(`${path} must be a string.`); + } + + return value; +} + +function optionalString(value: unknown, path: string): string | undefined { + if (value === undefined || value === null) { + return undefined; + } + + if (typeof value !== 'string') { + throw new TypeError(`${path} must be a string when present.`); + } + + return value; +} + +function requireNumber(value: unknown, path: string): number { + if (!isFiniteNumber(value)) { + throw new TypeError(`${path} must be a finite number.`); + } + + return value; +} + +function optionalNumber(value: unknown, path: string): number | undefined { + if (value === undefined || value === null) { + return undefined; + } + + if (!isFiniteNumber(value)) { + throw new TypeError(`${path} must be a finite number when present.`); + } + + return value; +} + +function requireBoolean(value: unknown, path: string): boolean { + if (typeof value !== 'boolean') { + throw new TypeError(`${path} must be a boolean.`); + } + + return value; +} + +function assertOptionalNonNegativeInteger( + value: number | undefined, + fieldName: string, +): void { + if (value === undefined) { + return; + } + + if (!Number.isInteger(value) || value < 0) { + throw new RangeError(`${fieldName} must be a non-negative integer.`); + } +} + +function assertOptionalRange( + value: number | undefined, + fieldName: string, + min: number, + max: number, +): void { + if (value === undefined) { + return; + } + + if (!Number.isInteger(value) || value < min || value > max) { + throw new RangeError( + `${fieldName} must be an integer between ${min} and ${max}.`, + ); + } +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} + +function isFiniteNumber(value: unknown): value is number { + return typeof value === 'number' && Number.isFinite(value); +} + +function isNonEmptyString(value: unknown): value is string { + return typeof value === 'string' && value.length > 0; +} diff --git a/apps/api/src/modules/riot/riot-queue.constants.ts b/apps/api/src/modules/riot/riot-queue.constants.ts new file mode 100644 index 00000000..70b3ae05 --- /dev/null +++ b/apps/api/src/modules/riot/riot-queue.constants.ts @@ -0,0 +1,88 @@ +export type RiotQueueGroup = + | 'all' + | 'summoners-rift' + | 'aram' + | 'urf' + | 'arena'; + +export type RiotRankFilter = 'all' | 'solo' | 'flex' | 'normal'; + +export interface RiotQueueGroupConfig { + label: string; + queues: Record; +} + +export const RIOT_QUEUE_GROUPS: Record = { + all: { + label: '전체', + queues: { + all: [400, 420, 430, 440, 450, 900, 1900, 1700, 1710], + solo: [420], + flex: [440], + normal: [400, 430, 450, 900, 1900, 1700, 1710], + }, + }, + 'summoners-rift': { + label: '소환사의 협곡', + queues: { + all: [400, 420, 430, 440], + solo: [420], + flex: [440], + normal: [400, 430], + }, + }, + aram: { + label: '칼바람 나락', + queues: { + all: [450], + solo: [], + flex: [], + normal: [450], + }, + }, + urf: { + label: '우르프', + queues: { + all: [900, 1900], + solo: [], + flex: [], + normal: [900, 1900], + }, + }, + arena: { + label: '아레나', + queues: { + all: [1700, 1710], + solo: [], + flex: [], + normal: [1700, 1710], + }, + }, +}; + +export const RIOT_QUEUE_LABELS: Record = { + 400: '일반 교차 선택', + 420: '솔로 랭크', + 430: '일반 비공개 선택', + 440: '자유 랭크', + 450: '칼바람 나락', + 900: '우르프', + 1700: '아레나', + 1710: '아레나', + 1900: '우르프', +}; + +export function resolveRiotQueueIds( + queueGroup: RiotQueueGroup, + rank: RiotRankFilter, +): number[] { + return RIOT_QUEUE_GROUPS[queueGroup].queues[rank]; +} + +export function isRiotQueueGroup(value: string): value is RiotQueueGroup { + return value in RIOT_QUEUE_GROUPS; +} + +export function isRiotRankFilter(value: string): value is RiotRankFilter { + return value === 'all' || value === 'solo' || value === 'flex' || value === 'normal'; +} diff --git a/apps/api/src/modules/riot/riot-rate-limiter.service.ts b/apps/api/src/modules/riot/riot-rate-limiter.service.ts new file mode 100644 index 00000000..d25a5b59 --- /dev/null +++ b/apps/api/src/modules/riot/riot-rate-limiter.service.ts @@ -0,0 +1,107 @@ +import { Injectable, Logger } from '@nestjs/common'; +import type { RiotPlatformRoute, RiotRegionalRoute } from './riot.types'; +import { GarnetService } from '../global/garnet/garnet.service'; + +const APP_LIMITS = [ + { windowMs: 1_000, max: 15 }, + { windowMs: 120_000, max: 90 }, +] as const; + +const ACQUIRE_SCRIPT = ` +local now = tonumber(ARGV[1]) +local member = ARGV[2] +local maxWait = 0 + +for i = 1, #KEYS do + local argIndex = 3 + ((i - 1) * 2) + local windowMs = tonumber(ARGV[argIndex]) + local limit = tonumber(ARGV[argIndex + 1]) + local key = KEYS[i] + + redis.call('ZREMRANGEBYSCORE', key, '-inf', now - windowMs) + local count = redis.call('ZCARD', key) + if count >= limit then + local oldest = redis.call('ZRANGE', key, 0, 0, 'WITHSCORES') + local waitMs = windowMs + if oldest[2] then + waitMs = windowMs - (now - tonumber(oldest[2])) + 1 + end + if waitMs > maxWait then + maxWait = waitMs + end + end +end + +if maxWait > 0 then + return maxWait +end + +for i = 1, #KEYS do + local argIndex = 3 + ((i - 1) * 2) + local windowMs = tonumber(ARGV[argIndex]) + local key = KEYS[i] + redis.call('ZADD', key, now, member) + redis.call('PEXPIRE', key, windowMs) +end + +return 0 +`; + +@Injectable() +export class RiotRateLimiterService { + private readonly logger = new Logger(RiotRateLimiterService.name); + + constructor(private readonly garnet: GarnetService) {} + + public async acquire( + route: RiotRegionalRoute | RiotPlatformRoute, + ): Promise { + for (;;) { + const now = Date.now(); + const waitMs = await this.checkAndAdd(route, now); + if (waitMs <= 0) return; + + if (waitMs >= 100) { + this.logger.warn( + `Riot API throttle waiting ${waitMs}ms for route=${route}.`, + ); + } + await sleep(waitMs); + } + } + + private async checkAndAdd( + route: RiotRegionalRoute | RiotPlatformRoute, + now: number, + ): Promise { + const client = this.garnet.raw(); + const keys = APP_LIMITS.map( + (limit) => `riot:rl:${route}:${limit.windowMs}`, + ); + const member = `${process.pid}:${now}:${Math.random().toString(36).slice(2)}`; + const argumentsList = [ + String(now), + member, + ...APP_LIMITS.flatMap((limit) => [ + String(limit.windowMs), + String(limit.max), + ]), + ]; + + const response = await client.sendCommand([ + 'EVAL', + ACQUIRE_SCRIPT, + String(keys.length), + ...keys, + ...argumentsList, + ]); + + const waitMs = Number(response ?? 0); + if (!Number.isFinite(waitMs) || waitMs < 0) return 0; + return waitMs; + } +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/apps/api/src/modules/riot/riot-recent-matches.service.ts b/apps/api/src/modules/riot/riot-recent-matches.service.ts new file mode 100644 index 00000000..964dd688 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-matches.service.ts @@ -0,0 +1,153 @@ +import { Injectable, Logger } from '@nestjs/common'; +import type { + RiotMatchDocument, + RiotMatch as StoredRiotMatch, +} from '../global/database/schema'; +import { ConnectionService } from '../global/database/connection.service'; +import { GarnetService } from '../global/garnet/garnet.service'; +import type { RiotRegionalRoute } from './riot.types'; +import { RiotMatchService } from './riot-match.service'; + +export const RIOT_RECENT_MATCH_LIMIT = 20; +export const RIOT_SOLO_QUEUE_ID = 420; + +const MATCH_ENRICHMENT_LOCK_TTL_SECONDS = 60; +const MATCH_DETAIL_CONCURRENCY = 2; +const DEFAULT_REGION: RiotRegionalRoute = 'asia'; + +@Injectable() +export class RiotRecentMatchesService { + private readonly logger = new Logger(RiotRecentMatchesService.name); + + constructor( + private readonly connectionService: ConnectionService, + private readonly matchService: RiotMatchService, + private readonly garnetService: GarnetService, + ) {} + + public async syncRecentMatches(params: { + puuid: string; + region?: RiotRegionalRoute; + limit?: number; + queueId?: number; + }): Promise { + const region = params.region ?? DEFAULT_REGION; + const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT; + const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID; + const lockKey = `riot:enrich:matches:${params.puuid}`; + const lockValue = `${process.pid}:${Date.now()}`; + + const acquired = await this.garnetService.setStringIfAbsent( + lockKey, + lockValue, + MATCH_ENRICHMENT_LOCK_TTL_SECONDS, + ); + if (!acquired) { + return this.loadFromDb({ puuid: params.puuid, limit, queueId }); + } + + try { + const matchIds = await this.matchService.getMatchIdsByPuuid(params.puuid, { + region, + queue: queueId, + count: limit, + }); + if (matchIds.length === 0) { + return this.loadFromDb({ puuid: params.puuid, limit, queueId }); + } + + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + const existingMatches = await RiotMatchModel.find({ + matchId: { $in: matchIds }, + }) + .select({ matchId: 1 }) + .lean() + .exec(); + const existingMatchIds = new Set(existingMatches.map((match) => match.matchId)); + const missingMatchIds = matchIds.filter((matchId) => !existingMatchIds.has(matchId)); + + await runWithConcurrency(missingMatchIds, MATCH_DETAIL_CONCURRENCY, async (matchId) => { + const dto = await this.matchService.getMatch(matchId, { region }); + if (dto.info.queueId !== queueId) { + this.logger.warn( + `Skipping unexpected queue ${dto.info.queueId} for ${matchId} while syncing ${params.puuid}.`, + ); + return; + } + + const payload: Partial = { + 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, + fetchedAt: new Date(), + }; + + await RiotMatchModel.updateOne( + { matchId: dto.metadata.matchId }, + { $setOnInsert: payload }, + { upsert: true }, + ).exec(); + }); + + return this.loadFromDb({ puuid: params.puuid, limit, queueId }); + } finally { + await this.garnetService.delete(lockKey).catch((error: unknown) => { + this.logger.warn( + `Failed to release recent matches lock for ${params.puuid}: ${ + (error as Error)?.message ?? error + }`, + ); + }); + } + } + + public async ensureFreshForQueue(params: { + puuid: string; + region?: RiotRegionalRoute; + queueId: number; + limit?: number; + }): Promise { + return this.syncRecentMatches(params); + } + + public async loadFromDb(params: { + puuid: string; + limit?: number; + queueId?: number; + }): Promise { + const limit = params.limit ?? RIOT_RECENT_MATCH_LIMIT; + const queueId = params.queueId ?? RIOT_SOLO_QUEUE_ID; + const RiotMatchModel = await this.connectionService.getModel('riotMatch'); + + return RiotMatchModel.find({ + participantPuuids: params.puuid, + queueId, + }) + .sort({ gameCreation: -1 }) + .limit(limit) + .exec(); + } +} + +async function runWithConcurrency( + items: T[], + concurrency: number, + worker: (item: T) => Promise, +): Promise { + if (items.length === 0) return; + + const queue = [...items]; + const runners = Array.from({ length: Math.min(concurrency, queue.length) }, async () => { + while (queue.length > 0) { + const item = queue.shift(); + if (item === undefined) return; + await worker(item); + } + }); + + await Promise.all(runners); +} diff --git a/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts b/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts new file mode 100644 index 00000000..326f1166 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-stats.service.spec.ts @@ -0,0 +1,304 @@ +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import type { RiotMatchDto } from './riot.types'; + +function makeMatch(params: { + matchId: string; + gameCreation: number; + gameDuration: number; + puuid: string; + championId: number; + kills: number; + deaths: number; + assists: number; + cs: number; + neutralCs?: number; + win?: boolean; + teamPosition?: string; + individualPosition?: string; +}): RiotMatchDto { + return { + metadata: { + dataVersion: '2', + matchId: params.matchId, + participants: [params.puuid, 'other-1'], + }, + info: { + gameCreation: params.gameCreation, + gameDuration: params.gameDuration, + gameId: 1, + gameMode: 'CLASSIC', + gameName: 'teambuilder-match-1', + gameStartTimestamp: params.gameCreation, + gameType: 'MATCHED_GAME', + gameVersion: '15.8.1', + mapId: 11, + platformId: 'KR', + queueId: 420, + participants: [ + { + assists: params.assists, + champExperience: 10000, + champLevel: 16, + championId: params.championId, + championName: `Champion-${params.championId}`, + deaths: params.deaths, + goldEarned: 12000, + goldSpent: 11000, + individualPosition: params.individualPosition ?? '', + item0: 0, + item1: 0, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 0, + kills: params.kills, + neutralMinionsKilled: params.neutralCs ?? 0, + participantId: 1, + perks: { + statPerks: { defense: 0, flex: 0, offense: 0 }, + styles: [], + }, + puuid: params.puuid, + riotIdGameName: 'tester', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 14, + summonerId: 'summoner-1', + summonerLevel: 100, + summonerName: 'tester', + teamId: 100, + teamPosition: params.teamPosition ?? '', + timePlayed: params.gameDuration, + totalDamageDealtToChampions: 10000, + totalDamageTaken: 5000, + totalMinionsKilled: params.cs, + visionScore: 20, + wardsKilled: 2, + wardsPlaced: 10, + win: params.win ?? true, + }, + { + assists: 1, + champExperience: 9000, + champLevel: 15, + championId: 1, + championName: 'Other', + deaths: 5, + goldEarned: 10000, + goldSpent: 9000, + individualPosition: 'TOP', + item0: 0, + item1: 0, + item2: 0, + item3: 0, + item4: 0, + item5: 0, + item6: 0, + kills: 3, + neutralMinionsKilled: 0, + participantId: 2, + perks: { + statPerks: { defense: 0, flex: 0, offense: 0 }, + styles: [], + }, + puuid: 'other-1', + riotIdGameName: 'other', + riotIdTagLine: 'KR1', + summoner1Id: 4, + summoner2Id: 14, + summonerId: 'summoner-2', + summonerLevel: 90, + summonerName: 'other', + teamId: 100, + teamPosition: 'TOP', + timePlayed: params.gameDuration, + totalDamageDealtToChampions: 8000, + totalDamageTaken: 7000, + totalMinionsKilled: 180, + visionScore: 10, + wardsKilled: 1, + wardsPlaced: 5, + win: false, + }, + ], + teams: [ + { + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: false, kills: 0 }, + dragon: { first: false, kills: 0 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: false, kills: 0 }, + }, + teamId: 100, + win: params.win ?? true, + }, + { + bans: [], + objectives: { + baron: { first: false, kills: 0 }, + champion: { first: false, kills: 0 }, + dragon: { first: false, kills: 0 }, + inhibitor: { first: false, kills: 0 }, + riftHerald: { first: false, kills: 0 }, + tower: { first: false, kills: 0 }, + }, + teamId: 200, + win: !(params.win ?? true), + }, + ], + }, + }; +} + +describe('RiotRecentStatsService', () => { + const service = new RiotRecentStatsService(); + + it('computes overall and lane summaries for recent solo queue matches', () => { + const matches = [ + makeMatch({ + matchId: 'KR_1', + gameCreation: 1_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 103, + kills: 8, + deaths: 2, + assists: 6, + cs: 180, + win: true, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_2', + gameCreation: 2_000, + gameDuration: 1500, + puuid: 'puuid-1', + championId: 103, + kills: 4, + deaths: 1, + assists: 8, + cs: 150, + neutralCs: 20, + win: false, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_3', + gameCreation: 3_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 22, + kills: 10, + deaths: 0, + assists: 5, + cs: 210, + win: true, + teamPosition: '', + individualPosition: 'BOTTOM', + }), + ]; + + const summary = service.computeSummary(matches, 'puuid-1'); + + expect(summary.overall).toEqual({ + games: 3, + wins: 2, + losses: 1, + avgKills: 7.3, + avgDeaths: 1, + avgAssists: 6.3, + avgCs: 186.7, + avgCsPerMin: 6.6, + mostPlayedChampionIds: [103, 22], + }); + expect(summary.byLane.MIDDLE).toEqual({ + games: 2, + wins: 1, + losses: 1, + avgKills: 6, + avgDeaths: 1.5, + avgAssists: 7, + avgCs: 175, + avgCsPerMin: 6.4, + mostPlayedChampionIds: [103], + }); + expect(summary.byLane.BOTTOM).toEqual({ + games: 1, + wins: 1, + losses: 0, + avgKills: 10, + avgDeaths: 0, + avgAssists: 5, + avgCs: 210, + avgCsPerMin: 7, + mostPlayedChampionIds: [22], + }); + }); + + it('skips invalid lane positions from byLane while keeping overall stats', () => { + const summary = service.computeSummary( + [ + makeMatch({ + matchId: 'KR_4', + gameCreation: 4_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 61, + kills: 6, + deaths: 3, + assists: 9, + cs: 190, + win: true, + teamPosition: 'Invalid', + individualPosition: '', + }), + ], + 'puuid-1', + ); + + expect(summary.overall.games).toBe(1); + expect(summary.byLane).toEqual({}); + }); + + it('filters out matches before seasonStartedAt', () => { + const summary = service.computeSummary( + [ + makeMatch({ + matchId: 'KR_5', + gameCreation: 1_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 61, + kills: 6, + deaths: 3, + assists: 9, + cs: 190, + win: true, + teamPosition: 'MIDDLE', + }), + makeMatch({ + matchId: 'KR_6', + gameCreation: 10_000, + gameDuration: 1800, + puuid: 'puuid-1', + championId: 134, + kills: 9, + deaths: 2, + assists: 7, + cs: 205, + win: true, + teamPosition: 'MIDDLE', + }), + ], + 'puuid-1', + { seasonStartedAt: new Date(5_000) }, + ); + + expect(summary.overall.games).toBe(1); + expect(summary.overall.mostPlayedChampionIds).toEqual([134]); + }); +}); diff --git a/apps/api/src/modules/riot/riot-recent-stats.service.ts b/apps/api/src/modules/riot/riot-recent-stats.service.ts new file mode 100644 index 00000000..62886925 --- /dev/null +++ b/apps/api/src/modules/riot/riot-recent-stats.service.ts @@ -0,0 +1,172 @@ +import { Injectable } from '@nestjs/common'; +import { + createEmptyRiotLaneStats, + createEmptyRiotRecentStatsSummary, + RIOT_LANES, + type RiotLane, + type RiotLaneStats, + type RiotRecentStatsSummary, +} from '../global/database/schema'; +import type { RiotMatchDto, RiotMatchParticipantDto } from './riot.types'; + +interface Aggregate { + games: number; + wins: number; + losses: number; + kills: number; + deaths: number; + assists: number; + cs: number; + csPerMin: number; + championCounts: Map; + lastPlayedAtByChampion: Map; +} + +interface ComputeSummaryOptions { + seasonStartedAt?: Date; +} + +@Injectable() +export class RiotRecentStatsService { + public computeSummary( + matches: RiotMatchDto[], + puuid: string, + options: ComputeSummaryOptions = {}, + ): RiotRecentStatsSummary { + const filteredMatches = this.filterMatchesBySeason(matches, options); + if (filteredMatches.length === 0) { + return createEmptyRiotRecentStatsSummary(); + } + + const overall = createAggregate(); + const laneAggregates = new Map( + RIOT_LANES.map((lane) => [lane, createAggregate()]), + ); + + for (const match of filteredMatches) { + const participant = match.info.participants.find((entry) => entry.puuid === puuid); + if (!participant) continue; + + accumulateAggregate(overall, participant, match.info.gameCreation, match.info.gameDuration); + + const lane = resolveLane(participant); + if (!lane) continue; + + const aggregate = laneAggregates.get(lane); + if (!aggregate) continue; + accumulateAggregate(aggregate, participant, match.info.gameCreation, match.info.gameDuration); + } + + if (overall.games === 0) { + return createEmptyRiotRecentStatsSummary(); + } + + const byLane: Partial> = {}; + for (const lane of RIOT_LANES) { + const aggregate = laneAggregates.get(lane); + if (!aggregate || aggregate.games === 0) continue; + byLane[lane] = finalizeAggregate(aggregate); + } + + return { + overall: finalizeAggregate(overall), + byLane, + }; + } + + private filterMatchesBySeason( + matches: RiotMatchDto[], + options: ComputeSummaryOptions, + ): RiotMatchDto[] { + const startedAt = options.seasonStartedAt?.getTime(); + if (!startedAt) return matches; + return matches.filter((match) => match.info.gameCreation >= startedAt); + } +} + +function createAggregate(): Aggregate { + return { + games: 0, + wins: 0, + losses: 0, + kills: 0, + deaths: 0, + assists: 0, + cs: 0, + csPerMin: 0, + championCounts: new Map(), + lastPlayedAtByChampion: new Map(), + }; +} + +function accumulateAggregate( + aggregate: Aggregate, + participant: RiotMatchParticipantDto, + gameCreation: number, + gameDurationSeconds: number, +): void { + aggregate.games += 1; + aggregate.wins += participant.win ? 1 : 0; + aggregate.losses += participant.win ? 0 : 1; + aggregate.kills += participant.kills; + aggregate.deaths += participant.deaths; + aggregate.assists += participant.assists; + + const cs = participant.totalMinionsKilled + participant.neutralMinionsKilled; + aggregate.cs += cs; + if (gameDurationSeconds > 0) { + aggregate.csPerMin += cs / (gameDurationSeconds / 60); + } + + aggregate.championCounts.set( + participant.championId, + (aggregate.championCounts.get(participant.championId) ?? 0) + 1, + ); + aggregate.lastPlayedAtByChampion.set(participant.championId, gameCreation); +} + +function finalizeAggregate(aggregate: Aggregate): RiotLaneStats { + if (aggregate.games === 0) { + return createEmptyRiotLaneStats(); + } + + const mostPlayedChampionIds = [...aggregate.championCounts.entries()] + .sort((left, right) => { + if (right[1] !== left[1]) return right[1] - left[1]; + const rightLastPlayed = aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0; + const leftLastPlayed = aggregate.lastPlayedAtByChampion.get(left[0]) ?? 0; + if (rightLastPlayed !== leftLastPlayed) { + return rightLastPlayed - leftLastPlayed; + } + return left[0] - right[0]; + }) + .slice(0, 3) + .map(([championId]) => championId); + + return { + games: aggregate.games, + wins: aggregate.wins, + losses: aggregate.losses, + avgKills: roundToOneDecimal(aggregate.kills / aggregate.games), + avgDeaths: roundToOneDecimal(aggregate.deaths / aggregate.games), + avgAssists: roundToOneDecimal(aggregate.assists / aggregate.games), + avgCs: roundToOneDecimal(aggregate.cs / aggregate.games), + avgCsPerMin: roundToOneDecimal(aggregate.csPerMin / aggregate.games), + mostPlayedChampionIds, + }; +} + +function resolveLane(participant: RiotMatchParticipantDto): RiotLane | null { + const candidates = [participant.teamPosition, participant.individualPosition]; + for (const candidate of candidates) { + if (!candidate) continue; + if (RIOT_LANES.includes(candidate as RiotLane)) { + return candidate as RiotLane; + } + } + return null; +} + +function roundToOneDecimal(value: number): number { + return Math.round(value * 10) / 10; +} diff --git a/apps/api/src/modules/riot/riot-summoner.service.ts b/apps/api/src/modules/riot/riot-summoner.service.ts new file mode 100644 index 00000000..30248294 --- /dev/null +++ b/apps/api/src/modules/riot/riot-summoner.service.ts @@ -0,0 +1,60 @@ +import { Injectable } from '@nestjs/common'; +import { RiotClientService } from './riot.client.service'; +import { + RiotPlatformLookupOptions, + RiotSummonerDto, +} from './riot.types'; + +@Injectable() +export class RiotSummonerService { + constructor(private readonly riotClientService: RiotClientService) {} + + public async getByPuuid( + puuid: string, + options: RiotPlatformLookupOptions = {}, + ): Promise { + return this.riotClientService.get( + `/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`, + { + platform: options.platform ?? 'kr', + signal: options.signal, + }, + parseSummoner, + ); + } +} + +function parseSummoner(value: unknown): RiotSummonerDto { + if (!isRecord(value)) { + throw new TypeError('Riot summoner response must be an object.'); + } + const puuid = value.puuid; + const profileIconId = value.profileIconId; + const revisionDate = value.revisionDate; + const summonerLevel = value.summonerLevel; + if (typeof puuid !== 'string' || puuid.length === 0) { + throw new TypeError('Summoner.puuid must be a non-empty string.'); + } + if (typeof profileIconId !== 'number') { + throw new TypeError('Summoner.profileIconId must be a number.'); + } + if (typeof revisionDate !== 'number') { + throw new TypeError('Summoner.revisionDate must be a number.'); + } + if (typeof summonerLevel !== 'number') { + throw new TypeError('Summoner.summonerLevel must be a number.'); + } + return { + puuid, + profileIconId, + revisionDate, + summonerLevel, + id: typeof value.id === 'string' ? value.id : undefined, + accountId: + typeof value.accountId === 'string' ? value.accountId : undefined, + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null; +} diff --git a/apps/api/src/modules/riot/riot-webhook.controller.spec.ts b/apps/api/src/modules/riot/riot-webhook.controller.spec.ts new file mode 100644 index 00000000..78bbd913 --- /dev/null +++ b/apps/api/src/modules/riot/riot-webhook.controller.spec.ts @@ -0,0 +1,60 @@ +import type { Request } from 'express'; +import { RiotWebhookController } from './riot-webhook.controller'; + +type RiotWebhookRequest = Request & { + rawBody?: Buffer; +}; + +describe('RiotWebhookController', () => { + let controller: RiotWebhookController; + + beforeEach(() => { + controller = new RiotWebhookController(); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + it('logs the incoming webhook payload and returns an acknowledgement', () => { + const logSpy = jest.spyOn(console, 'log').mockImplementation(() => undefined); + const dirSpy = jest.spyOn(console, 'dir').mockImplementation(() => undefined); + const request = { + method: 'POST', + originalUrl: '/riot/webhooks/tournament', + protocol: 'https', + hostname: 'example.test', + ip: '127.0.0.1', + ips: ['127.0.0.1'], + headers: { + 'content-type': 'application/json', + }, + query: { + shard: 'kr', + }, + params: {}, + body: { + eventType: 'MATCH_FINISHED', + }, + rawBody: Buffer.from('{"eventType":"MATCH_FINISHED"}', 'utf8'), + } as unknown as RiotWebhookRequest; + + const response = controller.captureTournamentWebhook(request); + + expect(response.ok).toBe(true); + expect(response.message).toBe('Riot webhook received.'); + expect(response.receivedAt).toEqual(expect.any(String)); + expect(logSpy).toHaveBeenCalledTimes(2); + expect(dirSpy).toHaveBeenCalledWith( + expect.objectContaining({ + method: 'POST', + url: '/riot/webhooks/tournament', + body: { + eventType: 'MATCH_FINISHED', + }, + rawBodyText: '{"eventType":"MATCH_FINISHED"}', + }), + { depth: null }, + ); + }); +}); diff --git a/apps/api/src/modules/riot/riot-webhook.controller.ts b/apps/api/src/modules/riot/riot-webhook.controller.ts new file mode 100644 index 00000000..689b2b2e --- /dev/null +++ b/apps/api/src/modules/riot/riot-webhook.controller.ts @@ -0,0 +1,49 @@ +import { + All, + Controller, + HttpCode, + HttpStatus, + Req, +} from '@nestjs/common'; +import type { Request } from 'express'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; + +type RiotWebhookRequest = Request & { + rawBody?: Buffer; +}; + +@Controller('riot') +export class RiotWebhookController { + @All('webhooks/tournament') + @AllowPublicAccess() + @HttpCode(HttpStatus.OK) + public captureTournamentWebhook(@Req() req: RiotWebhookRequest) { + const receivedAt = new Date().toISOString(); + const rawBodyText = req.rawBody?.toString('utf8') ?? null; + const logPayload = { + receivedAt, + method: req.method, + url: req.originalUrl, + protocol: req.protocol, + hostname: req.hostname, + ip: req.ip, + ips: req.ips, + headers: req.headers, + query: req.query, + params: req.params, + body: req.body, + rawBodyLength: req.rawBody?.length ?? null, + rawBodyText, + }; + + console.log('\n[RIOT TOURNAMENT WEBHOOK] Incoming request'); + console.dir(logPayload, { depth: null }); + console.log('[RIOT TOURNAMENT WEBHOOK] End request log\n'); + + return { + ok: true, + message: 'Riot webhook received.', + receivedAt, + }; + } +} diff --git a/apps/api/src/modules/riot/riot.client.service.ts b/apps/api/src/modules/riot/riot.client.service.ts new file mode 100644 index 00000000..9c8e3225 --- /dev/null +++ b/apps/api/src/modules/riot/riot.client.service.ts @@ -0,0 +1,177 @@ +import { Injectable, Logger } from '@nestjs/common'; +import { SecretService } from '../global/secret/secret.service'; +import { + RiotApiErrorBody, + RiotPlatformRoute, + RiotRegionalRoute, + RiotRequestOptions, + RiotResponseParser, +} from './riot.types'; +import { RiotRateLimiterService } from './riot-rate-limiter.service'; + +const RIOT_REGION_BASE_URLS: Record = { + americas: 'https://americas.api.riotgames.com', + asia: 'https://asia.api.riotgames.com', + europe: 'https://europe.api.riotgames.com', + sea: 'https://sea.api.riotgames.com', +}; + +const RIOT_PLATFORM_BASE_URLS: Record = { + br1: 'https://br1.api.riotgames.com', + eun1: 'https://eun1.api.riotgames.com', + euw1: 'https://euw1.api.riotgames.com', + jp1: 'https://jp1.api.riotgames.com', + kr: 'https://kr.api.riotgames.com', + la1: 'https://la1.api.riotgames.com', + la2: 'https://la2.api.riotgames.com', + me1: 'https://me1.api.riotgames.com', + na1: 'https://na1.api.riotgames.com', + oc1: 'https://oc1.api.riotgames.com', + ph2: 'https://ph2.api.riotgames.com', + ru: 'https://ru.api.riotgames.com', + sg2: 'https://sg2.api.riotgames.com', + th2: 'https://th2.api.riotgames.com', + tr1: 'https://tr1.api.riotgames.com', + tw2: 'https://tw2.api.riotgames.com', + vn2: 'https://vn2.api.riotgames.com', +}; + +export class RiotApiError extends Error { + constructor( + message: string, + public readonly status: number, + public readonly url: string, + public readonly body?: RiotApiErrorBody, + public readonly retryAfterSeconds?: number, + ) { + super(message); + } +} + +@Injectable() +export class RiotClientService { + private readonly logger = new Logger(RiotClientService.name); + + constructor( + private readonly secretService: SecretService, + private readonly rateLimiter: RiotRateLimiterService, + ) {} + + public async get( + path: string, + options: RiotRequestOptions = {}, + parser?: RiotResponseParser, + ): Promise { + const apiKey = await this.secretService.get('RIOT_API_KEY'); + const url = this.buildUrl(path, options); + const routeKey = options.platform ?? options.region ?? 'asia'; + + return this.fetchWithRetry(url, apiKey, options.signal, parser, routeKey); + } + + private buildUrl(path: string, options: RiotRequestOptions): string { + const baseUrl = options.platform + ? RIOT_PLATFORM_BASE_URLS[options.platform] + : RIOT_REGION_BASE_URLS[options.region ?? 'asia']; + const normalizedPath = path.startsWith('/') ? path : `/${path}`; + const url = new URL(`${baseUrl}${normalizedPath}`); + + if (options.query) { + for (const [key, value] of Object.entries(options.query)) { + if (value === undefined) { + continue; + } + + url.searchParams.set(key, String(value)); + } + } + + return url.toString(); + } + + private async createApiError( + response: Response, + url: string, + ): Promise { + let body: RiotApiErrorBody | undefined; + + try { + body = (await response.json()) as RiotApiErrorBody; + } catch { + body = undefined; + } + + const message = + body?.status?.message ?? + `Riot API request failed with status ${response.status}`; + const retryAfterHeader = response.headers.get('Retry-After'); + const retryAfterSeconds = retryAfterHeader + ? Number(retryAfterHeader) + : undefined; + + this.logger.warn(`${message} (${response.status}) ${url}`); + + return new RiotApiError( + message, + response.status, + url, + body, + Number.isFinite(retryAfterSeconds) ? retryAfterSeconds : undefined, + ); + } + + private async fetchWithRetry( + url: string, + apiKey: string, + signal: AbortSignal | undefined, + parser: RiotResponseParser | undefined, + routeKey: RiotRegionalRoute | RiotPlatformRoute, + attempt = 0, + ): Promise { + await this.rateLimiter.acquire(routeKey); + + const response = await fetch(url, { + method: 'GET', + headers: { + Accept: 'application/json', + 'X-Riot-Token': apiKey, + }, + signal, + }); + + const appRateLimitCount = response.headers.get('X-App-Rate-Limit-Count'); + if (appRateLimitCount && Math.random() < 0.05) { + this.logger.debug(`Riot rate usage ${routeKey}: ${appRateLimitCount}`); + } + + if (!response.ok) { + const error = await this.createApiError(response, url); + if ( + error.status === 429 && + attempt === 0 + ) { + await sleep((error.retryAfterSeconds ?? 1) * 1000); + return this.fetchWithRetry( + url, + apiKey, + signal, + parser, + routeKey, + attempt + 1, + ); + } + throw error; + } + + if (response.status === 204) { + return undefined as T; + } + + const payload = (await response.json()) as unknown; + return parser ? parser(payload) : (payload as T); + } +} + +function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} diff --git a/apps/api/src/modules/riot/riot.module.ts b/apps/api/src/modules/riot/riot.module.ts new file mode 100644 index 00000000..0989de8d --- /dev/null +++ b/apps/api/src/modules/riot/riot.module.ts @@ -0,0 +1,47 @@ +import { Module } from '@nestjs/common'; +import { SecretModule } from '../global/secret/secret.module'; +import { RiotAccountEnrichmentService } from './riot-account-enrichment.service'; +import { RiotAccountService } from './riot-account.service'; +import { RiotChampionMasteryService } from './riot-champion-mastery.service'; +import { RiotClientService } from './riot.client.service'; +import { RiotDdragonController } from './riot-ddragon.controller'; +import { RiotDdragonService } from './riot-ddragon.service'; +import { RiotLeagueService } from './riot-league.service'; +import { RiotMatchService } from './riot-match.service'; +import { RiotRateLimiterService } from './riot-rate-limiter.service'; +import { RiotRecentMatchesService } from './riot-recent-matches.service'; +import { RiotRecentStatsService } from './riot-recent-stats.service'; +import { RiotSummonerService } from './riot-summoner.service'; +import { RiotWebhookController } from './riot-webhook.controller'; + +@Module({ + imports: [SecretModule], + controllers: [RiotWebhookController, RiotDdragonController], + providers: [ + RiotRateLimiterService, + RiotClientService, + RiotAccountService, + RiotMatchService, + RiotRecentMatchesService, + RiotRecentStatsService, + RiotSummonerService, + RiotLeagueService, + RiotChampionMasteryService, + RiotAccountEnrichmentService, + RiotDdragonService, + ], + exports: [ + RiotRateLimiterService, + RiotClientService, + RiotAccountService, + RiotMatchService, + RiotRecentMatchesService, + RiotRecentStatsService, + RiotSummonerService, + RiotLeagueService, + RiotChampionMasteryService, + RiotAccountEnrichmentService, + RiotDdragonService, + ], +}) +export class RiotModule {} diff --git a/apps/api/src/modules/riot/riot.types.ts b/apps/api/src/modules/riot/riot.types.ts new file mode 100644 index 00000000..dd7df8d1 --- /dev/null +++ b/apps/api/src/modules/riot/riot.types.ts @@ -0,0 +1,251 @@ +export const RIOT_REGIONAL_ROUTES = [ + 'americas', + 'asia', + 'europe', + 'sea', +] as const; +export type RiotRegionalRoute = (typeof RIOT_REGIONAL_ROUTES)[number]; + +export const RIOT_PLATFORM_ROUTES = [ + 'br1', + 'eun1', + 'euw1', + 'jp1', + 'kr', + 'la1', + 'la2', + 'me1', + 'na1', + 'oc1', + 'ph2', + 'ru', + 'sg2', + 'th2', + 'tr1', + 'tw2', + 'vn2', +] as const; +export type RiotPlatformRoute = (typeof RIOT_PLATFORM_ROUTES)[number]; +export type RiotMatchType = 'ranked' | 'normal' | 'tourney' | 'tutorial'; + +export interface RiotAccountRegionDto { + puuid: string; + game: string; + region: RiotPlatformRoute; +} + +export interface RiotAccountApiResponse { + puuid: string; + gameName?: string; + tagLine?: string; +} + +export interface RiotAccountDto { + puuid: string; + gameName: string | null; + tagLine: string | null; +} + +export interface RiotRequestOptions { + region?: RiotRegionalRoute; + platform?: RiotPlatformRoute; + query?: Record; + signal?: AbortSignal; +} + +export type RiotResponseParser = (value: unknown) => T; + +export interface RiotApiErrorBody { + status?: { + message?: string; + status_code?: number; + }; +} + +export interface RiotAccountLookupOptions { + region?: RiotRegionalRoute; + signal?: AbortSignal; +} + +export interface RiotMatchLookupOptions { + region?: RiotRegionalRoute; + signal?: AbortSignal; +} + +export interface RiotPlatformLookupOptions { + platform?: RiotPlatformRoute; + signal?: AbortSignal; +} + +// Summoner-V4 by-puuid 응답 (간소화 — 실제 응답에 id 가 빠질 수 있어 optional 처리) +export interface RiotSummonerDto { + puuid: string; + profileIconId: number; + revisionDate: number; + summonerLevel: number; + id?: string; + accountId?: string; +} + +// League-V4 entries by-puuid 응답 +export interface RiotLeagueEntryDto { + leagueId: string; + queueType: string; + tier: string; + rank: string; + puuid: string; + leaguePoints: number; + wins: number; + losses: number; + veteran?: boolean; + inactive?: boolean; + freshBlood?: boolean; + hotStreak?: boolean; + miniSeries?: Record; +} + +// Champion-Mastery-V4 by-puuid 응답 +export interface RiotChampionMasteryDto extends Record { + 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 RiotMatchIdsLookupOptions extends RiotMatchLookupOptions { + start?: number; + count?: number; + queue?: number; + type?: RiotMatchType; + startTime?: number; + endTime?: number; +} + +export interface RiotMatchDto { + metadata: RiotMatchMetadataDto; + info: RiotMatchInfoDto; +} + +export interface RiotMatchMetadataDto { + dataVersion: string; + matchId: string; + participants: string[]; +} + +export interface RiotMatchInfoDto extends Record { + endOfGameResult?: string; + gameCreation: number; + gameDuration: number; + gameEndTimestamp?: number; + gameId: number; + gameMode: string; + gameName: string; + gameStartTimestamp: number; + gameType: string; + gameVersion: string; + mapId: number; + participants: RiotMatchParticipantDto[]; + platformId: string; + queueId: number; + teams: RiotMatchTeamDto[]; + tournamentCode?: string; +} + +export interface RiotMatchParticipantDto extends Record { + assists: number; + champExperience: number; + champLevel: number; + championId: number; + championName: string; + deaths: number; + goldEarned: number; + goldSpent: number; + individualPosition: string; + item0: number; + item1: number; + item2: number; + item3: number; + item4: number; + item5: number; + item6: number; + kills: number; + neutralMinionsKilled: number; + participantId: number; + perks: RiotMatchPerksDto; + puuid: string; + riotIdGameName?: string; + riotIdTagLine?: string; + summoner1Id: number; + summoner2Id: number; + summonerId: string; + summonerLevel: number; + summonerName: string; + teamId: number; + teamPosition: string; + timePlayed: number; + totalDamageDealtToChampions: number; + totalDamageTaken: number; + totalMinionsKilled: number; + visionScore: number; + wardsKilled: number; + wardsPlaced: number; + win: boolean; +} + +export interface RiotMatchPerksDto { + statPerks: RiotMatchStatPerksDto; + styles: RiotMatchPerkStyleDto[]; +} + +export interface RiotMatchStatPerksDto { + defense: number; + flex: number; + offense: number; +} + +export interface RiotMatchPerkStyleDto { + description: string; + selections: RiotMatchPerkStyleSelectionDto[]; + style: number; +} + +export interface RiotMatchPerkStyleSelectionDto { + perk: number; + var1: number; + var2: number; + var3: number; +} + +export interface RiotMatchTeamDto extends Record { + bans: RiotMatchBanDto[]; + objectives: RiotMatchObjectivesDto; + teamId: number; + win: boolean; +} + +export interface RiotMatchBanDto { + championId: number; + pickTurn: number; +} + +export interface RiotMatchObjectivesDto { + baron: RiotMatchObjectiveDto; + champion: RiotMatchObjectiveDto; + dragon: RiotMatchObjectiveDto; + inhibitor: RiotMatchObjectiveDto; + riftHerald: RiotMatchObjectiveDto; + tower: RiotMatchObjectiveDto; +} + +export interface RiotMatchObjectiveDto { + first: boolean; + kills: number; +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.constants.ts b/apps/api/src/modules/tournament-code/tournament-code.constants.ts new file mode 100644 index 00000000..ee4da598 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.constants.ts @@ -0,0 +1,4 @@ +export const TOURNAMENT_CODE_PATTERN = /^[A-Z0-9-]{8,}$/i; +export const TOURNAMENT_CODE_EXPIRY_MARGIN_MS = 24 * 60 * 60 * 1000; +export const TOURNAMENT_CODE_EXPIRING_SOON_MS = 7 * 24 * 60 * 60 * 1000; +export const DEFAULT_TOURNAMENT_GAME_COUNT = 3; diff --git a/apps/api/src/modules/tournament-code/tournament-code.controller.ts b/apps/api/src/modules/tournament-code/tournament-code.controller.ts new file mode 100644 index 00000000..cd28cd47 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.controller.ts @@ -0,0 +1,105 @@ +import { + BadRequestException, + Body, + Controller, + Delete, + Get, + HttpCode, + HttpStatus, + 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 { + TournamentCodeState, + UserDocument, +} from '../global/database/schema'; +import { TournamentCodeService } from './tournament-code.service'; +import type { BulkUploadTournamentCodesRequest } from './tournament-code.types'; + +@Controller('communities/:communityId/tournament-codes') +@Roles('owner', 'admin') +@UseGuards(RolesGuard) +export class TournamentCodeController { + constructor(private readonly tournamentCodeService: TournamentCodeService) {} + + @Post() + public async bulkUpload( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Body() body: BulkUploadTournamentCodesRequest, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.bulkUpload({ + communityId, + uploadedBy: currentUser._id, + codes: body.codes ?? [], + }); + } + + @Get() + public async list( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Query('state') state?: TournamentCodeState, + @Query('limit') limit?: string, + ) { + this.assertSameCommunity(currentUser, communityId); + return { + codes: await this.tournamentCodeService.list({ + state, + limit: limit ? Number(limit) : undefined, + }), + }; + } + + @Get('stats') + public async stats( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.stats(); + } + + @Post(':id/release') + public async restore( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('id', ParseObjectIdPipe) id: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + return this.tournamentCodeService.restoreToAvailable(id); + } + + @Delete(':id') + @HttpCode(HttpStatus.NO_CONTENT) + public async discard( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('id', ParseObjectIdPipe) id: mongoose.Types.ObjectId, + ) { + this.assertSameCommunity(currentUser, communityId); + await this.tournamentCodeService.discardAvailable(id); + } + + private assertSameCommunity( + user: UserDocument, + communityId: mongoose.Types.ObjectId, + ): void { + if (!user.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.module.ts b/apps/api/src/modules/tournament-code/tournament-code.module.ts new file mode 100644 index 00000000..f41cc726 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.module.ts @@ -0,0 +1,11 @@ +import { Module } from '@nestjs/common'; +import { TournamentCodeController } from './tournament-code.controller'; +import { TournamentCodeScheduler } from './tournament-code.scheduler'; +import { TournamentCodeService } from './tournament-code.service'; + +@Module({ + controllers: [TournamentCodeController], + providers: [TournamentCodeService, TournamentCodeScheduler], + exports: [TournamentCodeService], +}) +export class TournamentCodeModule {} diff --git a/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts new file mode 100644 index 00000000..9f73d297 --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.scheduler.ts @@ -0,0 +1,57 @@ +import { Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; +import { TournamentCodeService } from './tournament-code.service'; + +@Injectable() +export class TournamentCodeScheduler implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(TournamentCodeScheduler.name); + private attachTimer?: NodeJS.Timeout; + private expireTimer?: NodeJS.Timeout; + + constructor(private readonly tournamentCodeService: TournamentCodeService) {} + + public onModuleInit() { + this.attachTimer = setInterval(() => { + void this.attachPending(); + }, 30_000); + this.expireTimer = setInterval(() => { + void this.markExpired(); + }, 60 * 60 * 1000); + this.attachTimer.unref?.(); + this.expireTimer.unref?.(); + + void this.attachPending(); + void this.markExpired(); + } + + public onModuleDestroy() { + if (this.attachTimer) clearInterval(this.attachTimer); + if (this.expireTimer) clearInterval(this.expireTimer); + } + + private async attachPending() { + try { + const touched = await this.tournamentCodeService.attachPendingMatches(); + if (touched > 0) { + this.logger.debug(`Attached tournament codes for ${touched} matches.`); + } + } catch (error) { + this.logger.warn( + `Failed to attach pending tournament codes: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } + + private async markExpired() { + try { + await this.tournamentCodeService.markExpired(); + } catch (error) { + this.logger.warn( + `Failed to mark expired tournament codes: ${ + error instanceof Error ? error.message : error + }`, + ); + } + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.service.ts b/apps/api/src/modules/tournament-code/tournament-code.service.ts new file mode 100644 index 00000000..c5305abc --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.service.ts @@ -0,0 +1,365 @@ +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + MatchDocument, + TournamentCode, + TournamentCodeDocument, + TournamentCodeState, + TournamentSpectatorType, +} from '../global/database/schema'; +import { + DEFAULT_TOURNAMENT_GAME_COUNT, + TOURNAMENT_CODE_EXPIRING_SOON_MS, + TOURNAMENT_CODE_EXPIRY_MARGIN_MS, + TOURNAMENT_CODE_PATTERN, +} from './tournament-code.constants'; +import type { + BulkUploadTournamentCodesResponse, + TournamentCodeSlotView, + TournamentCodeUploadItem, +} from './tournament-code.types'; + +const DEFAULT_REGION = 'kr'; +const DEFAULT_SPECTATOR_TYPE: TournamentSpectatorType = 'ALL'; + +@Injectable() +export class TournamentCodeService { + constructor(private readonly connectionService: ConnectionService) {} + + public async bulkUpload(params: { + communityId: mongoose.Types.ObjectId; + uploadedBy: mongoose.Types.ObjectId; + codes: TournamentCodeUploadItem[]; + }): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const invalid: BulkUploadTournamentCodesResponse['invalid'] = []; + const duplicates: string[] = []; + const valid: Array< + Omit & { + uploadedBy: mongoose.Types.ObjectId; + } + > = []; + const seen = new Set(); + + for (const item of params.codes) { + const code = this.normalizeCode(item.code); + if (!code) { + invalid.push({ code: item.code ?? '', reason: 'empty-code' }); + continue; + } + if (!TOURNAMENT_CODE_PATTERN.test(code)) { + invalid.push({ code, reason: 'invalid-format' }); + continue; + } + if (seen.has(code)) { + duplicates.push(code); + continue; + } + seen.add(code); + + const expiresAt = new Date(item.expiresAt); + if (Number.isNaN(expiresAt.getTime())) { + invalid.push({ code, reason: 'invalid-expiresAt' }); + continue; + } + if (expiresAt <= new Date()) { + invalid.push({ code, reason: 'expired-expiresAt' }); + continue; + } + + valid.push({ + code, + region: DEFAULT_REGION, + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + spectatorType: item.spectatorType ?? DEFAULT_SPECTATOR_TYPE, + metadata: item.metadata, + expiresAt, + state: 'available', + uploadedBy: params.uploadedBy, + uploadedAt: new Date(), + source: item.source, + notes: item.notes, + }); + } + + if (valid.length === 0) { + return { inserted: 0, duplicates, invalid }; + } + + const existing = await TournamentCodeModel.find({ + code: { $in: valid.map((item) => item.code) }, + }) + .select({ code: 1 }) + .lean() + .exec(); + const existingCodes = new Set(existing.map((item) => item.code)); + duplicates.push(...existing.map((item) => item.code)); + + const insertable = valid.filter((item) => !existingCodes.has(item.code)); + if (insertable.length > 0) { + await TournamentCodeModel.insertMany(insertable, { ordered: false }); + } + + await this.attachPendingMatches(params.communityId); + + return { + inserted: insertable.length, + duplicates: [...new Set(duplicates)], + invalid, + }; + } + + public async list(params: { + state?: TournamentCodeState; + limit?: number; + }): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const filter: { state?: TournamentCodeState } = {}; + if (params.state) filter.state = params.state; + return TournamentCodeModel.find(filter) + .sort({ expiresAt: 1, uploadedAt: -1 }) + .limit(Math.min(params.limit ?? 100, 300)) + .exec(); + } + + public async stats(): Promise<{ + byState: Record; + expiringSoon: number; + available: number; + }> { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const states: TournamentCodeState[] = [ + 'available', + 'reserved', + 'used', + 'expired', + 'released', + ]; + const counts = await TournamentCodeModel.aggregate<{ + _id: TournamentCodeState; + count: number; + }>([{ $group: { _id: '$state', count: { $sum: 1 } } }]).exec(); + const byState = Object.fromEntries(states.map((state) => [state, 0])) as Record< + TournamentCodeState, + number + >; + for (const entry of counts) byState[entry._id] = entry.count; + + const expiringSoon = await TournamentCodeModel.countDocuments({ + state: 'available', + expiresAt: { + $gt: new Date(), + $lte: new Date(Date.now() + TOURNAMENT_CODE_EXPIRING_SOON_MS), + }, + }); + + return { byState, expiringSoon, available: byState.available }; + } + + public async discardAvailable(id: mongoose.Types.ObjectId): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const result = await TournamentCodeModel.deleteOne({ + _id: id, + state: 'available', + }).exec(); + if (result.deletedCount === 0) { + throw new BadRequestException('Only available tournament codes can be deleted.'); + } + } + + public async restoreToAvailable( + id: mongoose.Types.ObjectId, + ): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const MatchModel = await this.connectionService.getModel('match'); + const code = await TournamentCodeModel.findById(id); + if (!code) throw new NotFoundException('Tournament code not found.'); + if (code.state !== 'released' && code.state !== 'reserved') { + throw new BadRequestException( + 'Only released or reserved tournament codes can be restored.', + ); + } + const previousMatchId = code.matchId; + code.state = 'available'; + code.matchId = undefined; + code.gameNumber = undefined; + code.reservedAt = undefined; + code.releasedAt = undefined; + await code.save(); + if (previousMatchId) { + await MatchModel.updateOne( + { _id: previousMatchId }, + { $pull: { tournamentCodeIds: code._id } }, + ).exec(); + await this.attachPendingMatches(); + } + return code; + } + + public async reserveForMatch( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const match = + matchOrId instanceof mongoose.Types.ObjectId + ? await MatchModel.findById(matchOrId) + : await MatchModel.findById(matchOrId._id); + if (!match) throw new NotFoundException('Match not found.'); + + match.gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + const need = match.gameCount - match.tournamentCodeIds.length; + if (need <= 0) return match; + + const reservedIds: mongoose.Types.ObjectId[] = []; + const startGameNumber = match.tournamentCodeIds.length + 1; + const expiresAfter = new Date(Date.now() + TOURNAMENT_CODE_EXPIRY_MARGIN_MS); + + for (let index = 0; index < need; index += 1) { + const code = await TournamentCodeModel.findOneAndUpdate( + { + state: 'available', + region: DEFAULT_REGION, + mapType: 'SUMMONERS_RIFT', + teamSize: 5, + expiresAt: { $gt: expiresAfter }, + }, + { + $set: { + state: 'reserved', + matchId: match._id, + gameNumber: startGameNumber + index, + reservedAt: new Date(), + }, + $unset: { releasedAt: 1 }, + }, + { sort: { expiresAt: 1 }, returnDocument: 'after' }, + ).exec(); + if (!code) break; + reservedIds.push(code._id); + } + + if (reservedIds.length > 0) { + match.tournamentCodeIds.push(...reservedIds); + await match.save(); + } + return match; + } + + public async releaseFromMatch( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const match = + matchOrId instanceof mongoose.Types.ObjectId + ? await MatchModel.findById(matchOrId) + : await MatchModel.findById(matchOrId._id); + if (!match) return; + if (match.tournamentCodeIds.length === 0) return; + + await TournamentCodeModel.updateMany( + { _id: { $in: match.tournamentCodeIds }, state: 'reserved' }, + { + $set: { state: 'released', releasedAt: new Date() }, + $unset: { matchId: 1, gameNumber: 1, reservedAt: 1 }, + }, + ).exec(); + + match.tournamentCodeIds = []; + await match.save(); + } + + public async markExpired(): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const result = await TournamentCodeModel.updateMany( + { + state: { $in: ['available', 'reserved', 'released'] }, + expiresAt: { $lte: new Date() }, + }, + { $set: { state: 'expired' } }, + ).exec(); + return result.modifiedCount; + } + + public async attachPendingMatches( + communityId?: mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const filter: { + status: { $in: string[] }; + communityId?: mongoose.Types.ObjectId; + } = { + status: { $in: ['team-built', 'in-progress'] }, + }; + if (communityId) filter.communityId = communityId; + + const matches = await MatchModel.find(filter).exec(); + let touched = 0; + for (const match of matches) { + if ((match.tournamentCodeIds?.length ?? 0) >= (match.gameCount || 0)) { + continue; + } + const before = match.tournamentCodeIds?.length ?? 0; + await this.reserveForMatch(match); + const after = match.tournamentCodeIds?.length ?? 0; + if (after > before) touched += 1; + } + return touched; + } + + public async buildSlots(match: MatchDocument): Promise { + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const gameCount = match.gameCount || DEFAULT_TOURNAMENT_GAME_COUNT; + const ids = match.tournamentCodeIds ?? []; + const codes = + ids.length > 0 + ? await TournamentCodeModel.find({ _id: { $in: ids } }).exec() + : []; + const byGameNumber = new Map( + codes + .filter((code) => typeof code.gameNumber === 'number') + .map((code) => [code.gameNumber as number, code]), + ); + + return Array.from({ length: gameCount }, (_, index) => { + const gameNumber = index + 1; + const code = byGameNumber.get(gameNumber); + if (!code) { + return { + gameNumber, + code: null, + expiresAt: null, + state: 'pending', + riotMatchId: null, + }; + } + return { + gameNumber, + code: code.code, + expiresAt: code.expiresAt.toISOString(), + state: code.state, + riotMatchId: code.riotMatchId ?? null, + }; + }); + } + + private normalizeCode(code: string | undefined): string { + return (code ?? '').trim().toUpperCase(); + } +} diff --git a/apps/api/src/modules/tournament-code/tournament-code.types.ts b/apps/api/src/modules/tournament-code/tournament-code.types.ts new file mode 100644 index 00000000..c841da3f --- /dev/null +++ b/apps/api/src/modules/tournament-code/tournament-code.types.ts @@ -0,0 +1,31 @@ +import type { + TournamentCodeState, + TournamentSpectatorType, +} from '../global/database/schema'; + +export interface TournamentCodeUploadItem { + code: string; + expiresAt: string; + spectatorType?: TournamentSpectatorType; + metadata?: Record; + source?: string; + notes?: string; +} + +export interface BulkUploadTournamentCodesRequest { + codes: TournamentCodeUploadItem[]; +} + +export interface BulkUploadTournamentCodesResponse { + inserted: number; + duplicates: string[]; + invalid: Array<{ code: string; reason: string }>; +} + +export interface TournamentCodeSlotView { + gameNumber: number; + code: string | null; + expiresAt: string | null; + state: TournamentCodeState | 'pending'; + riotMatchId: string | null; +} diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts new file mode 100644 index 00000000..a0e72be8 --- /dev/null +++ b/apps/api/src/modules/tournament-result/team-mapping.util.spec.ts @@ -0,0 +1,144 @@ +import mongoose from 'mongoose'; +import type { MatchDocument } from '../global/database/schema'; +import type { RiotMatchDto } from '../riot/riot.types'; +import { computeGameResult, type MatchPuuidLookup } from './team-mapping.util'; + +function makeMatch(): { + match: MatchDocument; + lookup: MatchPuuidLookup; + blueUserIds: mongoose.Types.ObjectId[]; + redUserIds: mongoose.Types.ObjectId[]; +} { + const blueUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); + const redUserIds = Array.from({ length: 5 }, () => new mongoose.Types.ObjectId()); + const puuidByUserId = new Map(); + const userIdByPuuid = new Map(); + + for (const [index, userId] of [...blueUserIds, ...redUserIds].entries()) { + const puuid = `puuid-${index}`; + puuidByUserId.set(userId.toString(), puuid); + userIdByPuuid.set(puuid, userId); + } + + const match = { + teams: [ + { + side: 'blue', + name: '블루팀', + members: blueUserIds.map((userId) => ({ + userId, + assignedPosition: 'MID', + })), + }, + { + side: 'red', + name: '레드팀', + members: redUserIds.map((userId) => ({ + userId, + assignedPosition: 'MID', + })), + }, + ], + participants: [...blueUserIds, ...redUserIds].map((userId, index) => ({ + userId, + puuid: `puuid-${index}`, + preferredPositions: [], + joinedAt: new Date(), + })), + } as unknown as MatchDocument; + + return { match, lookup: { puuidByUserId, userIdByPuuid }, blueUserIds, redUserIds }; +} + +function makeRiotMatch(params: { + team100Puuids: string[]; + team200Puuids: string[]; + winningTeamId: 100 | 200; +}): RiotMatchDto { + const participants = [ + ...params.team100Puuids.map((puuid, index) => ({ + puuid, + participantId: index + 1, + teamId: 100, + championId: 10 + index, + kills: index, + deaths: 1, + assists: 2, + win: params.winningTeamId === 100, + })), + ...params.team200Puuids.map((puuid, index) => ({ + puuid, + participantId: index + 6, + teamId: 200, + championId: 20 + index, + kills: index, + deaths: 2, + assists: 3, + win: params.winningTeamId === 200, + })), + ]; + + return { + metadata: { + dataVersion: '2', + matchId: 'KR_1', + participants: participants.map((participant) => participant.puuid), + }, + info: { + gameCreation: 1, + gameDuration: 1800, + participants, + teams: [ + { teamId: 100, win: params.winningTeamId === 100 }, + { teamId: 200, win: params.winningTeamId === 200 }, + ], + }, + } as unknown as RiotMatchDto; +} + +describe('computeGameResult', () => { + it('maps Riot teams to local blue/red by overlap', () => { + const { match, lookup } = makeMatch(); + const detail = makeRiotMatch({ + team100Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'], + team200Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'], + winningTeamId: 100, + }); + + const result = computeGameResult({ match, lookup, detail, gameNumber: 1 }); + + expect(result).toMatchObject({ + gameNumber: 1, + riotMatchId: 'KR_1', + winnerSide: 'blue', + gameDuration: 1800, + }); + expect(result?.participants).toHaveLength(10); + }); + + it('handles reversed Riot side assignment', () => { + const { match, lookup } = makeMatch(); + const detail = makeRiotMatch({ + team100Puuids: ['puuid-5', 'puuid-6', 'puuid-7', 'puuid-8', 'puuid-9'], + team200Puuids: ['puuid-0', 'puuid-1', 'puuid-2', 'puuid-3', 'puuid-4'], + winningTeamId: 100, + }); + + const result = computeGameResult({ match, lookup, detail, gameNumber: 2 }); + + expect(result?.winnerSide).toBe('red'); + }); + + it('rejects matches with too little overlap', () => { + const { match, lookup } = makeMatch(); + const detail = makeRiotMatch({ + team100Puuids: ['other-1', 'other-2', 'other-3', 'other-4', 'other-5'], + team200Puuids: ['other-6', 'other-7', 'other-8', 'other-9', 'other-10'], + winningTeamId: 100, + }); + + const result = computeGameResult({ match, lookup, detail, gameNumber: 3 }); + + expect(result).toBeNull(); + }); +}); diff --git a/apps/api/src/modules/tournament-result/team-mapping.util.ts b/apps/api/src/modules/tournament-result/team-mapping.util.ts new file mode 100644 index 00000000..a617b78f --- /dev/null +++ b/apps/api/src/modules/tournament-result/team-mapping.util.ts @@ -0,0 +1,118 @@ +import mongoose from 'mongoose'; +import type { + MatchDocument, + MatchGameResult, + TeamSide, +} from '../global/database/schema'; +import type { RiotMatchDto } from '../riot/riot.types'; + +const RIOT_BLUE_TEAM_ID = 100; +const RIOT_RED_TEAM_ID = 200; +const MINIMUM_TRUSTED_OVERLAP = 6; + +export interface MatchPuuidLookup { + puuidByUserId: Map; + userIdByPuuid: Map; +} + +export function collectCaptainUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { + return match.teams + .map((team) => team.captainUserId) + .filter((userId): userId is mongoose.Types.ObjectId => Boolean(userId)); +} + +export function collectMatchUserIds(match: MatchDocument): mongoose.Types.ObjectId[] { + const ids = new Map(); + for (const participant of match.participants) { + ids.set(participant.userId.toString(), participant.userId); + } + for (const team of match.teams) { + if (team.captainUserId) ids.set(team.captainUserId.toString(), team.captainUserId); + for (const member of team.members) { + ids.set(member.userId.toString(), member.userId); + } + } + return [...ids.values()]; +} + +export function collectTeamPuuids( + match: MatchDocument, + side: TeamSide, + lookup: MatchPuuidLookup, +): string[] { + const team = match.teams.find((item) => item.side === side); + if (!team) return []; + return team.members + .map((member) => lookup.puuidByUserId.get(member.userId.toString())) + .filter((puuid): puuid is string => Boolean(puuid)); +} + +export function computeGameResult(params: { + match: MatchDocument; + detail: RiotMatchDto; + gameNumber: number; + lookup: MatchPuuidLookup; +}): MatchGameResult | null { + const { match, detail, gameNumber, lookup } = params; + const ourBluePuuids = collectTeamPuuids(match, 'blue', lookup); + const ourRedPuuids = collectTeamPuuids(match, 'red', lookup); + const team100Puuids = detail.info.participants + .filter((participant) => participant.teamId === RIOT_BLUE_TEAM_ID) + .map((participant) => participant.puuid); + const team200Puuids = detail.info.participants + .filter((participant) => participant.teamId === RIOT_RED_TEAM_ID) + .map((participant) => participant.puuid); + + const normalOverlap = + countOverlap(team100Puuids, ourBluePuuids) + + countOverlap(team200Puuids, ourRedPuuids); + const reversedOverlap = + countOverlap(team100Puuids, ourRedPuuids) + + countOverlap(team200Puuids, ourBluePuuids); + const teamMapping: Record = + normalOverlap >= reversedOverlap + ? { [RIOT_BLUE_TEAM_ID]: 'blue', [RIOT_RED_TEAM_ID]: 'red' } + : { [RIOT_BLUE_TEAM_ID]: 'red', [RIOT_RED_TEAM_ID]: 'blue' }; + + if (Math.max(normalOverlap, reversedOverlap) < MINIMUM_TRUSTED_OVERLAP) { + return null; + } + + const winningTeam = detail.info.teams.find((team) => team.win); + if (!winningTeam) return null; + const winnerSide = teamMapping[winningTeam.teamId]; + if (!winnerSide) return null; + + const participants = detail.info.participants + .map((participant) => { + const userId = lookup.userIdByPuuid.get(participant.puuid); + const side = teamMapping[participant.teamId]; + if (!userId || !side) return null; + return { + userId, + side, + championId: participant.championId, + kills: participant.kills, + deaths: participant.deaths, + assists: participant.assists, + win: participant.win, + }; + }) + .filter((participant): participant is NonNullable => + Boolean(participant), + ); + + return { + gameNumber, + riotMatchId: detail.metadata.matchId, + winnerSide, + gameCreation: detail.info.gameCreation, + gameDuration: detail.info.gameDuration, + participants, + }; +} + +export function countOverlap(left: string[], right: string[]): number { + const rightSet = new Set(right); + return left.filter((item) => rightSet.has(item)).length; +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.controller.ts b/apps/api/src/modules/tournament-result/tournament-result.controller.ts new file mode 100644 index 00000000..9f9e627e --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.controller.ts @@ -0,0 +1,39 @@ +import { + BadRequestException, + Controller, + Param, + Post, + 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 { TournamentResultService } from './tournament-result.service'; + +@Controller('communities/:communityId/matches/:matchId/poll-tournament-result') +@Roles('owner', 'admin') +@UseGuards(RolesGuard) +export class TournamentResultController { + constructor( + private readonly tournamentResultService: TournamentResultService, + ) {} + + @Post() + public async poll( + @CurrentUser() currentUser: UserDocument, + @Param('communityId', ParseObjectIdPipe) + communityId: mongoose.Types.ObjectId, + @Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId, + ) { + if (!currentUser.communityId.equals(communityId)) { + throw new BadRequestException('Different community.'); + } + return this.tournamentResultService.scheduleManualPoll({ + matchId, + communityId, + }); + } +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.module.ts b/apps/api/src/modules/tournament-result/tournament-result.module.ts new file mode 100644 index 00000000..b9281ad0 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.module.ts @@ -0,0 +1,14 @@ +import { forwardRef, Module } from '@nestjs/common'; +import { CommunityStatsModule } from '../community-stats/community-stats.module'; +import { RiotJobQueueModule } from '../riot-job-queue/riot-job-queue.module'; +import { RiotModule } from '../riot/riot.module'; +import { TournamentResultController } from './tournament-result.controller'; +import { TournamentResultService } from './tournament-result.service'; + +@Module({ + imports: [RiotModule, CommunityStatsModule, forwardRef(() => RiotJobQueueModule)], + controllers: [TournamentResultController], + providers: [TournamentResultService], + exports: [TournamentResultService], +}) +export class TournamentResultModule {} diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.ts b/apps/api/src/modules/tournament-result/tournament-result.service.ts new file mode 100644 index 00000000..2ce0be98 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.service.ts @@ -0,0 +1,464 @@ +import { + BadRequestException, + Injectable, + Logger, + NotFoundException, +} from '@nestjs/common'; +import mongoose from 'mongoose'; +import { CommunityStatsService } from '../community-stats/community-stats.service'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + MatchDocument, + MatchGameResult, + RiotMatch as StoredRiotMatch, + TournamentCodeDocument, +} from '../global/database/schema'; +import { RiotJobQueueService } from '../riot-job-queue/riot-job-queue.service'; +import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; +import { RiotMatchService } from '../riot/riot-match.service'; +import type { RiotMatchDto, RiotRegionalRoute } from '../riot/riot.types'; +import { + collectCaptainUserIds, + collectMatchUserIds, + computeGameResult, + type MatchPuuidLookup, +} from './team-mapping.util'; +import type { + EnqueueTournamentResultPollResult, + PollTournamentResultJob, +} from './tournament-result.types'; + +const FIRST_HOUR_POLL_DELAY_MS = 5 * 60_000; +const LATER_POLL_DELAY_MS = 60 * 60_000; +const POLL_EXPIRY_MS = 24 * 60 * 60_000; +const EXPAND_AFTER_MS = 60 * 60_000; +const TOURNAMENT_LOOKUP_START_MARGIN_SECONDS = 60; + +@Injectable() +export class TournamentResultService { + private readonly logger = new Logger(TournamentResultService.name); + + constructor( + private readonly connectionService: ConnectionService, + private readonly riotMatchService: RiotMatchService, + private readonly riotJobQueueService: RiotJobQueueService, + private readonly communityStatsService: CommunityStatsService, + ) {} + + public async scheduleInitialPoll( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + priority: RiotJobPriority = 'high', + ): Promise { + const match = await this.loadMatch(matchOrId); + if (match.status === 'finished') return null; + if (!this.isReadyToPoll(match)) return null; + + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: match.resultPollState?.lastPolledAt, + lastPollOutcome: match.resultPollState?.lastPollOutcome, + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids: false, + state: 'polling', + }; + await match.save(); + + return this.riotJobQueueService.enqueueTournamentResultPoll({ + matchId: match._id.toString(), + attempt: 1, + expandedToAllPuuids: false, + priority, + }); + } + + public async scheduleManualPoll(params: { + matchId: mongoose.Types.ObjectId; + communityId: mongoose.Types.ObjectId; + }): Promise { + const match = await this.loadMatch(params.matchId); + if (!match.communityId.equals(params.communityId)) { + throw new BadRequestException('Match does not belong to this community.'); + } + if (!this.isReadyToPoll(match)) { + throw new BadRequestException( + 'Match needs built teams, teamBuiltAt, and tournament codes before polling.', + ); + } + const result = await this.scheduleInitialPoll(match, 'high'); + if (!result) { + throw new BadRequestException('Tournament result polling is not available.'); + } + return result; + } + + public async processPollJob(job: PollTournamentResultJob): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const TournamentCodeModel = + await this.connectionService.getModel('tournamentCode'); + const CommunityModel = await this.connectionService.getModel('community'); + const match = await MatchModel.findById(job.matchId); + if (!match || match.status === 'finished') return; + if (!this.isReadyToPoll(match)) { + await this.updatePollState(match, 'failed', job.expandedToAllPuuids); + return; + } + + const codes = await TournamentCodeModel.find({ matchId: match._id }) + .sort({ gameNumber: 1 }) + .exec(); + const unmatched = codes.filter( + (code) => code.state === 'reserved' && !code.riotMatchId, + ); + if (unmatched.length === 0) { + await this.advanceMatchIfReady(match, codes); + return; + } + + const community = await CommunityModel.findById(match.communityId) + .select({ riotRegion: 1 }) + .lean() + .exec(); + const region = community?.riotRegion ?? 'asia'; + const lookup = await this.buildPuuidLookup(match); + const puuids = job.expandedToAllPuuids + ? this.collectPollingPuuids(collectMatchUserIds(match), lookup) + : this.collectPollingPuuids(collectCaptainUserIds(match), lookup); + + const matchedGameNumbers = new Set(); + const checkedRiotMatchIds = new Set(); + const unmatchedByCode = new Map(unmatched.map((code) => [code.code, code])); + + for (const puuid of puuids) { + let ids: string[]; + try { + ids = await this.riotMatchService.getMatchIdsByPuuid(puuid, { + region, + type: 'tourney', + startTime: this.resolveStartTime(match), + endTime: Math.floor(Date.now() / 1000), + count: 100, + }); + } catch (error) { + this.logger.warn( + `Tournament result match id lookup failed for ${puuid}: ${ + error instanceof Error ? error.message : error + }`, + ); + continue; + } + + for (const riotMatchId of ids) { + if (checkedRiotMatchIds.has(riotMatchId)) continue; + checkedRiotMatchIds.add(riotMatchId); + + const alreadyMatched = await TournamentCodeModel.exists({ riotMatchId }); + if (alreadyMatched) continue; + + let detail: RiotMatchDto; + try { + detail = await this.ensureRiotMatchPersisted(riotMatchId, region); + } catch (error) { + this.logger.warn( + `Tournament result detail fetch failed for ${riotMatchId}: ${ + error instanceof Error ? error.message : error + }`, + ); + continue; + } + const tournamentCode = detail.info.tournamentCode?.trim().toUpperCase(); + if (!tournamentCode) continue; + + const code = unmatchedByCode.get(tournamentCode); + if (!code) continue; + + const applied = await this.applyMatchToGameSlot({ + match, + code, + detail, + lookup, + }); + if (applied) { + matchedGameNumbers.add(code.gameNumber ?? 0); + unmatchedByCode.delete(tournamentCode); + } + } + } + + const reloadedCodes = await TournamentCodeModel.find({ matchId: match._id }) + .sort({ gameNumber: 1 }) + .exec(); + const outcome = matchedGameNumbers.size > 0 ? 'matched' : 'not-found'; + await this.updatePollState(match, outcome, job.expandedToAllPuuids); + const completed = await this.advanceMatchIfReady(match, reloadedCodes); + if (!completed) { + await this.scheduleNextPoll(match, job); + } + } + + private async applyMatchToGameSlot(params: { + match: MatchDocument; + code: TournamentCodeDocument; + detail: RiotMatchDto; + lookup: MatchPuuidLookup; + }): Promise { + const { match, code, detail, lookup } = params; + if (code.state !== 'reserved' || code.riotMatchId) return false; + if (!code.gameNumber) return false; + + const gameResult = computeGameResult({ + match, + detail, + gameNumber: code.gameNumber, + lookup, + }); + if (!gameResult) { + this.logger.warn( + `Skipped tournament result ${detail.metadata.matchId}; team mapping was not trusted for match ${match._id.toString()}.`, + ); + return false; + } + + code.state = 'used'; + code.usedAt = new Date(detail.info.gameEndTimestamp ?? detail.info.gameCreation); + code.riotMatchId = detail.metadata.matchId; + await code.save(); + + this.upsertGameResult(match, gameResult); + if (match.status === 'team-built') { + match.status = 'in-progress'; + } + await match.save(); + return true; + } + + private async advanceMatchIfReady( + match: MatchDocument, + codes: TournamentCodeDocument[], + ): Promise { + if (codes.length < match.gameCount) return false; + if (!codes.every((code) => code.state === 'used' && code.riotMatchId)) { + return false; + } + + match.status = 'finished'; + if (match.result) { + match.result.winnerSide = + match.result.blueScore > match.result.redScore + ? 'blue' + : match.result.redScore > match.result.blueScore + ? 'red' + : undefined; + } + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: match.resultPollState?.lastPolledAt, + lastPollOutcome: match.resultPollState?.lastPollOutcome, + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids: match.resultPollState?.expandedToAllPuuids ?? false, + state: 'complete', + }; + await match.save(); + void this.communityStatsService + .invalidateCommunity(match.communityId) + .catch((error) => { + this.logger.warn( + `Failed to invalidate community stats cache for ${match.communityId.toString()}: ${ + error instanceof Error ? error.message : error + }`, + ); + }); + return true; + } + + private async scheduleNextPoll( + match: MatchDocument, + job: PollTournamentResultJob, + ): Promise { + const pollState = match.resultPollState; + const startedAt = pollState?.startedAt ?? new Date(); + const elapsedMs = Date.now() - startedAt.getTime(); + const delayMs = this.nextPollDelayMs(elapsedMs); + if (delayMs === null) { + match.resultPollState = { + startedAt, + lastPolledAt: pollState?.lastPolledAt, + lastPollOutcome: pollState?.lastPollOutcome, + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids: pollState?.expandedToAllPuuids ?? job.expandedToAllPuuids, + state: 'expired', + }; + await match.save(); + this.logger.warn( + `Tournament result polling expired for match ${match._id.toString()}.`, + ); + return; + } + + const expandedToAllPuuids = + job.expandedToAllPuuids || + (elapsedMs >= EXPAND_AFTER_MS && (match.result?.games?.length ?? 0) === 0); + await this.riotJobQueueService.enqueueTournamentResultPoll({ + matchId: match._id.toString(), + attempt: job.attempt + 1, + expandedToAllPuuids, + priority: 'low', + deferUntilMs: Date.now() + delayMs, + }); + } + + private async ensureRiotMatchPersisted( + riotMatchId: string, + region: RiotRegionalRoute, + ): Promise { + 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 = { + 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, + fetchedAt: new Date(), + }; + await RiotMatchModel.updateOne( + { matchId: dto.metadata.matchId }, + { $setOnInsert: payload }, + { upsert: true }, + ).exec(); + return dto; + } + + private async buildPuuidLookup(match: MatchDocument): Promise { + const puuidByUserId = new Map(); + const userIdByPuuid = new Map(); + + for (const participant of match.participants) { + if (!participant.puuid) continue; + const userId = participant.userId.toString(); + puuidByUserId.set(userId, participant.puuid); + userIdByPuuid.set(participant.puuid, participant.userId); + } + + const missingUserIds = collectMatchUserIds(match).filter( + (userId) => !puuidByUserId.has(userId.toString()), + ); + if (missingUserIds.length > 0) { + const UserModel = await this.connectionService.getModel('user'); + const users = await UserModel.find({ _id: { $in: missingUserIds } }) + .select({ riotAccounts: 1 }) + .exec(); + for (const user of users) { + const primary = + user.riotAccounts.find((account) => account.isPrimary) ?? + user.riotAccounts[0]; + if (!primary) continue; + puuidByUserId.set(user._id.toString(), primary.puuid); + userIdByPuuid.set(primary.puuid, user._id); + } + } + + return { puuidByUserId, userIdByPuuid }; + } + + private collectPollingPuuids( + userIds: mongoose.Types.ObjectId[], + lookup: MatchPuuidLookup, + ): string[] { + return [ + ...new Set( + userIds + .map((userId) => lookup.puuidByUserId.get(userId.toString())) + .filter((puuid): puuid is string => Boolean(puuid)), + ), + ]; + } + + private upsertGameResult( + match: MatchDocument, + gameResult: MatchGameResult, + ): void { + const currentGames = match.result?.games ?? []; + const games = [ + ...currentGames.filter( + (game) => + game.gameNumber !== gameResult.gameNumber && + game.riotMatchId !== gameResult.riotMatchId, + ), + gameResult, + ].sort((left, right) => left.gameNumber - right.gameNumber); + + match.result = { + winnerSide: match.result?.winnerSide, + blueScore: games.filter((game) => game.winnerSide === 'blue').length, + redScore: games.filter((game) => game.winnerSide === 'red').length, + mvpUserId: match.result?.mvpUserId, + riotMatchIds: [...new Set(games.map((game) => game.riotMatchId))], + games, + }; + } + + private async updatePollState( + match: MatchDocument, + outcome: 'matched' | 'not-found' | 'failed', + expandedToAllPuuids: boolean, + ): Promise { + match.resultPollState = { + startedAt: match.resultPollState?.startedAt ?? new Date(), + lastPolledAt: new Date(), + lastPollOutcome: outcome, + matchedCount: match.result?.games?.length ?? 0, + expandedToAllPuuids, + state: outcome === 'failed' ? 'failed' : 'polling', + }; + await match.save(); + } + + private nextPollDelayMs(elapsedMs: number): number | null { + if (elapsedMs >= POLL_EXPIRY_MS) return null; + if (elapsedMs <= EXPAND_AFTER_MS) return FIRST_HOUR_POLL_DELAY_MS; + return LATER_POLL_DELAY_MS; + } + + private resolveStartTime(match: MatchDocument): number { + return Math.max( + 0, + Math.floor(match.teamBuiltAt!.getTime() / 1000) - + TOURNAMENT_LOOKUP_START_MARGIN_SECONDS, + ); + } + + private isReadyToPoll(match: MatchDocument): boolean { + return Boolean( + match.teamBuiltAt && + match.tournamentCodeIds.length > 0 && + match.teams.length >= 2 && + match.teams.every((team) => team.members.length > 0), + ); + } + + private async loadMatch( + matchOrId: MatchDocument | mongoose.Types.ObjectId, + ): Promise { + const MatchModel = await this.connectionService.getModel('match'); + const match = + matchOrId instanceof mongoose.Types.ObjectId + ? await MatchModel.findById(matchOrId) + : await MatchModel.findById(matchOrId._id); + if (!match) throw new NotFoundException('Match not found.'); + return match; + } +} + +function isRiotMatchDto(value: unknown): value is RiotMatchDto { + return Boolean( + value && + typeof value === 'object' && + 'metadata' in value && + 'info' in value, + ); +} diff --git a/apps/api/src/modules/tournament-result/tournament-result.types.ts b/apps/api/src/modules/tournament-result/tournament-result.types.ts new file mode 100644 index 00000000..25e265b7 --- /dev/null +++ b/apps/api/src/modules/tournament-result/tournament-result.types.ts @@ -0,0 +1,30 @@ +import type { TeamSide } from '../global/database/schema'; +import type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; + +export interface PollTournamentResultJob { + kind: 'poll-tournament-result'; + jobId: string; + matchId: string; + attempt: number; + expandedToAllPuuids: boolean; + enqueuedAt: number; + priority: RiotJobPriority; +} + +export interface EnqueueTournamentResultPollResult { + jobId: string; + matchId: string; + priority: RiotJobPriority; + attempt: number; + expandedToAllPuuids: boolean; +} + +export interface ComputedGameParticipant { + userId: string; + side: TeamSide; + championId: number; + kills: number; + deaths: number; + assists: number; + win: boolean; +} diff --git a/apps/api/src/modules/user/dto/me-response.dto.ts b/apps/api/src/modules/user/dto/me-response.dto.ts new file mode 100644 index 00000000..0bd09bbf --- /dev/null +++ b/apps/api/src/modules/user/dto/me-response.dto.ts @@ -0,0 +1,22 @@ +import type { + CommunityDocument, + UserDocument, +} from '../../global/database/schema'; + +export interface MeIdentityDto { + id: string; + entraOid: string; + tenantId?: string; + email?: string; + displayName?: string; +} + +export interface MeMembershipDto { + user: UserDocument; + community: CommunityDocument | null; +} + +export interface MeResponseDto { + identity: MeIdentityDto | null; + memberships: MeMembershipDto[]; +} diff --git a/apps/api/src/modules/user/dto/refresh-riot-account.dto.ts b/apps/api/src/modules/user/dto/refresh-riot-account.dto.ts new file mode 100644 index 00000000..02d9fd2d --- /dev/null +++ b/apps/api/src/modules/user/dto/refresh-riot-account.dto.ts @@ -0,0 +1,13 @@ +import { IsBoolean, IsIn, IsOptional } from 'class-validator'; +import { RIOT_PLATFORM_ROUTES } from '../../riot/riot.types'; +import type { RiotPlatformRoute } from '../../riot/riot.types'; + +export class RefreshRiotAccountDto { + @IsOptional() + @IsBoolean() + force?: boolean; + + @IsOptional() + @IsIn(RIOT_PLATFORM_ROUTES) + platform?: RiotPlatformRoute; +} diff --git a/apps/api/src/modules/user/user.controller.ts b/apps/api/src/modules/user/user.controller.ts new file mode 100644 index 00000000..9b614966 --- /dev/null +++ b/apps/api/src/modules/user/user.controller.ts @@ -0,0 +1,120 @@ +import { + Body, + Controller, + ForbiddenException, + Get, + Param, + Post, + Req, + UnauthorizedException, +} from '@nestjs/common'; +import type { Request } from 'express'; +import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; +import '../auth/auth-request'; +import { CurrentUser } from '../auth/current-user.decorator'; +import { ConnectionService } from '../global/database/connection.service'; +import type { + IdentityDocument, + UserDocument, +} from '../global/database/schema'; +import { RiotAccountEnrichmentService } from '../riot/riot-account-enrichment.service'; +import type { MeResponseDto } from './dto/me-response.dto'; +import { RefreshRiotAccountDto } from './dto/refresh-riot-account.dto'; + +@Controller('me') +export class UserController { + constructor( + private readonly enrichment: RiotAccountEnrichmentService, + private readonly connectionService: ConnectionService, + ) {} + + @Get() + @AllowPublicAccess() + public async me(@Req() req: Request): Promise { + if (req.identity) { + return this.resolveMeByIdentity(req.identity); + } + if (req.user) { + return { + identity: null, + memberships: [ + { + user: req.user, + community: await this.findCommunity(req.user), + }, + ], + }; + } + return { identity: null, memberships: [] }; + } + + @Post('riot-accounts/:puuid/refresh') + public async refreshRiotAccount( + @CurrentUser() user: UserDocument | undefined, + @Req() req: Request, + @Param('puuid') puuid: string, + @Body() body: RefreshRiotAccountDto, + ) { + const resolvedUser = + user ?? (req.identity ? await this.findUserByIdentityAndPuuid(req.identity, puuid) : null); + if (!resolvedUser) { + throw new UnauthorizedException('Authentication required.'); + } + if (!resolvedUser.riotAccounts.some((account) => account.puuid === puuid)) { + throw new ForbiddenException('Riot account does not belong to user.'); + } + + return this.enrichment.enrichRiotAccount({ + userId: resolvedUser._id, + puuid, + options: { + force: body.force === true, + platform: body.platform, + }, + }); + } + + private async resolveMeByIdentity( + identity: IdentityDocument, + ): Promise { + const UserModel = await this.connectionService.getModel('user'); + const CommunityModel = await this.connectionService.getModel('community'); + const users = await UserModel.find({ identityId: identity._id }).exec(); + const communities = await CommunityModel.find({ + _id: { $in: users.map((user) => user.communityId) }, + }).exec(); + const communityById = new Map( + communities.map((community) => [community._id.toString(), community]), + ); + + return { + identity: { + id: identity._id.toString(), + entraOid: identity.entraOid, + tenantId: identity.tenantId, + email: identity.email, + displayName: identity.displayName, + }, + memberships: users.map((user) => ({ + user, + community: communityById.get(user.communityId.toString()) ?? null, + })), + }; + } + + private async findCommunity(user: UserDocument) { + const CommunityModel = await this.connectionService.getModel('community'); + return CommunityModel.findById(user.communityId).exec(); + } + + private async findUserByIdentityAndPuuid( + identity: IdentityDocument, + puuid: string, + ): Promise { + const UserModel = await this.connectionService.getModel('user'); + return UserModel.findOne({ + identityId: identity._id, + 'riotAccounts.puuid': puuid, + }).exec(); + } +} diff --git a/apps/api/src/modules/user/user.module.ts b/apps/api/src/modules/user/user.module.ts new file mode 100644 index 00000000..66ca9ce0 --- /dev/null +++ b/apps/api/src/modules/user/user.module.ts @@ -0,0 +1,9 @@ +import { Module } from '@nestjs/common'; +import { RiotModule } from '../riot/riot.module'; +import { UserController } from './user.controller'; + +@Module({ + imports: [RiotModule], + controllers: [UserController], +}) +export class UserModule {} diff --git a/apps/api/src/seed-dakao-participant.ts b/apps/api/src/seed-dakao-participant.ts new file mode 100644 index 00000000..f66befa7 --- /dev/null +++ b/apps/api/src/seed-dakao-participant.ts @@ -0,0 +1,241 @@ +import 'reflect-metadata'; +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import mongoose from 'mongoose'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { ConnectionService } from './modules/global/database/connection.service'; +import { SecretModule } from './modules/global/secret/secret.module'; +import { MatchService } from './modules/match/match.service'; +import { DakaoUserService } from './modules/dakao/dakao-user.service'; +import { parsePositionList } from './modules/dakao/parsers/position.parser'; +import { normalizeRiotIdPart } from './modules/dakao/riot-id.util'; +import { RiotAccountEnrichmentService } from './modules/riot/riot-account-enrichment.service'; +import { RiotAccountService } from './modules/riot/riot-account.service'; +import { RiotChampionMasteryService } from './modules/riot/riot-champion-mastery.service'; +import { RiotClientService } from './modules/riot/riot.client.service'; +import { RiotLeagueService } from './modules/riot/riot-league.service'; +import { RiotSummonerService } from './modules/riot/riot-summoner.service'; + +process.env.NODE_ENV ??= 'dev'; + +const DEFAULT_INPUT = { + projectId: '69985467365c75936c355318', + matchId: '69ebe0adf627c11be2f020bb', + senderId: '6657856481076543434', + nickname: '집밖은 위험해/92/여/P', + riotId: '집밖은 위험해#SOS', + positions: 'SUP,MID', +}; + +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + envFilePath: [ + resolve(__dirname, '../../project.env'), + resolve(process.cwd(), 'apps/project.env'), + resolve(process.cwd(), 'project.env'), + ], + }), + SecretModule, + ], + providers: [ + ConnectionService, + RiotClientService, + RiotAccountService, + RiotSummonerService, + RiotLeagueService, + RiotChampionMasteryService, + RiotAccountEnrichmentService, + DakaoUserService, + MatchService, + ], +}) +class SeedDakaoParticipantModule {} + +async function loadMachineEnvFile() { + const homeDir = process.env.HOME ?? process.env.USERPROFILE; + if (!homeDir) return; + + const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt'); + + try { + const file = await readFile(machineEnvFile, 'utf8'); + for (const rawLine of file.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + + const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); + if (!matched) continue; + + const [, key, rawValue] = matched; + process.env[key] = rawValue.replace(/^["']|["']$/g, ''); + } + } catch { + // start.ps1과 동일하게 로컬 machine env 파일이 없으면 무시한다. + } +} + +function readInput() { + const riotId = process.env.DAKAO_SEED_RIOT_ID ?? DEFAULT_INPUT.riotId; + const hashIndex = riotId.lastIndexOf('#'); + if (hashIndex <= 0 || hashIndex === riotId.length - 1) { + throw new Error(`Invalid Riot ID: ${riotId}`); + } + + return { + projectId: process.env.DAKAO_SEED_PROJECT_ID ?? DEFAULT_INPUT.projectId, + matchId: process.env.DAKAO_SEED_MATCH_ID ?? DEFAULT_INPUT.matchId, + senderId: process.env.DAKAO_SEED_SENDER_ID ?? DEFAULT_INPUT.senderId, + nickname: process.env.DAKAO_SEED_NICKNAME ?? DEFAULT_INPUT.nickname, + gameName: normalizeRiotIdPart(riotId.slice(0, hashIndex)), + tagLine: normalizeRiotIdPart(riotId.slice(hashIndex + 1)), + positions: parsePositionList( + process.env.DAKAO_SEED_POSITIONS ?? DEFAULT_INPUT.positions, + ).positions, + }; +} + +async function ensureCommunityDakaoProjectId(params: { + connectionService: ConnectionService; + matchId: mongoose.Types.ObjectId; + projectId: mongoose.Types.ObjectId; +}): Promise { + const MatchModel = await params.connectionService.getModel('match'); + const CommunityModel = await params.connectionService.getModel('community'); + const match = await MatchModel.findById(params.matchId).exec(); + if (!match) { + throw new Error(`Match not found: ${params.matchId.toString()}`); + } + + const community = await CommunityModel.findById(match.communityId).exec(); + if (!community) { + throw new Error(`Community not found: ${match.communityId.toString()}`); + } + + if (community.dakaoProjectId?.equals(params.projectId)) { + return community._id; + } + if (community.dakaoProjectId) { + throw new Error( + `Community already has a different dakaoProjectId: ${community.dakaoProjectId.toString()}`, + ); + } + + const conflictingCommunity = await CommunityModel.findOne({ + _id: { $ne: community._id }, + dakaoProjectId: params.projectId, + }).exec(); + if (conflictingCommunity) { + throw new Error( + `dakaoProjectId already belongs to another community: ${conflictingCommunity._id.toString()}`, + ); + } + + community.dakaoProjectId = params.projectId; + await community.save(); + return community._id; +} + +async function main() { + await loadMachineEnvFile(); + + const input = readInput(); + if (!mongoose.isValidObjectId(input.projectId)) { + throw new Error(`Invalid projectId: ${input.projectId}`); + } + if (!mongoose.isValidObjectId(input.matchId)) { + throw new Error(`Invalid matchId: ${input.matchId}`); + } + + const app = await NestFactory.createApplicationContext( + SeedDakaoParticipantModule, + { logger: ['error', 'warn', 'log'] }, + ); + + try { + const connectionService = app.get(ConnectionService); + const dakaoUserService = app.get(DakaoUserService); + const matchService = app.get(MatchService); + const MatchModel = await connectionService.getModel('match'); + + const matchId = new mongoose.Types.ObjectId(input.matchId); + const projectId = new mongoose.Types.ObjectId(input.projectId); + const communityId = await ensureCommunityDakaoProjectId({ + connectionService, + matchId, + projectId, + }); + + const resolved = await dakaoUserService.resolveRiotAccount({ + communityId, + kakaoTalkId: input.senderId, + kakaoTalkNickname: input.nickname, + gameName: input.gameName, + tagLine: input.tagLine, + }); + + const existing = await MatchModel.findOne({ + _id: matchId, + 'participants.userId': resolved.user._id, + }).exec(); + if (existing) { + console.log('[seed:dakao-participant] Participant already exists.'); + console.log( + JSON.stringify( + { + communityId: communityId.toString(), + matchId: matchId.toString(), + userId: resolved.user._id.toString(), + puuid: resolved.riotAccount.puuid, + riotId: `${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`, + }, + null, + 2, + ), + ); + return; + } + + const preferredPositions = input.positions.map((position, index) => ({ + position, + priority: index + 1, + })); + + const match = await matchService.join({ + matchId, + userId: resolved.user._id, + riotPuuid: resolved.riotAccount.puuid, + preferredPositions, + }); + + console.log('[seed:dakao-participant] Participant added.'); + console.log( + JSON.stringify( + { + communityId: communityId.toString(), + matchId: match._id.toString(), + userId: resolved.user._id.toString(), + kakaoTalkId: input.senderId, + kakaoTalkNickname: input.nickname, + puuid: resolved.riotAccount.puuid, + riotId: `${resolved.riotAccount.gameName}#${resolved.riotAccount.tagLine}`, + preferredPositions, + participantCount: match.participants.length, + }, + null, + 2, + ), + ); + } finally { + await app.close(); + } +} + +void main().catch((error: unknown) => { + console.error('\n[seed:dakao-participant] Failed.\n'); + console.error(error); + process.exitCode = 1; +}); diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts new file mode 100644 index 00000000..8fe23f8c --- /dev/null +++ b/apps/api/src/seed.ts @@ -0,0 +1,1087 @@ +import 'reflect-metadata'; +import { Module } from '@nestjs/common'; +import { ConfigModule } from '@nestjs/config'; +import { NestFactory } from '@nestjs/core'; +import mongoose from 'mongoose'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { ConnectionService } from './modules/global/database/connection.service'; +import type { + ChampionMasteryEntry, + MatchParticipant, + MatchTeam, + Position, + PositionPreference, + RiotLane, + RiotRecentStatsSummary, + TierInfo, +} from './modules/global/database/schema'; +import { SecretModule } from './modules/global/secret/secret.module'; + +process.env.NODE_ENV ??= 'dev'; + +async function loadMachineEnvFile() { + const homeDir = process.env.HOME ?? process.env.USERPROFILE; + if (!homeDir) return; + + const machineEnvFile = resolve(homeDir, 'source/global-env-vars.txt'); + + try { + const file = await readFile(machineEnvFile, 'utf8'); + for (const rawLine of file.split(/\r?\n/)) { + const line = rawLine.trim(); + if (!line || line.startsWith('#')) continue; + + const matched = line.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/); + if (!matched) continue; + + const [, key, rawValue] = matched; + const value = rawValue.replace(/^["']|["']$/g, ''); + process.env[key] = value; + } + } catch { + // start.ps1도 파일이 없으면 그냥 지나간다. + } +} + +@Module({ + imports: [ + ConfigModule.forRoot({ + isGlobal: true, + envFilePath: [ + resolve(__dirname, '../../project.env'), + resolve(process.cwd(), 'apps/project.env'), + resolve(process.cwd(), 'project.env'), + ], + }), + SecretModule, + ], + providers: [ConnectionService], +}) +class SeedModule {} + +type SeedPlayer = { + key: string; + gameName: string; + tagLine: string; + kakaoTalkNickname: string; + profileIconId: number; + main: Position; + sub: Position; + tier: { + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + }; + flex?: { + tier: string; + rank: string; + leaguePoints: number; + wins: number; + losses: number; + }; + masteries: SeedChampionMastery[]; + recentStatsSummary: SeedRecentStatsSummary; +}; + +type SeedChampionMastery = { + championId: string; + championName?: string; + level: number; + points: number; +}; + +type SeedRecentStatsSummary = { + games: number; + wins: number; + losses: number; + avgKills: number; + avgDeaths: number; + avgAssists: number; + avgCs: number; + avgCsPerMin?: number; + mostPlayedChampionIds: string[]; +}; + +const DEV_COMMUNITY_NAME = '[DEV] Lolympus Test Community'; +const DEV_COMMUNITY_DESCRIPTION = + 'Frontend/Backend 통합 검증용으로 생성된 개발 커뮤니티입니다.'; + +const NOW = new Date(); + +const CHAMPION_IDS: Record = { + Ahri: 103, + Ashe: 22, + Camille: 164, + Ezreal: 81, + Gwen: 887, + Hwei: 910, + JarvanIV: 59, + Jax: 24, + Jinx: 222, + KaiSa: 145, + LeeSin: 64, + Nami: 267, + Nasus: 75, + Nautilus: 111, + Nidalee: 76, + Orianna: 61, + Rakan: 497, + Rengar: 107, + Sona: 37, + Syndra: 134, + Taliyah: 163, + Thresh: 412, + Viego: 234, + Viktor: 112, + Xayah: 498, + Yorick: 83, + Yuumi: 350, + Zeri: 221, +}; + +const POSITION_TO_RIOT_LANE: Record = { + TOP: 'TOP', + JGL: 'JUNGLE', + MID: 'MIDDLE', + ADC: 'BOTTOM', + SUP: 'UTILITY', +}; + +const PLAYER_SEEDS: SeedPlayer[] = [ + { + key: 'priri', + gameName: '프리리', + tagLine: 'KR1', + kakaoTalkNickname: '프리리', + profileIconId: 588, + main: 'MID', + sub: 'ADC', + tier: { + tier: 'DIAMOND', + rank: 'IV', + leaguePoints: 37, + wins: 66, + losses: 58, + }, + flex: { + tier: 'EMERALD', + rank: 'I', + leaguePoints: 54, + wins: 31, + losses: 22, + }, + masteries: [ + { + championId: 'Syndra', + championName: '신드라', + level: 7, + points: 124300, + }, + { championId: 'Ahri', championName: '아리', level: 7, points: 98200 }, + { + championId: 'Orianna', + championName: '오리아나', + level: 6, + points: 63400, + }, + ], + recentStatsSummary: { + games: 24, + wins: 14, + losses: 10, + avgKills: 7.8, + avgDeaths: 4.2, + avgAssists: 6.7, + avgCs: 188, + mostPlayedChampionIds: ['Syndra', 'Ahri', 'Orianna'], + }, + }, + { + key: 'hobul', + gameName: '호호불어먹어요', + tagLine: '0000', + kakaoTalkNickname: '호호불', + profileIconId: 7015, + main: 'JGL', + sub: 'TOP', + tier: { + tier: 'PLATINUM', + rank: 'II', + leaguePoints: 73, + wins: 54, + losses: 49, + }, + flex: { + tier: 'EMERALD', + rank: 'III', + leaguePoints: 22, + wins: 14, + losses: 10, + }, + masteries: [ + { championId: 'Viego', championName: '비에고', level: 7, points: 138200 }, + { championId: 'LeeSin', championName: '리신', level: 6, points: 88700 }, + { + championId: 'Nidalee', + championName: '니달리', + level: 6, + points: 64100, + }, + ], + recentStatsSummary: { + games: 28, + wins: 15, + losses: 13, + avgKills: 5.9, + avgDeaths: 4.9, + avgAssists: 9.1, + avgCs: 151, + mostPlayedChampionIds: ['Viego', 'LeeSin', 'Nidalee'], + }, + }, + { + key: 'soda', + gameName: '소다', + tagLine: 'KR1', + kakaoTalkNickname: '소다', + profileIconId: 5186, + main: 'TOP', + sub: 'MID', + tier: { + tier: 'EMERALD', + rank: 'I', + leaguePoints: 18, + wins: 49, + losses: 41, + }, + flex: { + tier: 'PLATINUM', + rank: 'I', + leaguePoints: 64, + wins: 20, + losses: 14, + }, + masteries: [ + { championId: 'Jax', championName: '잭스', level: 7, points: 112400 }, + { championId: 'Camille', championName: '카밀', level: 6, points: 76500 }, + { championId: 'Gwen', championName: '그웬', level: 6, points: 58700 }, + ], + recentStatsSummary: { + games: 21, + wins: 11, + losses: 10, + avgKills: 5.4, + avgDeaths: 4.6, + avgAssists: 5.2, + avgCs: 201, + mostPlayedChampionIds: ['Jax', 'Camille', 'Gwen'], + }, + }, + { + key: 'inghoba', + gameName: '잉호바', + tagLine: 'KR1', + kakaoTalkNickname: '잉호바', + profileIconId: 7050, + main: 'SUP', + sub: 'MID', + tier: { + tier: 'DIAMOND', + rank: 'III', + leaguePoints: 41, + wins: 72, + losses: 60, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 121, + wins: 19, + losses: 11, + }, + masteries: [ + { + championId: 'Thresh', + championName: '쓰레쉬', + level: 7, + points: 187300, + }, + { + championId: 'Nautilus', + championName: '노틸러스', + level: 7, + points: 144800, + }, + { championId: 'Rakan', championName: '라칸', level: 6, points: 65300 }, + ], + recentStatsSummary: { + games: 32, + wins: 19, + losses: 13, + avgKills: 2.5, + avgDeaths: 4.3, + avgAssists: 14.8, + avgCs: 34, + mostPlayedChampionIds: ['Thresh', 'Nautilus', 'Rakan'], + }, + }, + { + key: 'tabkey', + gameName: '잉호바탭키도둑', + tagLine: 'Tab', + kakaoTalkNickname: '탭키도둑', + profileIconId: 5231, + main: 'ADC', + sub: 'SUP', + tier: { + tier: 'PLATINUM', + rank: 'I', + leaguePoints: 47, + wins: 61, + losses: 56, + }, + flex: { + tier: 'EMERALD', + rank: 'IV', + leaguePoints: 28, + wins: 22, + losses: 20, + }, + masteries: [ + { championId: 'Jinx', championName: '징크스', level: 7, points: 166100 }, + { championId: 'KaiSa', championName: '카이사', level: 7, points: 139400 }, + { + championId: 'Ezreal', + championName: '이즈리얼', + level: 6, + points: 90100, + }, + ], + recentStatsSummary: { + games: 29, + wins: 16, + losses: 13, + avgKills: 8.4, + avgDeaths: 4.8, + avgAssists: 6.1, + avgCs: 213, + mostPlayedChampionIds: ['Jinx', 'KaiSa', 'Ezreal'], + }, + }, + { + key: 'osu', + gameName: 'osu', + tagLine: 'KR1', + kakaoTalkNickname: 'osu', + profileIconId: 7091, + main: 'MID', + sub: 'JGL', + tier: { + tier: 'EMERALD', + rank: 'III', + leaguePoints: 59, + wins: 58, + losses: 50, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 74, + wins: 12, + losses: 8, + }, + masteries: [ + { + championId: 'Viktor', + championName: '빅토르', + level: 7, + points: 172900, + }, + { championId: 'Hwei', championName: '흐웨이', level: 6, points: 94400 }, + { + championId: 'Taliyah', + championName: '탈리야', + level: 6, + points: 55300, + }, + ], + recentStatsSummary: { + games: 25, + wins: 13, + losses: 12, + avgKills: 6.3, + avgDeaths: 5.2, + avgAssists: 7.7, + avgCs: 198, + mostPlayedChampionIds: ['Viktor', 'Hwei', 'Taliyah'], + }, + }, + { + key: 'icequeen', + gameName: 'IceQueen', + tagLine: 'KR1', + kakaoTalkNickname: '아이스퀸', + profileIconId: 5102, + main: 'ADC', + sub: 'MID', + tier: { + tier: 'DIAMOND', + rank: 'II', + leaguePoints: 63, + wins: 67, + losses: 52, + }, + flex: { + tier: 'MASTER', + rank: '', + leaguePoints: 34, + wins: 11, + losses: 9, + }, + masteries: [ + { championId: 'Xayah', championName: '자야', level: 7, points: 154800 }, + { championId: 'Zeri', championName: '제리', level: 7, points: 141900 }, + { championId: 'Ashe', championName: '애쉬', level: 6, points: 59800 }, + ], + recentStatsSummary: { + games: 31, + wins: 18, + losses: 13, + avgKills: 7.7, + avgDeaths: 4.4, + avgAssists: 7.2, + avgCs: 226, + mostPlayedChampionIds: ['Xayah', 'Zeri', 'Ashe'], + }, + }, + { + key: 'jungler123', + gameName: '정글러123', + tagLine: 'KR3', + kakaoTalkNickname: '정글러123', + profileIconId: 4789, + main: 'JGL', + sub: 'SUP', + tier: { + tier: 'PLATINUM', + rank: 'III', + leaguePoints: 15, + wins: 43, + losses: 42, + }, + flex: { + tier: 'GOLD', + rank: 'I', + leaguePoints: 87, + wins: 18, + losses: 16, + }, + masteries: [ + { championId: 'LeeSin', championName: '리신', level: 7, points: 201300 }, + { championId: 'Viego', championName: '비에고', level: 6, points: 87600 }, + { championId: 'Rengar', championName: '렝가', level: 6, points: 65400 }, + ], + recentStatsSummary: { + games: 38, + wins: 18, + losses: 20, + avgKills: 5.4, + avgDeaths: 5.8, + avgAssists: 8.1, + avgCs: 142, + mostPlayedChampionIds: ['LeeSin', 'Viego', 'Rengar'], + }, + }, + { + key: 'topsol', + gameName: '탑솔장인', + tagLine: 'KR1', + kakaoTalkNickname: '탑솔장인', + profileIconId: 5450, + main: 'TOP', + sub: 'JGL', + tier: { + tier: 'EMERALD', + rank: 'II', + leaguePoints: 46, + wins: 57, + losses: 44, + }, + flex: { + tier: 'PLATINUM', + rank: 'II', + leaguePoints: 34, + wins: 21, + losses: 19, + }, + masteries: [ + { championId: 'Jax', championName: '잭스', level: 7, points: 145600 }, + { championId: 'Yorick', championName: '요릭', level: 7, points: 112400 }, + { championId: 'Nasus', championName: '나서스', level: 6, points: 89300 }, + ], + recentStatsSummary: { + games: 47, + wins: 27, + losses: 20, + avgKills: 5.6, + avgDeaths: 3.9, + avgAssists: 4.1, + avgCs: 201, + mostPlayedChampionIds: ['Jax', 'Yorick', 'Nasus'], + }, + }, + { + key: 'supporter', + gameName: '서폿장인', + tagLine: '0001', + kakaoTalkNickname: '서폿장인', + profileIconId: 4900, + main: 'SUP', + sub: 'ADC', + tier: { + tier: 'DIAMOND', + rank: 'IV', + leaguePoints: 9, + wins: 64, + losses: 61, + }, + flex: { + tier: 'DIAMOND', + rank: 'III', + leaguePoints: 25, + wins: 17, + losses: 14, + }, + masteries: [ + { championId: 'Yuumi', championName: '유미', level: 7, points: 198700 }, + { championId: 'Sona', championName: '소나', level: 7, points: 145200 }, + { championId: 'Nami', championName: '나미', level: 6, points: 92100 }, + ], + recentStatsSummary: { + games: 52, + wins: 30, + losses: 22, + avgKills: 1.8, + avgDeaths: 4.2, + avgAssists: 16.3, + avgCs: 25, + mostPlayedChampionIds: ['Yuumi', 'Sona', 'Nami'], + }, + }, +]; + +function createPreferences( + main: Position, + sub: Position, +): PositionPreference[] { + const rest = (['TOP', 'JGL', 'MID', 'ADC', 'SUP'] as Position[]).filter( + (position) => position !== main && position !== sub, + ); + + return [ + { position: main, priority: 1 }, + { position: sub, priority: 2 }, + ...rest.map((position, index) => ({ + position, + priority: index + 3, + })), + ]; +} + +function createTier( + puuid: string, + queueType: string, + tier: string, + rank: string, + leaguePoints: number, + wins: number, + losses: number, +): TierInfo { + return { + leagueId: `dev-${puuid}-${queueType}`, + queueType, + tier, + rank: rank || 'I', + puuid, + leaguePoints, + wins, + losses, + fetchedAt: NOW, + }; +} + +function selectPrimaryTier(tiers: TierInfo[]) { + return tiers.find((tier) => tier.queueType === 'RANKED_SOLO_5x5') ?? tiers[0]; +} + +function createRiotAccount(player: SeedPlayer) { + const puuid = `dev-seed-${player.key}-puuid`; + const tiers = [ + createTier( + puuid, + 'RANKED_SOLO_5x5', + player.tier.tier, + player.tier.rank, + player.tier.leaguePoints, + player.tier.wins, + player.tier.losses, + ), + ]; + + if (player.flex) { + tiers.push( + createTier( + puuid, + 'RANKED_FLEX_SR', + player.flex.tier, + player.flex.rank, + player.flex.leaguePoints, + player.flex.wins, + player.flex.losses, + ), + ); + } + + return { + puuid, + gameName: player.gameName, + tagLine: player.tagLine, + profileIconId: player.profileIconId, + revisionDate: Date.now(), + summonerLevel: 200, + isPrimary: true, + tiers, + tierHistory: [], + matchIds: [], + recentStatsSummary: createRecentStatsSummary( + player.recentStatsSummary, + player.main, + ), + recentStatsFetchedAt: NOW, + championMasteries: createChampionMasteries(puuid, player.masteries), + championMasteriesFetchedAt: NOW, + championRecords: {}, + championRecordsFetchedAt: NOW, + createdAt: NOW, + updatedAt: NOW, + }; +} + +function createStaffRiotAccount( + key: string, + gameName: string, + tagLine: string, +) { + const puuid = `dev-seed-${key}-puuid`; + return { + puuid, + gameName, + tagLine, + profileIconId: 29, + revisionDate: Date.now(), + summonerLevel: 120, + isPrimary: true, + tiers: [createTier(puuid, 'RANKED_SOLO_5x5', 'GOLD', 'I', 75, 24, 19)], + tierHistory: [], + matchIds: [], + recentStatsSummary: createRecentStatsSummary( + { + games: 12, + wins: 7, + losses: 5, + avgKills: 5.1, + avgDeaths: 4.3, + avgAssists: 7.4, + avgCs: 167, + mostPlayedChampionIds: ['Orianna', 'JarvanIV'], + }, + 'MID', + ), + recentStatsFetchedAt: NOW, + championMasteries: createChampionMasteries(puuid, [ + { + championId: 'Orianna', + championName: '오리아나', + level: 5, + points: 18300, + }, + { + championId: 'JarvanIV', + championName: '자르반 4세', + level: 5, + points: 12600, + }, + ]), + championMasteriesFetchedAt: NOW, + championRecords: {}, + championRecordsFetchedAt: NOW, + createdAt: NOW, + updatedAt: NOW, + }; +} + +function createChampionMasteries( + puuid: string, + masteries: SeedChampionMastery[], +): ChampionMasteryEntry[] { + return masteries.map((mastery) => ({ + puuid, + championId: CHAMPION_IDS[mastery.championId] ?? 0, + championLevel: mastery.level, + championPoints: mastery.points, + })); +} + +function createRecentStatsSummary( + input: SeedRecentStatsSummary, + mainPosition: Position, +): RiotRecentStatsSummary { + const lane = POSITION_TO_RIOT_LANE[mainPosition]; + const championIds = input.mostPlayedChampionIds.map( + (championId) => CHAMPION_IDS[championId] ?? 0, + ); + const laneStats = { + games: input.games, + wins: input.wins, + losses: input.losses, + avgKills: input.avgKills, + avgDeaths: input.avgDeaths, + avgAssists: input.avgAssists, + avgCs: input.avgCs, + avgCsPerMin: + input.avgCsPerMin ?? Math.round((input.avgCs / 28) * 10) / 10, + mostPlayedChampionIds: championIds, + }; + + return { + overall: laneStats, + byLane: { + [lane]: laneStats, + }, + }; +} + +function toMatchParticipant(user: { + _id: mongoose.Types.ObjectId; + riotAccounts: Array<{ + puuid: string; + gameName: string; + tagLine: string; + profileIconId: number; + tiers: TierInfo[]; + }>; + preferredPositions: PositionPreference[]; +}): MatchParticipant { + const primary = user.riotAccounts[0]; + + return { + userId: user._id, + puuid: primary?.puuid, + gameName: primary?.gameName, + tagLine: primary?.tagLine, + profileIconId: primary?.profileIconId, + tier: primary ? selectPrimaryTier(primary.tiers) : undefined, + preferredPositions: user.preferredPositions, + joinedAt: NOW, + }; +} + +async function main() { + await loadMachineEnvFile(); + + const app = await NestFactory.createApplicationContext(SeedModule, { + logger: ['error', 'warn', 'log'], + }); + + try { + const connectionService = app.get(ConnectionService); + const CommunityModel = await connectionService.getModel('community'); + const UserModel = await connectionService.getModel('user'); + const MatchModel = await connectionService.getModel('match'); + const AuctionModel = await connectionService.getModel('auction'); + + const existingCommunity = await CommunityModel.findOne({ + name: DEV_COMMUNITY_NAME, + }).exec(); + + if (existingCommunity) { + const existingMatches = await MatchModel.find({ + communityId: existingCommunity._id, + }) + .select('_id') + .lean() + .exec(); + + const matchIds = existingMatches.map((match) => match._id); + if (matchIds.length > 0) { + await AuctionModel.deleteMany({ matchId: { $in: matchIds } }).exec(); + } + + await MatchModel.deleteMany({ + communityId: existingCommunity._id, + }).exec(); + await UserModel.deleteMany({ communityId: existingCommunity._id }).exec(); + await CommunityModel.deleteOne({ _id: existingCommunity._id }).exec(); + } + + const communityId = new mongoose.Types.ObjectId(); + const ownerUserId = new mongoose.Types.ObjectId(); + const adminUserId = new mongoose.Types.ObjectId(); + + await CommunityModel.create({ + _id: communityId, + name: DEV_COMMUNITY_NAME, + description: DEV_COMMUNITY_DESCRIPTION, + ownerUserId, + riotPlatform: 'kr', + riotRegion: 'asia', + }); + + const owner = { + _id: ownerUserId, + communityId, + role: 'owner' as const, + kakaoTalkId: 'dev-owner', + kakaoTalkNickname: 'DevOwner', + discordId: 'dev-owner-discord', + discordNickname: 'DevOwner', + riotAccounts: [createStaffRiotAccount('owner', 'DevOwner', 'KR1')], + preferredPositions: createPreferences('MID', 'SUP'), + isActivated: true, + }; + + const admin = { + _id: adminUserId, + communityId, + role: 'admin' as const, + kakaoTalkId: 'dev-admin', + kakaoTalkNickname: 'DevAdmin', + discordId: 'dev-admin-discord', + discordNickname: 'DevAdmin', + riotAccounts: [createStaffRiotAccount('admin', 'DevAdmin', 'KR1')], + preferredPositions: createPreferences('JGL', 'MID'), + isActivated: true, + }; + + const players = PLAYER_SEEDS.map((player) => ({ + _id: new mongoose.Types.ObjectId(), + communityId, + role: 'member' as const, + kakaoTalkId: `seed-${player.key}`, + kakaoTalkNickname: player.kakaoTalkNickname, + discordId: `seed-${player.key}-discord`, + discordNickname: player.gameName, + riotAccounts: [createRiotAccount(player)], + preferredPositions: createPreferences(player.main, player.sub), + isActivated: true, + })); + + await UserModel.insertMany([owner, admin, ...players], { ordered: true }); + + const recruitingPlayers = players.slice(0, 6); + const auctionPlayers = players; + const finishedBlue = [ + { user: players[0], assignedPosition: 'MID' as const, cost: 0 }, + { user: players[2], assignedPosition: 'TOP' as const, cost: 320 }, + { user: players[4], assignedPosition: 'ADC' as const, cost: 280 }, + { user: players[7], assignedPosition: 'JGL' as const, cost: 190 }, + { user: players[9], assignedPosition: 'SUP' as const, cost: 210 }, + ]; + const finishedRed = [ + { user: players[1], assignedPosition: 'JGL' as const, cost: 0 }, + { user: players[3], assignedPosition: 'SUP' as const, cost: 240 }, + { user: players[5], assignedPosition: 'MID' as const, cost: 250 }, + { user: players[6], assignedPosition: 'ADC' as const, cost: 300 }, + { user: players[8], assignedPosition: 'TOP' as const, cost: 220 }, + ]; + + const recruitingMatchId = new mongoose.Types.ObjectId(); + const auctionMatchId = new mongoose.Types.ObjectId(); + const finishedMatchId = new mongoose.Types.ObjectId(); + + await MatchModel.insertMany([ + { + _id: recruitingMatchId, + communityId, + hostUserId: ownerUserId, + title: '쌀먹 내전', + description: '통합 테스트용 모집 중 매치입니다.', + mapId: 11, + status: 'recruiting', + scheduledAt: new Date('2026-04-27T12:00:00.000Z'), + maxParticipants: 10, + participants: recruitingPlayers.map(toMatchParticipant), + teams: [], + prizes: ['5명 추첨 커피', 'MVP: 스킨 선물'], + notices: [ + '시작 10분 전까지 커스텀 방에 입장해주세요.', + '개발용 시드 데이터입니다.', + ], + schedule: [ + { time: '20:50', label: '로비 오픈' }, + { time: '21:00', label: '내전 시작' }, + ], + }, + { + _id: auctionMatchId, + communityId, + hostUserId: ownerUserId, + title: '롤림푸스 경매 테스트 매치', + description: 'Socket.IO 경매 페이지 검증용으로 생성된 매치입니다.', + mapId: 11, + status: 'team-built', + scheduledAt: new Date('2026-04-26T11:00:00.000Z'), + maxParticipants: 10, + participants: auctionPlayers.map(toMatchParticipant), + teams: [ + { + side: 'blue', + name: '블루팀', + captainUserId: players[0]._id, + members: [ + { + userId: players[0]._id, + assignedPosition: 'MID', + cost: 0, + }, + ], + }, + { + side: 'red', + name: '레드팀', + captainUserId: players[1]._id, + members: [ + { + userId: players[1]._id, + assignedPosition: 'JGL', + cost: 0, + }, + ], + }, + ], + prizes: ['우승팀 햄버거 세트'], + notices: ['현재 경매 진행 중인 테스트 매치입니다.'], + schedule: [ + { time: '19:30', label: '디스코드 집합' }, + { time: '19:45', label: '경매 시작' }, + ], + }, + { + _id: finishedMatchId, + communityId, + hostUserId: ownerUserId, + title: '시즌 4 준결승', + description: '완료된 매치 UI 확인용 더미 경기 결과입니다.', + mapId: 11, + status: 'finished', + scheduledAt: new Date('2026-04-20T11:00:00.000Z'), + maxParticipants: 10, + participants: players.map(toMatchParticipant), + teams: [ + { + side: 'blue', + name: '블루팀', + captainUserId: players[0]._id, + members: finishedBlue.map((member) => ({ + userId: member.user._id, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + }, + { + side: 'red', + name: '레드팀', + captainUserId: players[1]._id, + members: finishedRed.map((member) => ({ + userId: member.user._id, + assignedPosition: member.assignedPosition, + cost: member.cost, + })), + }, + ], + result: { + winnerSide: 'blue', + blueScore: 2, + redScore: 1, + mvpUserId: players[0]._id, + riotMatchIds: ['KR_DEV_0001', 'KR_DEV_0002', 'KR_DEV_0003'], + }, + prizes: ['1등 팀: RP 10,000 지급', 'MVP: 프리리'], + notices: [], + schedule: [], + }, + ]); + + const auctionOrder = auctionPlayers.slice(2).map((player) => { + const primary = player.riotAccounts[0]; + + return { + userId: player._id, + puuid: primary.puuid, + gameName: primary.gameName, + tagLine: primary.tagLine, + profileIconId: primary.profileIconId, + preferredPositions: player.preferredPositions, + tiers: primary.tiers, + masteries: primary.championMasteries, + recentStatsSummary: primary.recentStatsSummary, + }; + }); + + await AuctionModel.create({ + matchId: auctionMatchId, + phase: 'presenting', + teams: [ + { + side: 'blue', + captainUserId: players[0]._id, + points: 1000, + members: [], + }, + { + side: 'red', + captainUserId: players[1]._id, + points: 1000, + members: [], + }, + ], + order: auctionOrder, + currentIndex: 0, + bids: [], + currentBid: 0, + maxTimerSeconds: 30, + initialPoints: 1000, + startedAt: NOW, + }); + + const summary = { + communityId: communityId.toString(), + ownerUserId: ownerUserId.toString(), + adminUserId: adminUserId.toString(), + recruitingMatchId: recruitingMatchId.toString(), + auctionMatchId: auctionMatchId.toString(), + finishedMatchId: finishedMatchId.toString(), + playerUserIds: players.map((player) => ({ + userId: player._id.toString(), + gameName: player.riotAccounts[0].gameName, + })), + }; + + console.log('\n[seed:dev] Dev seed completed.\n'); + console.log(JSON.stringify(summary, null, 2)); + console.log( + `\napps/web/.env.development 에 아래 값을 넣으면 됩니다:\nVITE_DEFAULT_COMMUNITY_ID=${summary.communityId}\n`, + ); + } finally { + await app.close(); + } +} + +void main().catch((error: unknown) => { + console.error('\n[seed:dev] Failed to seed database.\n'); + console.error(error); + process.exitCode = 1; +}); diff --git a/apps/api/start.ps1 b/apps/api/start.ps1 new file mode 100644 index 00000000..20e3329c --- /dev/null +++ b/apps/api/start.ps1 @@ -0,0 +1,68 @@ +param( + [switch]$UsePm2, + [string]$Pm2Name = "lolympus-tournament-support" +) + +if (-not $env:NODE_ENV) { + $env:NODE_ENV = "dev" +} + +$MainScript = Join-Path $PSScriptRoot "dist/main.js" + +if ($isMacOS -or $isLinux) { + $env:MachineEnvFile = "$env:HOME/source/global-env-vars.txt" +} elseif ($isWindows) { + $env:MachineEnvFile = "$env:USERPROFILE/source/global-env-vars.txt" +} + +function Set-EnvFromFile { + param([string]$Path) + + if (-not (Test-Path $Path)) { + throw "File not found: $Path" + } + + foreach ($line in Get-Content $Path) { + if ([string]::IsNullOrWhiteSpace($line)) { continue } + if ($line -match '^\s*#') { continue } + + if ($line -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$') { + $key = $matches[1] + $value = $matches[2].Trim() + + if ( + ($value.StartsWith('"') -and $value.EndsWith('"')) -or + ($value.StartsWith("'") -and $value.EndsWith("'")) + ) { + $value = $value.Substring(1, $value.Length - 2) + } + + [System.Environment]::SetEnvironmentVariable($key, $value) + } + } +} + +if (Test-Path $env:MachineEnvFile) { + Set-EnvFromFile $env:MachineEnvFile +} + +if (-not $env:INFISICAL_CLIENT_ID) { + Write-Error "INFISICAL_CLIENT_ID is not set." + exit 1 +} + +if (-not $env:INFISICAL_CLIENT_SECRET) { + Write-Error "INFISICAL_CLIENT_SECRET is not set." + exit 1 +} + +if (-not $env:INFISICAL_PROJECT_ID) { + Write-Error "INFISICAL_PROJECT_ID is not set." + exit 1 +} + +if ($UsePm2) { + pm2 start $MainScript --name $Pm2Name --update-env +} else { + node $MainScript +} diff --git a/apps/api/test/app.e2e-spec.ts b/apps/api/test/app.e2e-spec.ts new file mode 100644 index 00000000..a767839c --- /dev/null +++ b/apps/api/test/app.e2e-spec.ts @@ -0,0 +1,29 @@ +import { Test, TestingModule } from '@nestjs/testing'; +import { INestApplication } from '@nestjs/common'; +import request from 'supertest'; +import { App } from 'supertest/types'; +import { AppModule } from './../src/app.module'; + +describe('AppController (e2e)', () => { + let app: INestApplication; + + beforeEach(async () => { + const moduleFixture: TestingModule = await Test.createTestingModule({ + imports: [AppModule], + }).compile(); + + app = moduleFixture.createNestApplication(); + await app.init(); + }); + + it('/ (GET)', () => { + return request(app.getHttpServer()) + .get('/') + .expect(200) + .expect('Hello World!'); + }); + + afterEach(async () => { + await app.close(); + }); +}); diff --git a/apps/api/test/jest-e2e.json b/apps/api/test/jest-e2e.json new file mode 100644 index 00000000..e9d912f3 --- /dev/null +++ b/apps/api/test/jest-e2e.json @@ -0,0 +1,9 @@ +{ + "moduleFileExtensions": ["js", "json", "ts"], + "rootDir": ".", + "testEnvironment": "node", + "testRegex": ".e2e-spec.ts$", + "transform": { + "^.+\\.(t|j)s$": "ts-jest" + } +} diff --git a/apps/api/tsconfig.build.json b/apps/api/tsconfig.build.json new file mode 100644 index 00000000..64f86c6b --- /dev/null +++ b/apps/api/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] +} diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json new file mode 100644 index 00000000..aba29b0e --- /dev/null +++ b/apps/api/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "nodenext", + "moduleResolution": "nodenext", + "resolvePackageJsonExports": true, + "esModuleInterop": true, + "isolatedModules": true, + "declaration": true, + "removeComments": true, + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "allowSyntheticDefaultImports": true, + "target": "ES2023", + "sourceMap": true, + "outDir": "./dist", + "baseUrl": "./", + "incremental": true, + "skipLibCheck": true, + "strictNullChecks": true, + "forceConsistentCasingInFileNames": true, + "noImplicitAny": false, + "strictBindCallApply": false, + "noFallthroughCasesInSwitch": false + } +}