From 80fef25af368558edb0baa2152d491c19fc14f0b Mon Sep 17 00:00:00 2001 From: Park Dahyeon Date: Sat, 18 Jul 2026 05:21:49 +0000 Subject: [PATCH 1/3] chore: upgrade runtime to Node.js 26 --- .nvmrc | 1 + Dockerfile | 4 +- apps/api/package.json | 4 +- apps/web/package.json | 2 +- package.json | 3 + pnpm-lock.yaml | 312 +++++++++++++++++++++--------------------- 6 files changed, 165 insertions(+), 161 deletions(-) create mode 100644 .nvmrc diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 00000000..6f4247a6 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +26 diff --git a/Dockerfile b/Dockerfile index 315f68e4..092839d8 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,11 +1,11 @@ # syntax=docker/dockerfile:1.7 -FROM node:24-bookworm-slim AS pnpm-base +FROM node:26-bookworm-slim AS pnpm-base ENV PNPM_HOME=/pnpm ENV PATH="${PNPM_HOME}:${PATH}" -RUN corepack enable +RUN npm install --global pnpm@10.4.1 WORKDIR /app diff --git a/apps/api/package.json b/apps/api/package.json index 05377cc8..c79f569c 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -42,7 +42,7 @@ "jose": "^6.2.2", "mongoose": "^9.4.1", "nats": "^2.29.3", - "newrelic": "^14.1.2", + "newrelic": "^14.3.0", "redis": "^5.12.1", "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", @@ -57,7 +57,7 @@ "@nestjs/testing": "^11.0.1", "@types/express": "^5.0.0", "@types/jest": "^30.0.0", - "@types/node": "^24.0.0", + "@types/node": "^26.1.1", "@types/supertest": "^7.0.0", "eslint": "^9.18.0", "eslint-config-prettier": "^10.0.1", diff --git a/apps/web/package.json b/apps/web/package.json index 881c1aec..d722e693 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -34,7 +34,7 @@ "devDependencies": { "@eslint/js": "^9.39.4", "@tailwindcss/vite": "^4.2.2", - "@types/node": "^24.12.2", + "@types/node": "^26.1.1", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.1", diff --git a/package.json b/package.json index bf58342c..6cbb3e35 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,9 @@ "keywords": [], "author": "", "license": "LGPL-2.0", + "engines": { + "node": ">=26 <27" + }, "packageManager": "pnpm@10.4.1", "dependencies": { "@infisical/sdk": "^5.0.0" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1ed14ecf..9348a1a1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -57,8 +57,8 @@ importers: specifier: ^2.29.3 version: 2.29.3 newrelic: - specifier: ^14.1.2 - version: 14.1.2 + specifier: ^14.3.0 + version: 14.3.0 redis: specifier: ^5.12.1 version: 5.12.1(@opentelemetry/api@1.9.1) @@ -83,7 +83,7 @@ importers: version: 9.39.4 '@nestjs/cli': specifier: ^11.0.0 - version: 11.0.19(@types/node@24.12.2) + version: 11.0.19(@types/node@26.1.1) '@nestjs/schematics': specifier: ^11.0.0 version: 11.0.10(chokidar@4.0.3)(typescript@5.9.3) @@ -97,8 +97,8 @@ importers: specifier: ^30.0.0 version: 30.0.0 '@types/node': - specifier: ^24.0.0 - version: 24.12.2 + specifier: ^26.1.1 + version: 26.1.1 '@types/supertest': specifier: ^7.0.0 version: 7.2.0 @@ -116,7 +116,7 @@ importers: version: 17.4.0 jest: specifier: ^30.0.0 - version: 30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)) + version: 30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)) prettier: specifier: ^3.4.2 version: 3.8.2 @@ -128,13 +128,13 @@ importers: version: 7.2.2 ts-jest: specifier: ^29.2.5 - version: 29.4.9(@babel/core@7.29.0)(@jest/transform@30.3.0)(@jest/types@30.3.0)(babel-jest@30.3.0(@babel/core@7.29.0))(jest-util@30.3.0)(jest@30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)))(typescript@5.9.3) + version: 29.4.9(@babel/core@7.29.0)(@jest/transform@30.3.0)(@jest/types@30.3.0)(babel-jest@30.3.0(@babel/core@7.29.0))(jest-util@30.3.0)(jest@30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)))(typescript@5.9.3) ts-loader: specifier: ^9.5.2 version: 9.5.7(typescript@5.9.3)(webpack@5.106.0) ts-node: specifier: ^10.9.2 - version: 10.9.2(@types/node@24.12.2)(typescript@5.9.3) + version: 10.9.2(@types/node@26.1.1)(typescript@5.9.3) tsconfig-paths: specifier: ^4.2.0 version: 4.2.0 @@ -186,10 +186,10 @@ importers: version: 9.39.4 '@tailwindcss/vite': specifier: ^4.2.2 - version: 4.2.2(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1)) + version: 4.2.2(vite@8.0.8(@types/node@26.1.1)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1)) '@types/node': - specifier: ^24.12.2 - version: 24.12.2 + specifier: ^26.1.1 + version: 26.1.1 '@types/react': specifier: ^19.2.14 version: 19.2.14 @@ -198,7 +198,7 @@ importers: version: 19.2.3(@types/react@19.2.14) '@vitejs/plugin-react': specifier: ^6.0.1 - version: 6.0.1(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1)) + version: 6.0.1(vite@8.0.8(@types/node@26.1.1)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1)) daisyui: specifier: ^5.5.19 version: 5.5.19 @@ -225,7 +225,7 @@ importers: version: 8.58.1(eslint@9.39.4(jiti@2.6.1))(typescript@6.0.2) vite: specifier: ^8.0.4 - version: 8.0.8(@types/node@24.12.2)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1) + version: 8.0.8(@types/node@26.1.1)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1) wrangler: specifier: ^4.85.0 version: 4.85.0 @@ -1423,12 +1423,12 @@ packages: resolution: {integrity: sha512-tEylXfM5kNXpJAD+ckC7uX759/liWw7d9eEqXN2nO+r/PVCVAYoFwjRFzkYwhtcu6jMaI+La1aDaurgHPzprmg==} engines: {node: '>=12.17.0 < 13.0.0 || >=13.7.0'} - '@newrelic/fn-inspect@5.0.0': - resolution: {integrity: sha512-X/NciddM5AQ17JggcrmN230wlM/P+5j2fLos+m7pj0u1fiQK8F4Kru4qkNq7YRT/RhjYDSvy79KR80EYNhzVaw==} + '@newrelic/fn-inspect@5.1.0': + resolution: {integrity: sha512-2ogTrZYTSr/hTh+kMIzzSOIGoary2MqUFxDV9abC2kBY3renTfTWMHM0dUkenBNFtjtQDyARDVwVqsdbbJSbSw==} engines: {node: '>=22'} - '@newrelic/native-metrics@13.0.0': - resolution: {integrity: sha512-xtCzhiY6rLFseV5GfEEra0rGe8jyBzFl0DoqfYbjgIfmI/6h3O3z0KMKfuk2Xb2KINiXWRtKHYpfxwD4AWXoWA==} + '@newrelic/native-metrics@13.1.0': + resolution: {integrity: sha512-MoBcOr3FmO7CUOLafnN9D8FGbpSYz2RTXk/yhXPm6lNkNge+IFgSGMowImYm8oYe20m3PN1Dv+bGqEhJ7UI+7g==} engines: {node: '>=22', npm: '>=6'} '@newrelic/rrdom@1.1.2': @@ -2126,8 +2126,8 @@ packages: '@types/methods@1.1.4': resolution: {integrity: sha512-ymXWVrDiCxTBE3+RIrrP533E70eA+9qu7zdWoHuOmGujkYtzf4HQF96b8nwHLqhuf4ykX61IGRIB38CC6/sImQ==} - '@types/node@24.12.2': - resolution: {integrity: sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==} + '@types/node@26.1.1': + resolution: {integrity: sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==} '@types/qs@6.15.0': resolution: {integrity: sha512-JawvT8iBVWpzTrz3EGw9BTQFg3BQNmwERdKE22vlTxawwtbyUSlMppvZYKLZzB5zgACXdXxbD3m1bXaMqP/9ow==} @@ -4100,8 +4100,8 @@ packages: neo-async@2.6.2: resolution: {integrity: sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==} - newrelic@14.1.2: - resolution: {integrity: sha512-RYEIchr5bd7sJ6r6XE/GQQ7aXq9pTcqXulmN5Z7wCLqulXAGKZpHDbfWs0MxGixTHj3Xnm+YY5C4XhhmrnHWUg==} + newrelic@14.3.0: + resolution: {integrity: sha512-VpXJVKsOqjBwZCaGWYEC2E+T3mu6zq7qglNe5t/9y2uIeMdRls1PygdLF3pKBYjelxLATiTUFhJT1bmmupyadA==} engines: {node: '>=22', npm: '>=6.0.0'} hasBin: true @@ -4897,8 +4897,8 @@ packages: resolution: {integrity: sha512-rvKSBiC5zqCCiDZ9kAOszZcDvdAHwwIKJG33Ykj43OKcWsnmcBRL09YTU4nOeHZ8Y2a7l1MgTd08SBe9A8Qj6A==} engines: {node: '>=18'} - undici-types@7.16.0: - resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} + undici-types@8.3.0: + resolution: {integrity: sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==} undici@7.24.8: resolution: {integrity: sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==} @@ -5193,11 +5193,11 @@ snapshots: optionalDependencies: chokidar: 4.0.3 - '@angular-devkit/schematics-cli@19.2.24(@types/node@24.12.2)(chokidar@4.0.3)': + '@angular-devkit/schematics-cli@19.2.24(@types/node@26.1.1)(chokidar@4.0.3)': dependencies: '@angular-devkit/core': 19.2.24(chokidar@4.0.3) '@angular-devkit/schematics': 19.2.24(chokidar@4.0.3) - '@inquirer/prompts': 7.3.2(@types/node@24.12.2) + '@inquirer/prompts': 7.3.2(@types/node@26.1.1) ansi-colors: 4.1.3 symbol-observable: 4.0.0 yargs-parser: 21.1.1 @@ -6169,143 +6169,143 @@ snapshots: '@inquirer/ansi@1.0.2': {} - '@inquirer/checkbox@4.3.2(@types/node@24.12.2)': + '@inquirer/checkbox@4.3.2(@types/node@26.1.1)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/type': 3.0.10(@types/node@26.1.1) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/confirm@5.1.21(@types/node@24.12.2)': + '@inquirer/confirm@5.1.21(@types/node@26.1.1)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.12.2) - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) + '@inquirer/type': 3.0.10(@types/node@26.1.1) optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/core@10.3.2(@types/node@24.12.2)': + '@inquirer/core@10.3.2(@types/node@26.1.1)': dependencies: '@inquirer/ansi': 1.0.2 '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/type': 3.0.10(@types/node@26.1.1) cli-width: 4.1.0 mute-stream: 2.0.0 signal-exit: 4.1.0 wrap-ansi: 6.2.0 yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/editor@4.2.23(@types/node@24.12.2)': + '@inquirer/editor@4.2.23(@types/node@26.1.1)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.12.2) - '@inquirer/external-editor': 1.0.3(@types/node@24.12.2) - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) + '@inquirer/external-editor': 1.0.3(@types/node@26.1.1) + '@inquirer/type': 3.0.10(@types/node@26.1.1) optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/expand@4.0.23(@types/node@24.12.2)': + '@inquirer/expand@4.0.23(@types/node@26.1.1)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.12.2) - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) + '@inquirer/type': 3.0.10(@types/node@26.1.1) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/external-editor@1.0.3(@types/node@24.12.2)': + '@inquirer/external-editor@1.0.3(@types/node@26.1.1)': dependencies: chardet: 2.1.1 iconv-lite: 0.7.2 optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@inquirer/figures@1.0.15': {} - '@inquirer/input@4.3.1(@types/node@24.12.2)': + '@inquirer/input@4.3.1(@types/node@26.1.1)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.12.2) - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) + '@inquirer/type': 3.0.10(@types/node@26.1.1) optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/number@3.0.23(@types/node@24.12.2)': + '@inquirer/number@3.0.23(@types/node@26.1.1)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.12.2) - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) + '@inquirer/type': 3.0.10(@types/node@26.1.1) optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/password@4.0.23(@types/node@24.12.2)': + '@inquirer/password@4.0.23(@types/node@26.1.1)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@24.12.2) - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) + '@inquirer/type': 3.0.10(@types/node@26.1.1) optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/prompts@7.10.1(@types/node@24.12.2)': + '@inquirer/prompts@7.10.1(@types/node@26.1.1)': dependencies: - '@inquirer/checkbox': 4.3.2(@types/node@24.12.2) - '@inquirer/confirm': 5.1.21(@types/node@24.12.2) - '@inquirer/editor': 4.2.23(@types/node@24.12.2) - '@inquirer/expand': 4.0.23(@types/node@24.12.2) - '@inquirer/input': 4.3.1(@types/node@24.12.2) - '@inquirer/number': 3.0.23(@types/node@24.12.2) - '@inquirer/password': 4.0.23(@types/node@24.12.2) - '@inquirer/rawlist': 4.1.11(@types/node@24.12.2) - '@inquirer/search': 3.2.2(@types/node@24.12.2) - '@inquirer/select': 4.4.2(@types/node@24.12.2) + '@inquirer/checkbox': 4.3.2(@types/node@26.1.1) + '@inquirer/confirm': 5.1.21(@types/node@26.1.1) + '@inquirer/editor': 4.2.23(@types/node@26.1.1) + '@inquirer/expand': 4.0.23(@types/node@26.1.1) + '@inquirer/input': 4.3.1(@types/node@26.1.1) + '@inquirer/number': 3.0.23(@types/node@26.1.1) + '@inquirer/password': 4.0.23(@types/node@26.1.1) + '@inquirer/rawlist': 4.1.11(@types/node@26.1.1) + '@inquirer/search': 3.2.2(@types/node@26.1.1) + '@inquirer/select': 4.4.2(@types/node@26.1.1) optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/prompts@7.3.2(@types/node@24.12.2)': + '@inquirer/prompts@7.3.2(@types/node@26.1.1)': dependencies: - '@inquirer/checkbox': 4.3.2(@types/node@24.12.2) - '@inquirer/confirm': 5.1.21(@types/node@24.12.2) - '@inquirer/editor': 4.2.23(@types/node@24.12.2) - '@inquirer/expand': 4.0.23(@types/node@24.12.2) - '@inquirer/input': 4.3.1(@types/node@24.12.2) - '@inquirer/number': 3.0.23(@types/node@24.12.2) - '@inquirer/password': 4.0.23(@types/node@24.12.2) - '@inquirer/rawlist': 4.1.11(@types/node@24.12.2) - '@inquirer/search': 3.2.2(@types/node@24.12.2) - '@inquirer/select': 4.4.2(@types/node@24.12.2) + '@inquirer/checkbox': 4.3.2(@types/node@26.1.1) + '@inquirer/confirm': 5.1.21(@types/node@26.1.1) + '@inquirer/editor': 4.2.23(@types/node@26.1.1) + '@inquirer/expand': 4.0.23(@types/node@26.1.1) + '@inquirer/input': 4.3.1(@types/node@26.1.1) + '@inquirer/number': 3.0.23(@types/node@26.1.1) + '@inquirer/password': 4.0.23(@types/node@26.1.1) + '@inquirer/rawlist': 4.1.11(@types/node@26.1.1) + '@inquirer/search': 3.2.2(@types/node@26.1.1) + '@inquirer/select': 4.4.2(@types/node@26.1.1) optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/rawlist@4.1.11(@types/node@24.12.2)': + '@inquirer/rawlist@4.1.11(@types/node@26.1.1)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.12.2) - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) + '@inquirer/type': 3.0.10(@types/node@26.1.1) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/search@3.2.2(@types/node@24.12.2)': + '@inquirer/search@3.2.2(@types/node@26.1.1)': dependencies: - '@inquirer/core': 10.3.2(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/type': 3.0.10(@types/node@26.1.1) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/select@4.4.2(@types/node@24.12.2)': + '@inquirer/select@4.4.2(@types/node@26.1.1)': dependencies: '@inquirer/ansi': 1.0.2 - '@inquirer/core': 10.3.2(@types/node@24.12.2) + '@inquirer/core': 10.3.2(@types/node@26.1.1) '@inquirer/figures': 1.0.15 - '@inquirer/type': 3.0.10(@types/node@24.12.2) + '@inquirer/type': 3.0.10(@types/node@26.1.1) yoctocolors-cjs: 2.1.3 optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 - '@inquirer/type@3.0.10(@types/node@24.12.2)': + '@inquirer/type@3.0.10(@types/node@26.1.1)': optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@isaacs/cliui@8.0.2': dependencies: @@ -6329,13 +6329,13 @@ snapshots: '@jest/console@30.3.0': dependencies: '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 chalk: 4.1.2 jest-message-util: 30.3.0 jest-util: 30.3.0 slash: 3.0.0 - '@jest/core@30.3.0(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3))': + '@jest/core@30.3.0(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3))': dependencies: '@jest/console': 30.3.0 '@jest/pattern': 30.0.1 @@ -6343,14 +6343,14 @@ snapshots: '@jest/test-result': 30.3.0 '@jest/transform': 30.3.0 '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 ansi-escapes: 4.3.2 chalk: 4.1.2 ci-info: 4.4.0 exit-x: 0.2.2 graceful-fs: 4.2.11 jest-changed-files: 30.3.0 - jest-config: 30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)) + jest-config: 30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)) jest-haste-map: 30.3.0 jest-message-util: 30.3.0 jest-regex-util: 30.0.1 @@ -6376,7 +6376,7 @@ snapshots: dependencies: '@jest/fake-timers': 30.3.0 '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 jest-mock: 30.3.0 '@jest/expect-utils@30.3.0': @@ -6394,7 +6394,7 @@ snapshots: dependencies: '@jest/types': 30.3.0 '@sinonjs/fake-timers': 15.3.1 - '@types/node': 24.12.2 + '@types/node': 26.1.1 jest-message-util: 30.3.0 jest-mock: 30.3.0 jest-util: 30.3.0 @@ -6412,7 +6412,7 @@ snapshots: '@jest/pattern@30.0.1': dependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 jest-regex-util: 30.0.1 '@jest/reporters@30.3.0': @@ -6423,7 +6423,7 @@ snapshots: '@jest/transform': 30.3.0 '@jest/types': 30.3.0 '@jridgewell/trace-mapping': 0.3.31 - '@types/node': 24.12.2 + '@types/node': 26.1.1 chalk: 4.1.2 collect-v8-coverage: 1.0.3 exit-x: 0.2.2 @@ -6499,7 +6499,7 @@ snapshots: '@jest/schemas': 30.0.5 '@types/istanbul-lib-coverage': 2.0.6 '@types/istanbul-reports': 3.0.4 - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/yargs': 17.0.35 chalk: 4.1.2 @@ -6556,12 +6556,12 @@ snapshots: '@tybys/wasm-util': 0.10.1 optional: true - '@nestjs/cli@11.0.19(@types/node@24.12.2)': + '@nestjs/cli@11.0.19(@types/node@26.1.1)': dependencies: '@angular-devkit/core': 19.2.24(chokidar@4.0.3) '@angular-devkit/schematics': 19.2.24(chokidar@4.0.3) - '@angular-devkit/schematics-cli': 19.2.24(@types/node@24.12.2)(chokidar@4.0.3) - '@inquirer/prompts': 7.10.1(@types/node@24.12.2) + '@angular-devkit/schematics-cli': 19.2.24(@types/node@26.1.1)(chokidar@4.0.3) + '@inquirer/prompts': 7.10.1(@types/node@26.1.1) '@nestjs/schematics': 11.0.10(chokidar@4.0.3)(typescript@5.9.3) ansis: 4.2.0 chokidar: 4.0.3 @@ -6704,14 +6704,14 @@ snapshots: fflate: 0.8.2 web-vitals: 4.2.4 - '@newrelic/fn-inspect@5.0.0': + '@newrelic/fn-inspect@5.1.0': dependencies: nan: 2.28.0 node-gyp-build: 4.8.4 prebuildify: 6.0.1 optional: true - '@newrelic/native-metrics@13.0.0': + '@newrelic/native-metrics@13.1.0': dependencies: nan: 2.28.0 node-gyp-build: 4.8.4 @@ -7331,12 +7331,12 @@ snapshots: '@tailwindcss/oxide-win32-arm64-msvc': 4.2.2 '@tailwindcss/oxide-win32-x64-msvc': 4.2.2 - '@tailwindcss/vite@4.2.2(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1))': + '@tailwindcss/vite@4.2.2(vite@8.0.8(@types/node@26.1.1)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1))': dependencies: '@tailwindcss/node': 4.2.2 '@tailwindcss/oxide': 4.2.2 tailwindcss: 4.2.2 - vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1) + vite: 8.0.8(@types/node@26.1.1)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1) '@tanstack/query-core@5.100.1': {} @@ -7391,17 +7391,17 @@ snapshots: '@types/body-parser@1.19.6': dependencies: '@types/connect': 3.4.38 - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/connect@3.4.38': dependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/cookiejar@2.1.5': {} '@types/cors@2.8.19': dependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/css-font-loading-module@0.0.7': {} @@ -7443,7 +7443,7 @@ snapshots: '@types/express-serve-static-core@5.1.1': dependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/qs': 6.15.0 '@types/range-parser': 1.2.7 '@types/send': 1.2.1 @@ -7475,9 +7475,9 @@ snapshots: '@types/methods@1.1.4': {} - '@types/node@24.12.2': + '@types/node@26.1.1': dependencies: - undici-types: 7.16.0 + undici-types: 8.3.0 '@types/qs@6.15.0': {} @@ -7493,12 +7493,12 @@ snapshots: '@types/send@1.2.1': dependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/serve-static@2.2.0': dependencies: '@types/http-errors': 2.0.5 - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/stack-utils@2.0.3': {} @@ -7506,7 +7506,7 @@ snapshots: dependencies: '@types/cookiejar': 2.1.5 '@types/methods': 1.1.4 - '@types/node': 24.12.2 + '@types/node': 26.1.1 form-data: 4.0.5 '@types/supertest@7.2.0': @@ -7528,7 +7528,7 @@ snapshots: '@types/ws@8.18.1': dependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/yargs-parser@21.0.3': {} @@ -7769,10 +7769,10 @@ snapshots: '@unrs/resolver-binding-win32-x64-msvc@1.11.1': optional: true - '@vitejs/plugin-react@6.0.1(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1))': + '@vitejs/plugin-react@6.0.1(vite@8.0.8(@types/node@26.1.1)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1))': dependencies: '@rolldown/pluginutils': 1.0.0-rc.7 - vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1) + vite: 8.0.8(@types/node@26.1.1)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1) '@webassemblyjs/ast@1.14.1': dependencies: @@ -8385,7 +8385,7 @@ snapshots: engine.io@6.6.6: dependencies: '@types/cors': 2.8.19 - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@types/ws': 8.18.1 accepts: 1.3.8 base64id: 2.0.0 @@ -9036,7 +9036,7 @@ snapshots: '@jest/expect': 30.3.0 '@jest/test-result': 30.3.0 '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 chalk: 4.1.2 co: 4.6.0 dedent: 1.7.2 @@ -9056,15 +9056,15 @@ snapshots: - babel-plugin-macros - supports-color - jest-cli@30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)): + jest-cli@30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)): dependencies: - '@jest/core': 30.3.0(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)) + '@jest/core': 30.3.0(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)) '@jest/test-result': 30.3.0 '@jest/types': 30.3.0 chalk: 4.1.2 exit-x: 0.2.2 import-local: 3.2.0 - jest-config: 30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)) + jest-config: 30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)) jest-util: 30.3.0 jest-validate: 30.3.0 yargs: 17.7.2 @@ -9075,7 +9075,7 @@ snapshots: - supports-color - ts-node - jest-config@30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)): + jest-config@30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)): dependencies: '@babel/core': 7.29.0 '@jest/get-type': 30.1.0 @@ -9101,8 +9101,8 @@ snapshots: slash: 3.0.0 strip-json-comments: 3.1.1 optionalDependencies: - '@types/node': 24.12.2 - ts-node: 10.9.2(@types/node@24.12.2)(typescript@5.9.3) + '@types/node': 26.1.1 + ts-node: 10.9.2(@types/node@26.1.1)(typescript@5.9.3) transitivePeerDependencies: - babel-plugin-macros - supports-color @@ -9131,7 +9131,7 @@ snapshots: '@jest/environment': 30.3.0 '@jest/fake-timers': 30.3.0 '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 jest-mock: 30.3.0 jest-util: 30.3.0 jest-validate: 30.3.0 @@ -9139,7 +9139,7 @@ snapshots: jest-haste-map@30.3.0: dependencies: '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 anymatch: 3.1.3 fb-watchman: 2.0.2 graceful-fs: 4.2.11 @@ -9178,7 +9178,7 @@ snapshots: jest-mock@30.3.0: dependencies: '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 jest-util: 30.3.0 jest-pnp-resolver@1.2.3(jest-resolve@30.3.0): @@ -9212,7 +9212,7 @@ snapshots: '@jest/test-result': 30.3.0 '@jest/transform': 30.3.0 '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 chalk: 4.1.2 emittery: 0.13.1 exit-x: 0.2.2 @@ -9241,7 +9241,7 @@ snapshots: '@jest/test-result': 30.3.0 '@jest/transform': 30.3.0 '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 chalk: 4.1.2 cjs-module-lexer: 2.2.0 collect-v8-coverage: 1.0.3 @@ -9288,7 +9288,7 @@ snapshots: jest-util@30.3.0: dependencies: '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 chalk: 4.1.2 ci-info: 4.4.0 graceful-fs: 4.2.11 @@ -9307,7 +9307,7 @@ snapshots: dependencies: '@jest/test-result': 30.3.0 '@jest/types': 30.3.0 - '@types/node': 24.12.2 + '@types/node': 26.1.1 ansi-escapes: 4.3.2 chalk: 4.1.2 emittery: 0.13.1 @@ -9316,24 +9316,24 @@ snapshots: jest-worker@27.5.1: dependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 merge-stream: 2.0.0 supports-color: 8.1.1 jest-worker@30.3.0: dependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 '@ungap/structured-clone': 1.3.0 jest-util: 30.3.0 merge-stream: 2.0.0 supports-color: 8.1.1 - jest@30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)): + jest@30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)): dependencies: - '@jest/core': 30.3.0(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)) + '@jest/core': 30.3.0(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)) '@jest/types': 30.3.0 import-local: 3.2.0 - jest-cli: 30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)) + jest-cli: 30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)) transitivePeerDependencies: - '@types/node' - babel-plugin-macros @@ -9674,7 +9674,7 @@ snapshots: neo-async@2.6.2: {} - newrelic@14.1.2: + newrelic@14.3.0: dependencies: '@apm-js-collab/tracing-hooks': 0.9.1 '@grpc/grpc-js': 1.14.4 @@ -9702,8 +9702,8 @@ snapshots: winston-transport: 4.9.0 optionalDependencies: '@datadog/pprof': 5.15.0 - '@newrelic/fn-inspect': 5.0.0 - '@newrelic/native-metrics': 13.0.0 + '@newrelic/fn-inspect': 5.1.0 + '@newrelic/native-metrics': 13.1.0 '@prisma/prisma-fmt-wasm': 4.17.0-16.27eb2449f178cd9fe1a4b892d732cc4795f75085 transitivePeerDependencies: - bufferutil @@ -9904,7 +9904,7 @@ snapshots: '@protobufjs/path': 1.1.2 '@protobufjs/pool': 1.1.0 '@protobufjs/utf8': 1.1.1 - '@types/node': 24.12.2 + '@types/node': 26.1.1 long: 5.3.2 proxy-addr@2.0.7: @@ -10463,12 +10463,12 @@ snapshots: dependencies: typescript: 6.0.2 - ts-jest@29.4.9(@babel/core@7.29.0)(@jest/transform@30.3.0)(@jest/types@30.3.0)(babel-jest@30.3.0(@babel/core@7.29.0))(jest-util@30.3.0)(jest@30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)))(typescript@5.9.3): + ts-jest@29.4.9(@babel/core@7.29.0)(@jest/transform@30.3.0)(@jest/types@30.3.0)(babel-jest@30.3.0(@babel/core@7.29.0))(jest-util@30.3.0)(jest@30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)))(typescript@5.9.3): dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 handlebars: 4.7.9 - jest: 30.3.0(@types/node@24.12.2)(ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3)) + jest: 30.3.0(@types/node@26.1.1)(ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3)) json5: 2.2.3 lodash.memoize: 4.1.2 make-error: 1.3.6 @@ -10493,14 +10493,14 @@ snapshots: typescript: 5.9.3 webpack: 5.106.0 - ts-node@10.9.2(@types/node@24.12.2)(typescript@5.9.3): + ts-node@10.9.2(@types/node@26.1.1)(typescript@5.9.3): dependencies: '@cspotcode/source-map-support': 0.8.1 '@tsconfig/node10': 1.0.12 '@tsconfig/node12': 1.0.11 '@tsconfig/node14': 1.0.3 '@tsconfig/node16': 1.0.4 - '@types/node': 24.12.2 + '@types/node': 26.1.1 acorn: 8.16.0 acorn-walk: 8.3.5 arg: 4.1.3 @@ -10588,7 +10588,7 @@ snapshots: uint8array-extras@1.5.0: {} - undici-types@7.16.0: {} + undici-types@8.3.0: {} undici@7.24.8: {} @@ -10679,7 +10679,7 @@ snapshots: d3-time: 3.1.0 d3-timer: 3.0.1 - vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1): + vite@8.0.8(@types/node@26.1.1)(esbuild@0.27.3)(jiti@2.6.1)(terser@5.46.1): dependencies: lightningcss: 1.32.0 picomatch: 4.0.4 @@ -10687,7 +10687,7 @@ snapshots: rolldown: 1.0.0-rc.15 tinyglobby: 0.2.16 optionalDependencies: - '@types/node': 24.12.2 + '@types/node': 26.1.1 esbuild: 0.27.3 fsevents: 2.3.3 jiti: 2.6.1 -- 2.54.0 From 96fede9fe5296de076de01c989685268dfdf74d7 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Fri, 24 Jul 2026 21:42:28 -0700 Subject: [PATCH 2/3] style(api): apply prettier formatting --- .../auction-deadline.scheduler.spec.ts | 28 +-- .../auction/auction-deadline.scheduler.ts | 32 ++-- .../auction/auction-event-bus.service.ts | 7 +- .../modules/auction/auction-rejection.spec.ts | 5 +- .../auction/auction-side-effect.service.ts | 37 ++-- .../src/modules/auction/auction.controller.ts | 3 +- .../src/modules/auction/auction.gateway.ts | 30 +-- .../auction-redis-command.service.spec.ts | 108 ++++++----- .../auction/redis/auction-redis-projection.ts | 4 +- ...auction-redis-state-reader.service.spec.ts | 10 +- .../auction-redis-state-reader.service.ts | 66 ++++--- .../auction-redis.apply-transition.spec.ts | 4 +- .../auction/redis/auction-redis.bid.spec.ts | 4 +- .../auction/redis/auction-redis.keys.spec.ts | 6 +- .../redis/auction-redis.service.spec.ts | 4 +- .../auction/redis/auction-redis.service.ts | 6 +- .../auction/redis/auction-redis.state.spec.ts | 4 +- apps/api/src/modules/auth/auth-request.ts | 5 +- apps/api/src/modules/auth/auth.service.ts | 5 +- apps/api/src/modules/auth/jwt.guard.ts | 3 +- .../modules/common/parse-object-id.pipe.ts | 7 +- .../community-stats.controller.ts | 18 +- .../community-stats/community-stats.types.ts | 9 +- .../match-stats-fragment.builder.ts | 30 +-- .../modules/community/community.service.ts | 5 +- .../dakao/dakao-outbox-sweeper.service.ts | 3 +- .../src/modules/dakao/dakao-outbox.service.ts | 46 ++--- .../handlers/match-cancel.handler.spec.ts | 8 +- .../dakao/handlers/match-join.handler.spec.ts | 16 +- .../dakao/handlers/match-join.handler.ts | 9 +- .../database/auction-redis-schema.spec.ts | 53 ++++-- .../20260502-auction-pass-history.ts | 5 +- .../migrations/20260502-team-index.spec.ts | 37 ++-- .../migrations/20260502-team-index.ts | 51 +++-- ...0260622-auction-redis-field-rename.spec.ts | 26 ++- .../20260622-auction-redis-field-rename.ts | 14 +- ...pair-limited-round-robin-finished-match.ts | 26 +-- .../run-auction-redis-field-rename.ts | 9 +- .../run-tournament-code-unique-indexes.ts | 8 +- .../mongoose-performance.plugin.ts | 31 ++-- .../modules/global/observability/new-relic.ts | 4 +- .../observability/performance-observer.ts | 8 +- .../global/redis/distributed-lock.service.ts | 58 +++--- .../src/modules/global/redis/redis.module.ts | 4 +- .../global/redis/redis.service.spec.ts | 16 +- .../src/modules/global/redis/redis.service.ts | 8 +- .../legacy-import/match-builder.util.ts | 19 +- .../match-history/match-history.controller.ts | 4 +- .../match-history/match-history.service.ts | 117 ++++++++---- .../riot-job-queue/riot-job-queue.module.ts | 6 +- .../riot-job-queue/riot-job-queue.service.ts | 34 ++-- .../riot-job-queue/riot-job-queue.types.ts | 5 +- .../riot-job-worker.service.spec.ts | 18 +- .../riot-job-queue/riot-job-worker.service.ts | 8 +- .../riot-job-queue/riot-refresh.gateway.ts | 5 +- .../riot-account-enrichment.service.spec.ts | 117 ++++++------ .../modules/riot/riot-ddragon.service.spec.ts | 8 +- .../src/modules/riot/riot-ddragon.service.ts | 33 ++-- .../src/modules/riot/riot-league.service.ts | 5 +- .../src/modules/riot/riot-match.service.ts | 26 ++- .../src/modules/riot/riot-queue.constants.ts | 7 +- .../riot/riot-recent-matches.service.ts | 17 +- .../modules/riot/riot-recent-stats.service.ts | 21 ++- .../src/modules/riot/riot-summoner.service.ts | 5 +- .../riot/riot-webhook.controller.spec.ts | 8 +- .../modules/riot/riot-webhook.controller.ts | 8 +- apps/api/src/modules/riot/riot.types.ts | 11 +- .../tournament-code/round-robin.util.spec.ts | 9 +- .../tournament-code/round-robin.util.ts | 5 +- .../tournament-code-vendor.service.spec.ts | 4 +- apps/api/src/modules/user/user.controller.ts | 10 +- .../scripts/api-performance-report.spec.ts | 17 +- .../api/src/scripts/api-performance-report.ts | 28 +-- .../src/scripts/auction-redis-rehearsal.ts | 175 ++++++++++-------- apps/api/src/seed.ts | 19 +- 75 files changed, 955 insertions(+), 674 deletions(-) diff --git a/apps/api/src/modules/auction/auction-deadline.scheduler.spec.ts b/apps/api/src/modules/auction/auction-deadline.scheduler.spec.ts index 1e4824df..e0aad270 100644 --- a/apps/api/src/modules/auction/auction-deadline.scheduler.spec.ts +++ b/apps/api/src/modules/auction/auction-deadline.scheduler.spec.ts @@ -79,7 +79,9 @@ describe('AuctionDeadlineScheduler', () => { .spyOn(scheduler, 'processDueBidRoundDeadlines') .mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 }); - await (scheduler as unknown as { safeTick: () => Promise }).safeTick(); + await ( + scheduler as unknown as { safeTick: () => Promise } + ).safeTick(); const leaderLockToken = redis.acquireTokenLock.mock.calls[0]?.[1]; expect(redis.acquireTokenLock).toHaveBeenCalledWith( @@ -100,7 +102,9 @@ describe('AuctionDeadlineScheduler', () => { .spyOn(scheduler, 'processDueBidRoundDeadlines') .mockResolvedValue({ completed: 0, prepared: 0, skipped: 0 }); - await (scheduler as unknown as { safeTick: () => Promise }).safeTick(); + await ( + scheduler as unknown as { safeTick: () => Promise } + ).safeTick(); expect(processDueBidRoundDeadlinesSpy).not.toHaveBeenCalled(); expect(redis.releaseTokenLock).not.toHaveBeenCalled(); @@ -129,10 +133,12 @@ describe('AuctionDeadlineScheduler', () => { it('prepares and completes due auction deadlines', async () => { const matchId = '665f2f01f1f1f1f1f1f1f1f1'; const completedState = { phase: 'passed', revision: 3 }; - const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler({ - dueReply: [matchId], - completedState, - }); + const { auctionService, eventBus, redisCommand, scheduler } = makeScheduler( + { + dueReply: [matchId], + completedState, + }, + ); await expect(scheduler.processDueBidRoundDeadlines(10)).resolves.toEqual({ completed: 1, @@ -149,7 +155,10 @@ describe('AuctionDeadlineScheduler', () => { expect(auctionService.completePreparedExpiry).toHaveBeenCalledTimes(1); // 만료 확정 결과는 즉시 1차 broadcast돼야 한다(클라가 입찰 라운드에 멈춰 // 후속 액션에서 CONFLICT가 반복되는 것을 막는 핵심 동작). - expect(eventBus.broadcastState).toHaveBeenCalledWith(matchId, completedState); + expect(eventBus.broadcastState).toHaveBeenCalledWith( + matchId, + completedState, + ); }); it('skips noop expiry preparations', async () => { @@ -189,10 +198,7 @@ describe('AuctionDeadlineScheduler', () => { }); it('continues processing later deadline items after one item fails', async () => { - const matchIds = [ - '665f2f01f1f1f1f1f1f1f1f1', - '665f2f02f1f1f1f1f1f1f1f1', - ]; + const matchIds = ['665f2f01f1f1f1f1f1f1f1f1', '665f2f02f1f1f1f1f1f1f1f1']; const { auctionService, redisCommand, scheduler } = makeScheduler({ dueReply: matchIds, }); diff --git a/apps/api/src/modules/auction/auction-deadline.scheduler.ts b/apps/api/src/modules/auction/auction-deadline.scheduler.ts index b68a5ca8..60f9b654 100644 --- a/apps/api/src/modules/auction/auction-deadline.scheduler.ts +++ b/apps/api/src/modules/auction/auction-deadline.scheduler.ts @@ -101,15 +101,17 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy { currentRedisTimestampMS: number, batchLimit: number, ): Promise { - const reply = await this.auctionRedisService.raw().sendCommand([ - 'ZRANGEBYSCORE', - BID_ROUND_DEADLINE_QUEUE_KEY, - '-inf', - String(currentRedisTimestampMS), - 'LIMIT', - '0', - String(batchLimit), - ]); + const reply = await this.auctionRedisService + .raw() + .sendCommand([ + 'ZRANGEBYSCORE', + BID_ROUND_DEADLINE_QUEUE_KEY, + '-inf', + String(currentRedisTimestampMS), + 'LIMIT', + '0', + String(batchLimit), + ]); return Array.isArray(reply) ? reply.map(String) : []; } @@ -177,11 +179,11 @@ export class AuctionDeadlineScheduler implements OnModuleInit, OnModuleDestroy { return { completed, prepared, skipped }; } - private async removeBidRoundDeadlineQueueEntry(matchId: string): Promise { - await this.auctionRedisService.raw().sendCommand([ - 'ZREM', - BID_ROUND_DEADLINE_QUEUE_KEY, - matchId, - ]); + private async removeBidRoundDeadlineQueueEntry( + matchId: string, + ): Promise { + await this.auctionRedisService + .raw() + .sendCommand(['ZREM', BID_ROUND_DEADLINE_QUEUE_KEY, matchId]); } } diff --git a/apps/api/src/modules/auction/auction-event-bus.service.ts b/apps/api/src/modules/auction/auction-event-bus.service.ts index f4032730..f617de51 100644 --- a/apps/api/src/modules/auction/auction-event-bus.service.ts +++ b/apps/api/src/modules/auction/auction-event-bus.service.ts @@ -20,9 +20,8 @@ export class AuctionEventBusService { } public broadcastState(matchId: string, state: AuctionStateResponse): void { - this.auctionNamespace?.to(matchId).emit( - 'state', - serializeRealtimeAuction(state), - ); + this.auctionNamespace + ?.to(matchId) + .emit('state', serializeRealtimeAuction(state)); } } diff --git a/apps/api/src/modules/auction/auction-rejection.spec.ts b/apps/api/src/modules/auction/auction-rejection.spec.ts index 79b6316a..dfa73ea5 100644 --- a/apps/api/src/modules/auction/auction-rejection.spec.ts +++ b/apps/api/src/modules/auction/auction-rejection.spec.ts @@ -22,7 +22,10 @@ describe('resolveAuctionRejectionReason', () => { it('maps known BadRequest messages without a structured code', () => { expect( - resolveAuctionRejectionReason(undefined, 'Cannot advance from current phase.'), + resolveAuctionRejectionReason( + undefined, + 'Cannot advance from current phase.', + ), ).toBe( AUCTION_REJECTION_REASON.AUCTION_TRANSITION_REJECTED_BECAUSE_PHASE_DOES_NOT_ALLOW_ADVANCE, ); diff --git a/apps/api/src/modules/auction/auction-side-effect.service.ts b/apps/api/src/modules/auction/auction-side-effect.service.ts index 2dbc3b2e..950ccef9 100644 --- a/apps/api/src/modules/auction/auction-side-effect.service.ts +++ b/apps/api/src/modules/auction/auction-side-effect.service.ts @@ -41,22 +41,24 @@ export class AuctionSideEffectService { matchSideEffectStatus: AuctionMatchSideEffectStatus; }): Promise { const keys = buildAuctionRedisKeys(params.matchId); - const result = await this.auctionRedisService.raw().sendCommand([ - 'EVAL', - [ - "if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end", - "local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')", - 'local nextRevision = tonumber(ARGV[2])', - 'if currentRevision >= nextRevision then return 0 end', - "redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])", - 'return 1', - ].join('\n'), - '1', - keys.liveStateKey, - params.auctionLifecycleId, - String(params.matchSideEffectRevision), - params.matchSideEffectStatus, - ]); + const result = await this.auctionRedisService + .raw() + .sendCommand([ + 'EVAL', + [ + "if redis.call('HGET', KEYS[1], 'auctionLifecycleId') ~= ARGV[1] then return 0 end", + "local currentRevision = tonumber(redis.call('HGET', KEYS[1], 'matchSideEffectRevision') or '-1')", + 'local nextRevision = tonumber(ARGV[2])', + 'if currentRevision >= nextRevision then return 0 end', + "redis.call('HSET', KEYS[1], 'matchSideEffectRevision', ARGV[2], 'matchSideEffectStatus', ARGV[3])", + 'return 1', + ].join('\n'), + '1', + keys.liveStateKey, + params.auctionLifecycleId, + String(params.matchSideEffectRevision), + params.matchSideEffectStatus, + ]); return Number(result) === 1; } } @@ -78,8 +80,7 @@ export function canAcquireSideEffectLease( if (state.state === 'pending' || state.state === 'failed') return true; if (state.state !== 'processing') return false; return ( - (state.processingLeaseExpiresAtTimestampMS ?? 0) <= - currentRedisTimestampMS + (state.processingLeaseExpiresAtTimestampMS ?? 0) <= currentRedisTimestampMS ); } diff --git a/apps/api/src/modules/auction/auction.controller.ts b/apps/api/src/modules/auction/auction.controller.ts index 3aca5420..f6570d50 100644 --- a/apps/api/src/modules/auction/auction.controller.ts +++ b/apps/api/src/modules/auction/auction.controller.ts @@ -59,8 +59,7 @@ export class AuctionController { initialTeamBidPointAmount: c.initialTeamBidPointAmount, })), initialTeamBidPointAmount: body.initialTeamBidPointAmount ?? 1000, - maximumBidRoundDurationSeconds: - body.maximumBidRoundDurationSeconds ?? 30, + maximumBidRoundDurationSeconds: body.maximumBidRoundDurationSeconds ?? 30, bidRoundExtensionSeconds: body.bidRoundExtensionSeconds ?? 5, topTierAuctionPriorityThreshold: body.topTierAuctionPriorityThreshold ?? 'NONE', diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index 66d4df76..f71d7cf0 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -92,9 +92,7 @@ const BID_RATE_LIMIT_REJECTION_MESSAGE = allowedHeaders: ['Authorization', 'Content-Type', 'X-Auth-User-Id'], }, }) -export class AuctionGateway - implements OnGatewayConnection, OnGatewayInit -{ +export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @WebSocketServer() private server!: Namespace; @@ -205,7 +203,9 @@ export class AuctionGateway ack?.({ ...(bidDelta ? {} - : { state: this.serializeAuction(bidResult as AuctionStateResponse) }), + : { + state: this.serializeAuction(bidResult as AuctionStateResponse), + }), ok: true, bidRequestId, bidDelta: broadcastBidDelta, @@ -417,8 +417,9 @@ export class AuctionGateway private consumeBidRateLimit(socket: Socket): boolean { const currentTimestampMS = Date.now(); - const previousState = socket.data - .auctionBidRateLimit as BidRateLimitState | undefined; + const previousState = socket.data.auctionBidRateLimit as + | BidRateLimitState + | undefined; if ( !previousState || currentTimestampMS - previousState.windowStartedAtTimestampMS >= @@ -633,7 +634,9 @@ export class AuctionGateway typeof errorPayload.code === 'string' ? errorPayload.code : undefined, errorPayload.message, ); - const resyncRecommended = isAuctionResyncRecommended(auctionRejectionReason); + const resyncRecommended = isAuctionResyncRecommended( + auctionRejectionReason, + ); const state = resyncRecommended ? await this.fetchSerializedAuctionState(matchId) : undefined; @@ -688,7 +691,9 @@ export class AuctionGateway return { code: error instanceof Error ? error.message : 'UNKNOWN', message: - error instanceof Error ? error.message : 'Unexpected auction gateway error.', + error instanceof Error + ? error.message + : 'Unexpected auction gateway error.', }; } @@ -724,7 +729,10 @@ export class AuctionGateway auction: AuctionStateResponse, bidRequestId?: string, ): Record | null { - const serialized = this.serializeAuction(auction) as Record; + const serialized = this.serializeAuction(auction) as Record< + string, + unknown + >; const revision = Number(serialized.revision); const currentHighestBidPointAmount = Number( serialized.currentHighestBidPointAmount ?? serialized.currentBid, @@ -775,9 +783,7 @@ export class AuctionGateway }; } - private isBidDeltaResponse( - value: unknown, - ): value is AuctionBidDeltaResponse { + private isBidDeltaResponse(value: unknown): value is AuctionBidDeltaResponse { return ( typeof value === 'object' && value !== null && diff --git a/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts b/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts index 515cdb51..64ba08df 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-command.service.spec.ts @@ -210,21 +210,25 @@ describe('AuctionRedisCommandService', () => { it('parses apply transition replay and rejected replies', async () => { await expect( - makeService(['REPLAY', 'APPLIED', 'transition-1', '2100']) - .service.applyTransition('match-1', { - afterAuctionStructureStateJson: '{}', - auctionHistorySequence: 5, - auctionLifecycleId: 'life-1', - auctionStateTransitionId: 'transition-1', - broadcastStateRevision: 11, - deadline: { mode: 'none' }, - durabilityPayloadJson: '{}', - expectedPhase: 'sold', - expectedRevision: 10, - liveStatePatch: {}, - matchId: 'match-1', - shouldBroadcastState: false, - }), + makeService([ + 'REPLAY', + 'APPLIED', + 'transition-1', + '2100', + ]).service.applyTransition('match-1', { + afterAuctionStructureStateJson: '{}', + auctionHistorySequence: 5, + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + broadcastStateRevision: 11, + deadline: { mode: 'none' }, + durabilityPayloadJson: '{}', + expectedPhase: 'sold', + expectedRevision: 10, + liveStatePatch: {}, + matchId: 'match-1', + shouldBroadcastState: false, + }), ).resolves.toEqual({ auctionStateTransitionId: 'transition-1', currentServerTimestampMS: 2100, @@ -233,21 +237,25 @@ describe('AuctionRedisCommandService', () => { }); await expect( - makeService(['REJECTED', 'CONFLICT', 'transition-1', '2200']) - .service.applyTransition('match-1', { - afterAuctionStructureStateJson: '{}', - auctionHistorySequence: 5, - auctionLifecycleId: 'life-1', - auctionStateTransitionId: 'transition-1', - broadcastStateRevision: 11, - deadline: { mode: 'none' }, - durabilityPayloadJson: '{}', - expectedPhase: 'sold', - expectedRevision: 10, - liveStatePatch: {}, - matchId: 'match-1', - shouldBroadcastState: false, - }), + makeService([ + 'REJECTED', + 'CONFLICT', + 'transition-1', + '2200', + ]).service.applyTransition('match-1', { + afterAuctionStructureStateJson: '{}', + auctionHistorySequence: 5, + auctionLifecycleId: 'life-1', + auctionStateTransitionId: 'transition-1', + broadcastStateRevision: 11, + deadline: { mode: 'none' }, + durabilityPayloadJson: '{}', + expectedPhase: 'sold', + expectedRevision: 10, + liveStatePatch: {}, + matchId: 'match-1', + shouldBroadcastState: false, + }), ).resolves.toEqual({ auctionStateTransitionId: 'transition-1', code: 'CONFLICT', @@ -288,12 +296,17 @@ describe('AuctionRedisCommandService', () => { it('parses expire prepare replay and noop replies', async () => { await expect( - makeService(['REPLAY', 'passed', 'expire-1', '12', '3100']) - .service.expirePrepare('match-1', { - auctionStateTransitionId: 'expire-1', - bidRoundExpiryRetryDelayMS: 3000, - matchId: 'match-1', - }), + makeService([ + 'REPLAY', + 'passed', + 'expire-1', + '12', + '3100', + ]).service.expirePrepare('match-1', { + auctionStateTransitionId: 'expire-1', + bidRoundExpiryRetryDelayMS: 3000, + matchId: 'match-1', + }), ).resolves.toMatchObject({ auctionStateTransitionId: 'expire-1', bidRoundExpiryDecision: 'passed', @@ -360,16 +373,19 @@ describe('AuctionRedisCommandService', () => { }); await expect( - makeService(['REJECTED', 'INVALID_PATCH_ARITY', '4200']) - .service.hydrateState('match-1', { - auctionHistorySequence: 3, - auctionLifecycleId: 'life-1', - maximumBidRoundDurationSeconds: 30, - matchId: 'match-1', - phase: 'presenting', - revision: 6, - structureStateJson: '{}', - }), + makeService([ + 'REJECTED', + 'INVALID_PATCH_ARITY', + '4200', + ]).service.hydrateState('match-1', { + auctionHistorySequence: 3, + auctionLifecycleId: 'life-1', + maximumBidRoundDurationSeconds: 30, + matchId: 'match-1', + phase: 'presenting', + revision: 6, + structureStateJson: '{}', + }), ).resolves.toEqual({ code: 'INVALID_PATCH_ARITY', currentServerTimestampMS: 4200, diff --git a/apps/api/src/modules/auction/redis/auction-redis-projection.ts b/apps/api/src/modules/auction/redis/auction-redis-projection.ts index 3993a4a9..2254b708 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-projection.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-projection.ts @@ -85,7 +85,9 @@ export function stringifyAuctionRedisStructureState( return JSON.stringify(buildAuctionRedisStructureState(input)); } -function countAuctionTeamMembersIncludingCaptain(team: RedisAuctionTeam): number { +function countAuctionTeamMembersIncludingCaptain( + team: RedisAuctionTeam, +): number { const userIds = new Set([team.captainUserId.toString()]); for (const member of team.members) { userIds.add(member.userId.toString()); diff --git a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts index ed81edfe..ed605a36 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.spec.ts @@ -1,7 +1,10 @@ import { AuctionRedisService } from './auction-redis.service'; import { AuctionRedisStateReaderService } from './auction-redis-state-reader.service'; -function makeService(commandReplies: unknown[], currentServerTimestampMS = 1000) { +function makeService( + commandReplies: unknown[], + currentServerTimestampMS = 1000, +) { const sendCommand = jest .fn() .mockImplementation(() => Promise.resolve(commandReplies.shift())); @@ -149,7 +152,9 @@ describe('AuctionRedisStateReaderService', () => { [], ]); - await expect(service.readAuctionStateView('match-1')).resolves.toMatchObject({ + await expect( + service.readAuctionStateView('match-1'), + ).resolves.toMatchObject({ auctionLifecycleId: 'life-1', auctionTeams: [], phase: 'presenting', @@ -181,7 +186,6 @@ describe('AuctionRedisStateReaderService', () => { }); }); - it('returns null when live or structure state is absent', async () => { await expect( makeService([[], '{"auctionTeams":[]}', []]).service.readAuctionStateView( diff --git a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts index fc0b5384..593446d8 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts @@ -42,12 +42,14 @@ export class AuctionRedisStateReaderService { matchId: string, ): Promise { const keys = buildAuctionRedisKeys(matchId); - const reply = await this.auctionRedisService.raw().sendCommand([ - 'HMGET', - keys.liveStateKey, - 'auctionLifecycleId', - 'revision', - ]); + const reply = await this.auctionRedisService + .raw() + .sendCommand([ + 'HMGET', + keys.liveStateKey, + 'auctionLifecycleId', + 'revision', + ]); if (!Array.isArray(reply)) return null; const auctionLifecycleId = typeof reply[0] === 'string' && reply[0] ? reply[0] : undefined; @@ -68,14 +70,16 @@ export class AuctionRedisStateReaderService { ): Promise { const keys = buildAuctionRedisKeys(matchId); const bidderTeamCaptainUserIdField = `team:${bidderTeamIndex}:captainUserId`; - const liveReply = await this.auctionRedisService.raw().sendCommand([ - 'HMGET', - keys.liveStateKey, - 'phase', - 'auctionLifecycleId', - 'currentBidRoundPlayerUserId', - bidderTeamCaptainUserIdField, - ]); + const liveReply = await this.auctionRedisService + .raw() + .sendCommand([ + 'HMGET', + keys.liveStateKey, + 'phase', + 'auctionLifecycleId', + 'currentBidRoundPlayerUserId', + bidderTeamCaptainUserIdField, + ]); if (!Array.isArray(liveReply)) return null; const phase = stringValue(liveReply[0]); @@ -102,18 +106,23 @@ export class AuctionRedisStateReaderService { options: AuctionRedisStateViewReadOptions = {}, ): Promise | null> { const keys = buildAuctionRedisKeys(matchId); - const [currentServerTimestampMS, liveReply, structureStateJson, bidEntries] = - await Promise.all([ - this.auctionRedisService.getCurrentRedisTimestampMS(), - this.auctionRedisService.raw().sendCommand(['HGETALL', keys.liveStateKey]), - this.auctionRedisService.raw().sendCommand(['GET', keys.structureStateKey]), - this.auctionRedisService.raw().sendCommand([ - 'LRANGE', - keys.bidHistoryKey, - '0', - '-1', - ]), - ]); + const [ + currentServerTimestampMS, + liveReply, + structureStateJson, + bidEntries, + ] = await Promise.all([ + this.auctionRedisService.getCurrentRedisTimestampMS(), + this.auctionRedisService + .raw() + .sendCommand(['HGETALL', keys.liveStateKey]), + this.auctionRedisService + .raw() + .sendCommand(['GET', keys.structureStateKey]), + this.auctionRedisService + .raw() + .sendCommand(['LRANGE', keys.bidHistoryKey, '0', '-1']), + ]); const liveState = parseHashReply(liveReply, { includeInternalLiveStateFields: @@ -210,7 +219,10 @@ function parseHashEntries( ): Record { const result: Record = {}; for (const [field, rawValue] of entries) { - if (!options.includeInternalLiveStateFields && isInternalLiveStateField(field)) { + if ( + !options.includeInternalLiveStateFields && + isInternalLiveStateField(field) + ) { continue; } const value = String(rawValue); diff --git a/apps/api/src/modules/auction/redis/auction-redis.apply-transition.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.apply-transition.spec.ts index 90dd2586..239a222a 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.apply-transition.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.apply-transition.spec.ts @@ -91,9 +91,7 @@ describe('auction apply transition redis script contract', () => { expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( 'shouldBroadcastState', ); - expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( - "redis.call('SADD'", - ); + expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain("redis.call('SADD'"); expect(AUCTION_APPLY_TRANSITION_SCRIPT.lua).toContain( "redis.call('HINCRBY'", ); diff --git a/apps/api/src/modules/auction/redis/auction-redis.bid.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.bid.spec.ts index fe0a5c7a..9a71e098 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.bid.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.bid.spec.ts @@ -64,9 +64,7 @@ describe('auction bid redis script contract', () => { expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('TIME')"); expect(AUCTION_BID_SCRIPT.lua).toContain("redis.call('HINCRBY'"); expect(AUCTION_BID_SCRIPT.lua).toContain('BID_REQUEST_RESULT_LIMIT'); - expect(AUCTION_BID_SCRIPT.lua).toContain( - 'currentHighestBidPointAmount', - ); + expect(AUCTION_BID_SCRIPT.lua).toContain('currentHighestBidPointAmount'); expect(AUCTION_BID_SCRIPT.lua).not.toContain('cjson.decode'); }); }); diff --git a/apps/api/src/modules/auction/redis/auction-redis.keys.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.keys.spec.ts index b03377b1..3b5032e9 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.keys.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.keys.spec.ts @@ -3,9 +3,11 @@ import { buildAuctionRedisKeys } from './auction-redis.keys'; describe('auction redis keys', () => { it('builds lifecycle-safe key names from match id', () => { expect(buildAuctionRedisKeys('match-1')).toMatchObject({ - actionRequestResultOrderKey: 'auction:match-1:auctionActionRequestResultOrder', + actionRequestResultOrderKey: + 'auction:match-1:auctionActionRequestResultOrder', actionRequestResultsKey: 'auction:match-1:auctionActionRequestResults', - appliedTransitionIdsKey: 'auction:match-1:appliedAuctionStateTransitionIds', + appliedTransitionIdsKey: + 'auction:match-1:appliedAuctionStateTransitionIds', bidHistoryKey: 'auction:match-1:auctionBidHistory', bidRequestResultOrderKey: 'auction:match-1:bidRequestResultOrder', bidRequestResultsKey: 'auction:match-1:bidRequestResults', diff --git a/apps/api/src/modules/auction/redis/auction-redis.service.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.service.spec.ts index 9098dec1..275714b3 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.service.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.service.spec.ts @@ -15,7 +15,9 @@ function makeService(sendCommand: jest.Mock) { describe('AuctionRedisService', () => { it('uses Redis TIME as the timestamp source', async () => { - const service = makeService(jest.fn().mockResolvedValue(['1781700000', '123000'])); + const service = makeService( + jest.fn().mockResolvedValue(['1781700000', '123000']), + ); await expect(service.getCurrentRedisTimestampMS()).resolves.toBe( 1_781_700_000_123, diff --git a/apps/api/src/modules/auction/redis/auction-redis.service.ts b/apps/api/src/modules/auction/redis/auction-redis.service.ts index 571787cd..91ba3cae 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.service.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.service.ts @@ -22,7 +22,11 @@ export class AuctionRedisNoscriptError extends Error { function isNoscriptError(error: unknown): boolean { if (error instanceof AuctionRedisNoscriptError) return true; const message = - error instanceof Error ? error.message : typeof error === 'string' ? error : ''; + error instanceof Error + ? error.message + : typeof error === 'string' + ? error + : ''; return /\bNOSCRIPT\b/iu.test(message); } diff --git a/apps/api/src/modules/auction/redis/auction-redis.state.spec.ts b/apps/api/src/modules/auction/redis/auction-redis.state.spec.ts index 810b77d0..537fc5a2 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.state.spec.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.state.spec.ts @@ -100,9 +100,7 @@ describe('auction redis state assembly', () => { '1000', ]); expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain("redis.call('TIME')"); - expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain( - 'INVALID_PATCH_ARITY', - ); + expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain('INVALID_PATCH_ARITY'); expect(AUCTION_HYDRATE_STATE_SCRIPT.lua).toContain( 'mongoRevision > redisRevision', ); diff --git a/apps/api/src/modules/auth/auth-request.ts b/apps/api/src/modules/auth/auth-request.ts index 678677d9..0255d17c 100644 --- a/apps/api/src/modules/auth/auth-request.ts +++ b/apps/api/src/modules/auth/auth-request.ts @@ -1,8 +1,5 @@ import type { JWTHeaderParameters, JWTPayload } from 'jose'; -import type { - IdentityDocument, - UserDocument, -} from '../global/database/schema'; +import type { IdentityDocument, UserDocument } from '../global/database/schema'; import type { IdentityProviderName } from './jwt.service'; declare module 'express' { diff --git a/apps/api/src/modules/auth/auth.service.ts b/apps/api/src/modules/auth/auth.service.ts index 373aa71f..91773427 100644 --- a/apps/api/src/modules/auth/auth.service.ts +++ b/apps/api/src/modules/auth/auth.service.ts @@ -2,10 +2,7 @@ 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 { IdentityDocument, UserDocument } from '../global/database/schema'; import { SecretService } from '../global/secret/secret.service'; import './auth-request'; diff --git a/apps/api/src/modules/auth/jwt.guard.ts b/apps/api/src/modules/auth/jwt.guard.ts index e3d405a1..97b73d0d 100644 --- a/apps/api/src/modules/auth/jwt.guard.ts +++ b/apps/api/src/modules/auth/jwt.guard.ts @@ -84,7 +84,8 @@ export class JwtAuthGuard implements CanActivate { } throw new Error(`Unknown issuer: ${iss}`); } catch (err) { - const message = err instanceof Error ? err.message : 'Unable to decode token'; + const message = + err instanceof Error ? err.message : 'Unable to decode token'; throw new UnauthorizedException(message); } } diff --git a/apps/api/src/modules/common/parse-object-id.pipe.ts b/apps/api/src/modules/common/parse-object-id.pipe.ts index e9e046f6..a781590c 100644 --- a/apps/api/src/modules/common/parse-object-id.pipe.ts +++ b/apps/api/src/modules/common/parse-object-id.pipe.ts @@ -7,9 +7,10 @@ import { import mongoose from 'mongoose'; @Injectable() -export class ParseObjectIdPipe - implements PipeTransform -{ +export class ParseObjectIdPipe implements PipeTransform< + string, + mongoose.Types.ObjectId +> { public transform( value: string, metadata: ArgumentMetadata, diff --git a/apps/api/src/modules/community-stats/community-stats.controller.ts b/apps/api/src/modules/community-stats/community-stats.controller.ts index e8d4ee69..982f4f66 100644 --- a/apps/api/src/modules/community-stats/community-stats.controller.ts +++ b/apps/api/src/modules/community-stats/community-stats.controller.ts @@ -23,7 +23,14 @@ export class CommunityStatsController { ) { return this.communityStatsService.getMatches({ communityId, - filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), + filters: this.toFilters({ + seasonId, + from, + to, + championId, + cursor, + limit, + }), }); } @@ -85,7 +92,14 @@ export class CommunityStatsController { return this.communityStatsService.getUserInternalHistory({ communityId, userId, - filters: this.toFilters({ seasonId, from, to, championId, cursor, limit }), + filters: this.toFilters({ + seasonId, + from, + to, + championId, + cursor, + limit, + }), }); } diff --git a/apps/api/src/modules/community-stats/community-stats.types.ts b/apps/api/src/modules/community-stats/community-stats.types.ts index e6824841..928a7471 100644 --- a/apps/api/src/modules/community-stats/community-stats.types.ts +++ b/apps/api/src/modules/community-stats/community-stats.types.ts @@ -7,7 +7,10 @@ import type { RiotLane, TeamSide, } from '../global/database/schema'; -import type { RecentMatchView, HistorySeasonDto } from '../match-history/match-history.types'; +import type { + RecentMatchView, + HistorySeasonDto, +} from '../match-history/match-history.types'; export interface CommunityStatsFilters { seasonId?: string; @@ -80,7 +83,9 @@ export interface LeaderboardRow { avgCsPerMin: number; avgDamageShare: number; avgVisionScore: number; - byLane: Partial>; + byLane: Partial< + Record + >; topChampions: Array<{ championId: number; games: number; winRate: number }>; } diff --git a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts index c91a5d77..e9ab7223 100644 --- a/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts +++ b/apps/api/src/modules/community-stats/match-stats-fragment.builder.ts @@ -227,9 +227,7 @@ export class MatchStatsFragmentBuilder { participant, rawParticipant, buildEvents: rawParticipant - ? buildEventsByParticipantId.get( - rawParticipant.participantId, - ) + ? buildEventsByParticipantId.get(rawParticipant.participantId) : undefined, checkpoints: rawParticipant ? checkpointsByParticipantId.get(rawParticipant.participantId) @@ -420,7 +418,10 @@ export class MatchStatsFragmentBuilder { private toBuildEventsByParticipantId( timeline?: RiotMatchTimelineDto, ): Map { - const buildEventsByParticipantId = new Map(); + const buildEventsByParticipantId = new Map< + number, + ParticipantBuildEvents + >(); if (!timeline?.info.frames.length) return buildEventsByParticipantId; const getEvents = (participantId: number): ParticipantBuildEvents => { @@ -796,15 +797,18 @@ export class MatchStatsFragmentBuilder { ? timelineDragon : (rawObjectives?.dragon?.kills ?? 0), inhibitor: rawObjectives?.inhibitor?.kills ?? 0, - baron: (timelineObjectives?.baron ?? 0) > 0 - ? (timelineObjectives?.baron ?? 0) - : (rawObjectives?.baron?.kills ?? 0), - riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0 - ? (timelineObjectives?.riftHerald ?? 0) - : (rawObjectives?.riftHerald?.kills ?? 0), - voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0 - ? (timelineObjectives?.voidGrub ?? 0) - : (rawObjectives?.horde?.kills ?? 0), + baron: + (timelineObjectives?.baron ?? 0) > 0 + ? (timelineObjectives?.baron ?? 0) + : (rawObjectives?.baron?.kills ?? 0), + riftHerald: + (timelineObjectives?.riftHerald ?? 0) > 0 + ? (timelineObjectives?.riftHerald ?? 0) + : (rawObjectives?.riftHerald?.kills ?? 0), + voidGrub: + (timelineObjectives?.voidGrub ?? 0) > 0 + ? (timelineObjectives?.voidGrub ?? 0) + : (rawObjectives?.horde?.kills ?? 0), elderDragon: hasProjectedDragon ? timelineElder : 0, }; } diff --git a/apps/api/src/modules/community/community.service.ts b/apps/api/src/modules/community/community.service.ts index 44a52e42..24dc17b5 100644 --- a/apps/api/src/modules/community/community.service.ts +++ b/apps/api/src/modules/community/community.service.ts @@ -6,10 +6,7 @@ import { } from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; -import { - CommunityDocument, - UserDocument, -} from '../global/database/schema'; +import { CommunityDocument, UserDocument } from '../global/database/schema'; export interface CreateCommunityInput { name: string; diff --git a/apps/api/src/modules/dakao/dakao-outbox-sweeper.service.ts b/apps/api/src/modules/dakao/dakao-outbox-sweeper.service.ts index e060242f..c24a3377 100644 --- a/apps/api/src/modules/dakao/dakao-outbox-sweeper.service.ts +++ b/apps/api/src/modules/dakao/dakao-outbox-sweeper.service.ts @@ -9,7 +9,8 @@ import { DakaoOutboxService } from './dakao-outbox.service'; const SWEEP_INTERVAL_MS = 60 * 1000; const STALE_OUTBOX_MS = 5 * 60 * 1000; -const SWEEP_LOCK_KEY = 'distributed-lock:dakao-outbox:sweep-stale-publish-leases'; +const SWEEP_LOCK_KEY = + 'distributed-lock:dakao-outbox:sweep-stale-publish-leases'; const SWEEP_LOCK_EXPIRATION_DURATION_MILLISECONDS = 55_000; @Injectable() diff --git a/apps/api/src/modules/dakao/dakao-outbox.service.ts b/apps/api/src/modules/dakao/dakao-outbox.service.ts index 1662c6a6..bcf72225 100644 --- a/apps/api/src/modules/dakao/dakao-outbox.service.ts +++ b/apps/api/src/modules/dakao/dakao-outbox.service.ts @@ -78,35 +78,29 @@ export class DakaoOutboxService { await this.natsService.publishJetStream(params.subject, params.envelope, { messageId: params.eventId, }); - await OutboxModel.updateOne( - updateFilter, - { - $set: { - state: 'published', - publishedAt: new Date(), - }, - $inc: { publishAttempts: 1 }, - $unset: { - lastPublishError: '', - publishLeaseOwnerIdentifier: '', - publishLeaseExpiresAt: '', - }, + await OutboxModel.updateOne(updateFilter, { + $set: { + state: 'published', + publishedAt: new Date(), }, - ).exec(); + $inc: { publishAttempts: 1 }, + $unset: { + lastPublishError: '', + publishLeaseOwnerIdentifier: '', + publishLeaseExpiresAt: '', + }, + }).exec(); } catch (err) { - await OutboxModel.updateOne( - updateFilter, - { - $inc: { publishAttempts: 1 }, - $set: { - lastPublishError: (err as Error)?.message ?? String(err), - }, - $unset: { - publishLeaseOwnerIdentifier: '', - publishLeaseExpiresAt: '', - }, + await OutboxModel.updateOne(updateFilter, { + $inc: { publishAttempts: 1 }, + $set: { + lastPublishError: (err as Error)?.message ?? String(err), }, - ).exec(); + $unset: { + publishLeaseOwnerIdentifier: '', + publishLeaseExpiresAt: '', + }, + }).exec(); this.logger.error( `Failed to publish Dakao outbox eventId=${params.eventId}: ${ (err as Error)?.stack ?? err diff --git a/apps/api/src/modules/dakao/handlers/match-cancel.handler.spec.ts b/apps/api/src/modules/dakao/handlers/match-cancel.handler.spec.ts index 5225da2f..a9897bd0 100644 --- a/apps/api/src/modules/dakao/handlers/match-cancel.handler.spec.ts +++ b/apps/api/src/modules/dakao/handlers/match-cancel.handler.spec.ts @@ -104,9 +104,11 @@ describe('MatchCancelHandler', () => { const handler = makeHandler({ matchService: { cancelJoin, - list: jest.fn().mockResolvedValue([ - { _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, - ]), + list: jest + .fn() + .mockResolvedValue([ + { _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, + ]), } as Partial, dakaoUserService: { findUserByKakaoTalkId, 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 index 9ca96fc8..e34eec58 100644 --- a/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts +++ b/apps/api/src/modules/dakao/handlers/match-join.handler.spec.ts @@ -230,9 +230,11 @@ describe('MatchJoinHandler', () => { const resolveRiotAccount = jest.fn(); const handler = makeHandler({ matchService: { - list: jest.fn().mockResolvedValue([ - { _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, - ]), + list: jest + .fn() + .mockResolvedValue([ + { _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, + ]), join, } as Partial, dakaoUserService: { @@ -282,9 +284,11 @@ describe('MatchJoinHandler', () => { const join = jest.fn(); const handler = makeHandler({ matchService: { - list: jest.fn().mockResolvedValue([ - { _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, - ]), + list: jest + .fn() + .mockResolvedValue([ + { _id: matchId, title: '저녁 내전', shortCode: 'AB12' }, + ]), join, } as Partial, dakaoUserService: { diff --git a/apps/api/src/modules/dakao/handlers/match-join.handler.ts b/apps/api/src/modules/dakao/handlers/match-join.handler.ts index a5e45a0c..e1407a86 100644 --- a/apps/api/src/modules/dakao/handlers/match-join.handler.ts +++ b/apps/api/src/modules/dakao/handlers/match-join.handler.ts @@ -44,9 +44,7 @@ export class MatchJoinHandler { return this.errorReply(params, joinTarget); } - let resolved: - | { user: UserDocument; riotAccount: RiotAccount } - | string; + let resolved: { user: UserDocument; riotAccount: RiotAccount } | string; try { resolved = joinTarget.gameName && joinTarget.tagLine @@ -243,10 +241,7 @@ export class MatchJoinHandler { const gameName = normalizeRiotIdPart(value.slice(splitAt + 1)); if (!matchTitlePrefix || !gameName) continue; - const result = resolveRecruitingMatchReference( - matchTitlePrefix, - matches, - ); + const result = resolveRecruitingMatchReference(matchTitlePrefix, matches); if (result.kind === 'matched') { return { kind: 'matched', match: result.match, gameName }; } diff --git a/apps/api/src/modules/global/database/auction-redis-schema.spec.ts b/apps/api/src/modules/global/database/auction-redis-schema.spec.ts index c984c8cd..4ea571e5 100644 --- a/apps/api/src/modules/global/database/auction-redis-schema.spec.ts +++ b/apps/api/src/modules/global/database/auction-redis-schema.spec.ts @@ -19,7 +19,9 @@ describe('auction Redis schema foundation', () => { expect(AuctionSchema.path('revision')).toBeDefined(); expect(AuctionSchema.path('auctionEngineVersion')).toBeDefined(); expect(AuctionSchema.path('auctionLifecycleId')).toBeDefined(); - expect(AuctionSchema.path('lastAppliedAuctionStateTransitionId')).toBeDefined(); + expect( + AuctionSchema.path('lastAppliedAuctionStateTransitionId'), + ).toBeDefined(); expect(AuctionSchema.path('currentAuctionHistorySequence')).toBeDefined(); expect(AuctionSchema.path('startAuctionRequestId')).toBeDefined(); expect(AuctionSchema.path('startAuctionStateTransitionId')).toBeDefined(); @@ -36,46 +38,75 @@ describe('auction Redis schema foundation', () => { expect(AuctionSchema.path('auctionBidHistory')).toBeDefined(); expect(AuctionSchema.path('currentHighestBidPointAmount')).toBeDefined(); expect(AuctionSchema.path('currentHighestBidderTeamIndex')).toBeDefined(); - expect(AuctionSchema.path('currentBidRoundDeadlineTimestampMS')).toBeDefined(); + expect( + AuctionSchema.path('currentBidRoundDeadlineTimestampMS'), + ).toBeDefined(); expect(AuctionSchema.path('maximumBidRoundDurationSeconds')).toBeDefined(); expect(AuctionSchema.path('bidRoundExtensionSeconds')).toBeDefined(); expect(AuctionSchema.path('initialTeamBidPointAmount')).toBeDefined(); expect(AuctionSchema.path('topTierAuctionPriorityThreshold')).toBeDefined(); - expect(AuctionSchema.path('manualTopTierAuctionPriorityUserIds')).toBeDefined(); + expect( + AuctionSchema.path('manualTopTierAuctionPriorityUserIds'), + ).toBeDefined(); expect(AuctionSchema.path('auctionStartedAtTimestampMS')).toBeDefined(); expect(AuctionSchema.path('auctionCompletedAtTimestampMS')).toBeDefined(); }); it('adds history transition fields and reset/undo action enum values', () => { - expect(AuctionHistoryEntrySchema.path('auctionStateTransitionId')).toBeDefined(); + expect( + AuctionHistoryEntrySchema.path('auctionStateTransitionId'), + ).toBeDefined(); expect(AuctionHistoryEntrySchema.path('auctionLifecycleId')).toBeDefined(); expect(AuctionHistoryEntrySchema.path('revision')).toBeDefined(); expect(AuctionHistoryEntrySchema.path('historyMutation')).toBeDefined(); - expect(AuctionHistoryEntrySchema.path('matchSideEffectMutation')).toBeDefined(); + expect( + AuctionHistoryEntrySchema.path('matchSideEffectMutation'), + ).toBeDefined(); expect( AuctionHistoryEntrySchema.path('action').options.enum, ).toEqual( - expect.arrayContaining(['start', 'open-bidding', 'bid', 'sold', 'passed', 'next', 'complete', 'reset', 'undo']), + expect.arrayContaining([ + 'start', + 'open-bidding', + 'bid', + 'sold', + 'passed', + 'next', + 'complete', + 'reset', + 'undo', + ]), ); }); it('adds unique history indexes for sequence and transition idempotency', () => { const indexes = AuctionHistoryEntrySchema.indexes(); - expect(indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1]).toMatchObject({ + expect( + indexWithKeys(indexes, { auctionId: 1, sequence: 1 })?.[1], + ).toMatchObject({ unique: true, }); expect( - indexWithKeys(indexes, { auctionId: 1, auctionStateTransitionId: 1 })?.[1], + indexWithKeys(indexes, { + auctionId: 1, + auctionStateTransitionId: 1, + })?.[1], ).toMatchObject({ unique: true, sparse: true }); }); it('registers auction side effect application model with lease fields and unique idempotency index', () => { - expect(AuctionSideEffectApplicationSchema.path('processingOwnerToken')).toBeDefined(); expect( - AuctionSideEffectApplicationSchema.path('processingLeaseExpiresAtTimestampMS'), + AuctionSideEffectApplicationSchema.path('processingOwnerToken'), + ).toBeDefined(); + expect( + AuctionSideEffectApplicationSchema.path( + 'processingLeaseExpiresAtTimestampMS', + ), + ).toBeDefined(); + expect( + AuctionSideEffectApplicationSchema.path('payloadChecksum'), ).toBeDefined(); - expect(AuctionSideEffectApplicationSchema.path('payloadChecksum')).toBeDefined(); const indexes = AuctionSideEffectApplicationSchema.indexes(); expect( diff --git a/apps/api/src/modules/global/database/migrations/20260502-auction-pass-history.ts b/apps/api/src/modules/global/database/migrations/20260502-auction-pass-history.ts index 95f0bbce..665490f4 100644 --- a/apps/api/src/modules/global/database/migrations/20260502-auction-pass-history.ts +++ b/apps/api/src/modules/global/database/migrations/20260502-auction-pass-history.ts @@ -45,7 +45,10 @@ export async function migrateAuctionPassHistory( }; }> = []; - for await (const doc of db.collection('auction').find({}).limit(options.limit ?? 0)) { + for await (const doc of db + .collection('auction') + .find({}) + .limit(options.limit ?? 0)) { stats.scannedAuctions += 1; const set: Record = {}; let changed = false; diff --git a/apps/api/src/modules/global/database/migrations/20260502-team-index.spec.ts b/apps/api/src/modules/global/database/migrations/20260502-team-index.spec.ts index deb3168f..4e82af8e 100644 --- a/apps/api/src/modules/global/database/migrations/20260502-team-index.spec.ts +++ b/apps/api/src/modules/global/database/migrations/20260502-team-index.spec.ts @@ -27,17 +27,21 @@ function createDb(params: { }, }; }, - async bulkWrite(writes: Array<{ - updateOne: { - filter: { _id: unknown }; - update: { - $set: Record; - $unset: Record; + async bulkWrite( + writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { + $set: Record; + $unset: Record; + }; }; - }; - }>) { + }>, + ) { for (const write of writes) { - const doc = docs.find((item) => item._id === write.updateOne.filter._id); + const doc = docs.find( + (item) => item._id === write.updateOne.filter._id, + ); if (!doc) continue; Object.assign(doc, write.updateOne.update.$set); for (const key of Object.keys(write.updateOne.update.$unset)) { @@ -57,7 +61,10 @@ describe('migrateTeamIndex', () => { auctions: [ { _id: 'auction-1', - teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }], + teams: [ + { side: 'blue', groupIndex: 1 }, + { side: 'red', groupIndex: 1 }, + ], bids: [{ side: 'red', groupIndex: 1, amount: 100 }], currentBidder: 'red', currentBidderGroupIndex: 1, @@ -66,7 +73,10 @@ describe('migrateTeamIndex', () => { matches: [ { _id: 'match-1', - teams: [{ side: 'blue', groupIndex: 1 }, { side: 'red', groupIndex: 1 }], + teams: [ + { side: 'blue', groupIndex: 1 }, + { side: 'red', groupIndex: 1 }, + ], result: { winnerSide: 'blue', blueScore: 1, @@ -112,7 +122,10 @@ describe('migrateTeamIndex', () => { currentBidderTeamIndex: 2, }); expect(collections.match[0]).toMatchObject({ - teams: [{ teamIndex: 1, name: '1팀' }, { teamIndex: 2, name: '2팀' }], + teams: [ + { teamIndex: 1, name: '1팀' }, + { teamIndex: 2, name: '2팀' }, + ], result: { winnerTeamIndex: 1, games: [ diff --git a/apps/api/src/modules/global/database/migrations/20260502-team-index.ts b/apps/api/src/modules/global/database/migrations/20260502-team-index.ts index cbbf21c2..cd0863fc 100644 --- a/apps/api/src/modules/global/database/migrations/20260502-team-index.ts +++ b/apps/api/src/modules/global/database/migrations/20260502-team-index.ts @@ -45,8 +45,20 @@ export async function migrateTeamIndex( changedMatches: 0, }; - await migrateCollection(db.collection('auction'), options.limit, dryRun, stats, 'auction'); - await migrateCollection(db.collection('match'), options.limit, dryRun, stats, 'match'); + await migrateCollection( + db.collection('auction'), + options.limit, + dryRun, + stats, + 'auction', + ); + await migrateCollection( + db.collection('match'), + options.limit, + dryRun, + stats, + 'match', + ); return stats; } @@ -60,7 +72,7 @@ async function migrateCollection( ) { const cursor = collection.find({}).limit(limit ?? 0); const writes: Array<{ - updateOne: { + updateOne: { filter: { _id: unknown }; update: { $set: Record; $unset: Record }; }; @@ -143,7 +155,8 @@ function migrateMatch(doc: AnyDoc) { const migrated = { ...team }; const teamIndex = readTeamIndex(migrated); if (teamIndex !== undefined) migrated.teamIndex = teamIndex; - if (!migrated.name && typeof teamIndex === 'number') migrated.name = `${teamIndex}팀`; + if (!migrated.name && typeof teamIndex === 'number') + migrated.name = `${teamIndex}팀`; if ('side' in migrated || 'groupIndex' in migrated) changed = true; delete migrated.side; delete migrated.groupIndex; @@ -200,7 +213,10 @@ function migrateResult(result: Record) { migrated.games = games; const seriesResults = asArray(result.seriesResults).map((series) => { - if (typeof series.teamAIndex === 'number' && typeof series.teamBIndex === 'number') { + if ( + typeof series.teamAIndex === 'number' && + typeof series.teamBIndex === 'number' + ) { return series; } changed = true; @@ -216,7 +232,9 @@ function migrateResult(result: Record) { const teamBIndex = Math.max(legacyBlueTeamIndex, legacyRedTeamIndex); const blueScore = numberOrDefault(series.blueScore, 0); const redScore = numberOrDefault(series.redScore, 0); - const winnerSide = isSide(series.winnerSide) ? series.winnerSide : undefined; + const winnerSide = isSide(series.winnerSide) + ? series.winnerSide + : undefined; const winnerTeamIndex = winnerSide === 'blue' ? legacyBlueTeamIndex @@ -231,7 +249,8 @@ function migrateResult(result: Record) { winnerTeamIndex, }; }); - migrated.seriesResults = seriesResults.length > 0 ? seriesResults : buildSeries(games); + migrated.seriesResults = + seriesResults.length > 0 ? seriesResults : buildSeries(games); if (typeof migrated.winnerTeamIndex !== 'number') { const migratedSeriesResults = Array.isArray(migrated.seriesResults) @@ -244,7 +263,11 @@ function migrateResult(result: Record) { : undefined); } - if ('winnerSide' in migrated || 'blueScore' in migrated || 'redScore' in migrated) { + if ( + 'winnerSide' in migrated || + 'blueScore' in migrated || + 'redScore' in migrated + ) { changed = true; } delete migrated.winnerSide; @@ -272,8 +295,12 @@ function buildSeries(games: Record[]) { const teamAIndex = Math.min(blueTeamIndex, redTeamIndex); const teamBIndex = Math.max(blueTeamIndex, redTeamIndex); const key = `${teamAIndex}:${teamBIndex}`; - const current = - bySeries.get(key) ?? { teamAIndex, teamBIndex, teamAWins: 0, teamBWins: 0 }; + const current = bySeries.get(key) ?? { + teamAIndex, + teamBIndex, + teamAWins: 0, + teamBWins: 0, + }; if (winnerTeamIndex === teamAIndex) current.teamAWins += 1; if (winnerTeamIndex === teamBIndex) current.teamBWins += 1; current.winnerTeamIndex = @@ -331,5 +358,7 @@ function numberOrDefault(value: unknown, fallback: number) { } function numberOrUndefined(value: unknown) { - return typeof value === 'number' && Number.isFinite(value) ? value : undefined; + return typeof value === 'number' && Number.isFinite(value) + ? value + : undefined; } diff --git a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.spec.ts b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.spec.ts index 7d4e92dc..105b7ea9 100644 --- a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.spec.ts +++ b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.spec.ts @@ -30,20 +30,26 @@ function createDb(params: { auctions?: Doc[]; history?: Doc[] }) { }, }; }, - async bulkWrite(writes: Array<{ - updateOne: { - filter: { _id: unknown }; - update: { - $set?: Record; - $unset?: Record; + async bulkWrite( + writes: Array<{ + updateOne: { + filter: { _id: unknown }; + update: { + $set?: Record; + $unset?: Record; + }; }; - }; - }>) { + }>, + ) { for (const write of writes) { - const doc = docs.find((item) => item._id === write.updateOne.filter._id); + const doc = docs.find( + (item) => item._id === write.updateOne.filter._id, + ); if (!doc) continue; Object.assign(doc, write.updateOne.update.$set ?? {}); - for (const key of Object.keys(write.updateOne.update.$unset ?? {})) { + for (const key of Object.keys( + write.updateOne.update.$unset ?? {}, + )) { delete doc[key]; } } diff --git a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts index a1a0d67c..970e60ff 100644 --- a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts +++ b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts @@ -31,7 +31,10 @@ interface MigrationStats { } type AnyDoc = Record & { _id: unknown }; -type UpdateDoc = { $set?: Record; $unset?: Record }; +type UpdateDoc = { + $set?: Record; + $unset?: Record; +}; const AUCTION_FIELD_RENAMES: Array<{ from: string; @@ -43,7 +46,11 @@ const AUCTION_FIELD_RENAMES: Array<{ { from: 'passedQueue', to: 'passedAuctionPlayerQueue' }, { from: 'auctionRound', to: 'currentAuctionRound' }, { from: 'currentIndex', to: 'currentAuctionPlayerOrderIndex' }, - { from: 'bids', to: 'auctionBidHistory', transform: transformAuctionBidHistory }, + { + from: 'bids', + to: 'auctionBidHistory', + transform: transformAuctionBidHistory, + }, { from: 'currentBid', to: 'currentHighestBidPointAmount' }, { from: 'currentBidderTeamIndex', to: 'currentHighestBidderTeamIndex' }, { @@ -157,7 +164,8 @@ async function countDuplicateHistorySequences( const duplicates = new Set(); for await (const doc of collection.find({}).limit(limit ?? 0)) { const auctionId = stringifyId(doc.auctionId); - const sequence = typeof doc.sequence === 'number' ? doc.sequence : undefined; + const sequence = + typeof doc.sequence === 'number' ? doc.sequence : undefined; if (!auctionId || sequence === undefined) continue; const key = `${auctionId}:${sequence}`; diff --git a/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts b/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts index 24108c05..15eb0315 100644 --- a/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts +++ b/apps/api/src/modules/global/database/migrations/repair-limited-round-robin-finished-match.ts @@ -5,10 +5,7 @@ import { NestFactory } from '@nestjs/core'; import mongoose from 'mongoose'; import { readFile } from 'node:fs/promises'; import { resolve } from 'node:path'; -import { - ConnectionService, - resolveMongoDbName, -} from '../connection.service'; +import { ConnectionService, resolveMongoDbName } from '../connection.service'; import type { MatchDocument, MatchGameAssignment, @@ -214,12 +211,16 @@ async function main() { printPlan(options, match, codes, plan); if (options.dryRun) { - console.log('No writes were made. Re-run with --apply to update MongoDB.'); + console.log( + 'No writes were made. Re-run with --apply to update MongoDB.', + ); return; } const now = new Date(); - const session = await (await connectionService.getConnection()).startSession(); + const session = await ( + await connectionService.getConnection() + ).startSession(); try { await session.withTransaction(async () => { await applyTournamentCodeUpdates(plan, now, session); @@ -230,9 +231,9 @@ async function main() { status: 'finished', roundRobinMaxRounds: options.maxRounds, gameSchedule: plan.schedule, - tournamentCodeIds: [ - ...plan.usedCodeByOldGameNumber.values(), - ].map((code) => code._id), + tournamentCodeIds: [...plan.usedCodeByOldGameNumber.values()].map( + (code) => code._id, + ), resultPollState: { startedAt: match.resultPollState?.startedAt ?? now, lastPolledAt: now, @@ -423,7 +424,9 @@ function partitionIntoRounds( } if (!fillRound(0)) { - throw new Error('Could not partition result games into simultaneous rounds.'); + throw new Error( + 'Could not partition result games into simultaneous rounds.', + ); } return rounds; @@ -586,8 +589,7 @@ function buildSeriesResults(games: MatchGameResult[]): MatchSeriesResult[] { } return [...bySeries.values()].sort( (left, right) => - left.teamAIndex - right.teamAIndex || - left.teamBIndex - right.teamBIndex, + left.teamAIndex - right.teamAIndex || left.teamBIndex - right.teamBIndex, ); } diff --git a/apps/api/src/modules/global/database/migrations/run-auction-redis-field-rename.ts b/apps/api/src/modules/global/database/migrations/run-auction-redis-field-rename.ts index afba5e10..0d62b20a 100644 --- a/apps/api/src/modules/global/database/migrations/run-auction-redis-field-rename.ts +++ b/apps/api/src/modules/global/database/migrations/run-auction-redis-field-rename.ts @@ -219,9 +219,9 @@ async function listDuplicateHistorySequences( .toArray(); } -function printDuplicateHistorySequences(groups: Awaited< - ReturnType ->) { +function printDuplicateHistorySequences( + groups: Awaited>, +) { if (groups.length === 0) { console.log('No duplicate auctionHistory auctionId+sequence groups found.'); return; @@ -248,7 +248,8 @@ async function repairDuplicateHistorySequences( ): Promise { const historyCollection = db.collection('auctionHistory'); const auctionCollection = db.collection('auction'); - const affectedAuctionIds = await findAuctionIdsWithDuplicateHistorySequences(db); + const affectedAuctionIds = + await findAuctionIdsWithDuplicateHistorySequences(db); const stats: DuplicateSequenceRepairStats = { affectedAuctions: affectedAuctionIds.length, changedAuctionSequenceFields: 0, diff --git a/apps/api/src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts b/apps/api/src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts index 48754a6d..f9792ab4 100644 --- a/apps/api/src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts +++ b/apps/api/src/modules/global/database/migrations/run-tournament-code-unique-indexes.ts @@ -177,7 +177,9 @@ function parseArgs(argv: string[]): CliOptions { function parseCommitQuorum(value: string | undefined, label: string) { if (!value) { - throw new Error(`${label} requires a positive integer, majority, or votingMembers.`); + throw new Error( + `${label} requires a positive integer, majority, or votingMembers.`, + ); } if (value === 'majority' || value === 'votingMembers') return value; return parsePositiveInteger(value, label); @@ -230,9 +232,7 @@ function printDuplicateGroups(groups: TournamentCodeDuplicateGroupSummary[]) { kind: group.kind, loserCodes: group.losers.map((loser) => loser.code ?? '').join(', '), loserIds: group.losers.map((loser) => loser.id).join(', '), - loserStates: group.losers - .map((loser) => loser.state ?? '') - .join(', '), + loserStates: group.losers.map((loser) => loser.state ?? '').join(', '), })), ); } diff --git a/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts b/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts index 2016f542..6b878473 100644 --- a/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts +++ b/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts @@ -46,19 +46,20 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void { query[QUERY_PERFORMANCE_RECORDED] = false; }); - hookableSchema.post( - QUERY_OPERATION_REGEX, - function (result: unknown) { - recordQueryPerformance( - this as unknown as QueryWithPerformanceState, - result, - ); - }, - ); + hookableSchema.post(QUERY_OPERATION_REGEX, function (result: unknown) { + recordQueryPerformance( + this as unknown as QueryWithPerformanceState, + result, + ); + }); hookableSchema.post( QUERY_OPERATION_REGEX, - function (error: unknown, _result: unknown, next: (error: unknown) => void) { + function ( + error: unknown, + _result: unknown, + next: (error: unknown) => void, + ) { recordQueryPerformance( this as unknown as QueryWithPerformanceState, undefined, @@ -80,7 +81,11 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void { hookableSchema.post( 'aggregate', - function (error: unknown, _result: unknown, next: (error: unknown) => void) { + function ( + error: unknown, + _result: unknown, + next: (error: unknown) => void, + ) { recordAggregatePerformance( this as AggregateWithPerformanceState, undefined, @@ -164,8 +169,8 @@ export function countHydratedDocuments(result: unknown): number { function isHydratedDocument(value: unknown): boolean { return Boolean( value && - typeof value === 'object' && - '$__' in (value as Record), + typeof value === 'object' && + '$__' in (value as Record), ); } diff --git a/apps/api/src/modules/global/observability/new-relic.ts b/apps/api/src/modules/global/observability/new-relic.ts index 5d773976..1e3807a4 100644 --- a/apps/api/src/modules/global/observability/new-relic.ts +++ b/apps/api/src/modules/global/observability/new-relic.ts @@ -11,9 +11,7 @@ interface NewRelicCustomEventApi { eventType: string, attributes: Record, ): void; - addCustomAttributes( - attributes: Record, - ): void; + addCustomAttributes(attributes: Record): void; setTransactionName(name: string): void; } const agent = newrelicAgent as unknown as NewRelicCustomEventApi; diff --git a/apps/api/src/modules/global/observability/performance-observer.ts b/apps/api/src/modules/global/observability/performance-observer.ts index a41a256d..51509e5e 100644 --- a/apps/api/src/modules/global/observability/performance-observer.ts +++ b/apps/api/src/modules/global/observability/performance-observer.ts @@ -52,8 +52,7 @@ export interface ApiRequestPerformanceEvent { leanQueryCount: number; } -export interface MongooseQueryPerformanceEvent - extends MongooseQueryPerformance { +export interface MongooseQueryPerformanceEvent extends MongooseQueryPerformance { type: 'mongoose-query'; timestamp: string; requestId?: string; @@ -92,10 +91,7 @@ export function resolveApiPerformanceConfig( const enabled = readBoolean(env.API_PERF_OBSERVABILITY_ENABLED, false); return { enabled, - localEventsEnabled: readBoolean( - env.API_PERF_LOCAL_EVENTS_ENABLED, - enabled, - ), + localEventsEnabled: readBoolean(env.API_PERF_LOCAL_EVENTS_ENABLED, enabled), localEventFile: env.API_PERF_LOCAL_EVENT_FILE || '/tmp/lolympus-api-performance.ndjson', newRelicRequestEventsEnabled: readBoolean( diff --git a/apps/api/src/modules/global/redis/distributed-lock.service.ts b/apps/api/src/modules/global/redis/distributed-lock.service.ts index fbaa2ccd..fb2e0023 100644 --- a/apps/api/src/modules/global/redis/distributed-lock.service.ts +++ b/apps/api/src/modules/global/redis/distributed-lock.service.ts @@ -35,8 +35,7 @@ export interface RunWithDistributedLockOptions { lockRetryDelayMilliseconds?: number; } -export interface RunWithRenewedDistributedLockOptions - extends RunWithDistributedLockOptions { +export interface RunWithRenewedDistributedLockOptions extends RunWithDistributedLockOptions { lockRenewalIntervalMilliseconds: number; } @@ -55,14 +54,16 @@ export class DistributedLockService { ); const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID(); - const result = await this.redisService.raw().sendCommand([ - 'SET', - options.lockKey, - lockOwnershipToken, - 'NX', - 'PX', - String(options.lockExpirationDurationMilliseconds), - ]); + const result = await this.redisService + .raw() + .sendCommand([ + 'SET', + options.lockKey, + lockOwnershipToken, + 'NX', + 'PX', + String(options.lockExpirationDurationMilliseconds), + ]); if (String(result) !== 'OK') return null; return { @@ -76,34 +77,37 @@ export class DistributedLockService { public async releaseLockIfOwned( lockOwnership: DistributedLockOwnership, ): Promise { - const result = await this.redisService.raw().sendCommand([ - 'EVAL', - RELEASE_LOCK_IF_OWNED_SCRIPT, - '1', - lockOwnership.lockKey, - lockOwnership.lockOwnershipToken, - ]); + const result = await this.redisService + .raw() + .sendCommand([ + 'EVAL', + RELEASE_LOCK_IF_OWNED_SCRIPT, + '1', + lockOwnership.lockKey, + lockOwnership.lockOwnershipToken, + ]); return Number(result) === 1; } public async extendLockIfOwned( lockOwnership: DistributedLockOwnership, - lockExpirationDurationMilliseconds = - lockOwnership.lockExpirationDurationMilliseconds, + lockExpirationDurationMilliseconds = lockOwnership.lockExpirationDurationMilliseconds, ): Promise { this.assertPositiveDuration( lockExpirationDurationMilliseconds, 'lockExpirationDurationMilliseconds', ); - const result = await this.redisService.raw().sendCommand([ - 'EVAL', - EXTEND_LOCK_IF_OWNED_SCRIPT, - '1', - lockOwnership.lockKey, - lockOwnership.lockOwnershipToken, - String(lockExpirationDurationMilliseconds), - ]); + const result = await this.redisService + .raw() + .sendCommand([ + 'EVAL', + EXTEND_LOCK_IF_OWNED_SCRIPT, + '1', + lockOwnership.lockKey, + lockOwnership.lockOwnershipToken, + String(lockExpirationDurationMilliseconds), + ]); return Number(result) === 1; } diff --git a/apps/api/src/modules/global/redis/redis.module.ts b/apps/api/src/modules/global/redis/redis.module.ts index 205dd4e7..50d9d7ca 100644 --- a/apps/api/src/modules/global/redis/redis.module.ts +++ b/apps/api/src/modules/global/redis/redis.module.ts @@ -25,7 +25,9 @@ async function readFirstSecret( { provide: REDIS_CLIENT, inject: [SecretService], - useFactory: async (secretService: SecretService): Promise => { + useFactory: async ( + secretService: SecretService, + ): Promise => { await secretService.ready(); const [url, endpoint, username, password] = await Promise.all([ diff --git a/apps/api/src/modules/global/redis/redis.service.spec.ts b/apps/api/src/modules/global/redis/redis.service.spec.ts index 46aa02cf..07281081 100644 --- a/apps/api/src/modules/global/redis/redis.service.spec.ts +++ b/apps/api/src/modules/global/redis/redis.service.spec.ts @@ -6,15 +6,17 @@ function createRedisService(client: Record) { describe('RedisService stream pending recovery', () => { it('normalizes XAUTOCLAIM array replies into stream entries', async () => { - const sendCommand = jest.fn().mockResolvedValue([ - '0-0', - [ + const sendCommand = jest + .fn() + .mockResolvedValue([ + '0-0', [ - '1700000000000-0', - ['job', '{"kind":"poll-tournament-result"}', 'source', 'test'], + [ + '1700000000000-0', + ['job', '{"kind":"poll-tournament-result"}', 'source', 'test'], + ], ], - ], - ]); + ]); const service = createRedisService({ sendCommand }); await expect( diff --git a/apps/api/src/modules/global/redis/redis.service.ts b/apps/api/src/modules/global/redis/redis.service.ts index 71f1169a..666fab98 100644 --- a/apps/api/src/modules/global/redis/redis.service.ts +++ b/apps/api/src/modules/global/redis/redis.service.ts @@ -223,9 +223,7 @@ export class RedisService implements OnModuleDestroy { ])) as unknown; const responseItems = Array.isArray(response) ? response : []; - const rawMessages = Array.isArray(responseItems[1]) - ? responseItems[1] - : []; + const rawMessages = Array.isArray(responseItems[1]) ? responseItems[1] : []; return { nextStartId: String(responseItems[0] ?? '0-0'), @@ -258,7 +256,9 @@ export class RedisService implements OnModuleDestroy { return this.client.publish(channel, message); } - private normalizeClaimedStreamMessage(rawMessage: unknown): StreamEntry | null { + private normalizeClaimedStreamMessage( + rawMessage: unknown, + ): StreamEntry | null { if (Array.isArray(rawMessage)) { const [id, fields] = rawMessage; if (id === undefined) return null; diff --git a/apps/api/src/modules/legacy-import/match-builder.util.ts b/apps/api/src/modules/legacy-import/match-builder.util.ts index 6915ecc4..3b7b1d75 100644 --- a/apps/api/src/modules/legacy-import/match-builder.util.ts +++ b/apps/api/src/modules/legacy-import/match-builder.util.ts @@ -46,11 +46,13 @@ export function countKnownParticipants( ): { team100: number; team200: number; total: number } { const team100 = detail.info.participants.filter( (participant) => - participant.teamId === RIOT_BLUE_TEAM_ID && userByPuuid.has(participant.puuid), + 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), + participant.teamId === RIOT_RED_TEAM_ID && + userByPuuid.has(participant.puuid), ).length; return { team100, team200, total: team100 + team200 }; } @@ -78,13 +80,16 @@ export function buildParticipantsSnapshot( 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], + 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)); + .filter((participant): participant is MatchParticipant => + Boolean(participant), + ); } export function buildTeams( @@ -105,7 +110,9 @@ export function buildTeams( assignedPosition: resolveAssignedPosition(participant, user), }; }) - .filter((member): member is NonNullable => Boolean(member)); + .filter((member): member is NonNullable => + Boolean(member), + ); return { teamIndex, name: `${teamIndex}팀`, diff --git a/apps/api/src/modules/match-history/match-history.controller.ts b/apps/api/src/modules/match-history/match-history.controller.ts index 29d142ca..866a5957 100644 --- a/apps/api/src/modules/match-history/match-history.controller.ts +++ b/apps/api/src/modules/match-history/match-history.controller.ts @@ -3,9 +3,7 @@ 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 type { RiotJobPriority } from '../riot-job-queue/riot-job-queue.types'; import { MatchHistoryService } from './match-history.service'; interface RefreshBody { diff --git a/apps/api/src/modules/match-history/match-history.service.ts b/apps/api/src/modules/match-history/match-history.service.ts index c70900cd..fa343b4f 100644 --- a/apps/api/src/modules/match-history/match-history.service.ts +++ b/apps/api/src/modules/match-history/match-history.service.ts @@ -1,4 +1,8 @@ -import { BadRequestException, Injectable, NotFoundException } from '@nestjs/common'; +import { + BadRequestException, + Injectable, + NotFoundException, +} from '@nestjs/common'; import mongoose from 'mongoose'; import { ConnectionService } from '../global/database/connection.service'; import type { @@ -16,10 +20,7 @@ import { type RiotQueueGroup, type RiotRankFilter, } from '../riot/riot-queue.constants'; -import type { - RiotMatchDto, - RiotMatchParticipantDto, -} from '../riot/riot.types'; +import type { RiotMatchDto, RiotMatchParticipantDto } from '../riot/riot.types'; import type { ChampionStatsResponse, ChampionStatsRow, @@ -104,7 +105,10 @@ export class MatchHistoryService { fetchedAt: tier.fetchedAt.toISOString(), })), tierHistory: [...context.account.tierHistory] - .sort((left, right) => left.recordedAt.getTime() - right.recordedAt.getTime()) + .sort( + (left, right) => + left.recordedAt.getTime() - right.recordedAt.getTime(), + ) .map((entry) => ({ queueType: entry.queueType, tier: entry.tier, @@ -170,7 +174,11 @@ export class MatchHistoryService { seasonId: params.filters.seasonId, }); const { queueIds } = this.resolveQueueFilters(params.filters); - const limit = this.clampLimit(params.filters.limit, DEFAULT_SUMMARY_LIMIT, 50); + const limit = this.clampLimit( + params.filters.limit, + DEFAULT_SUMMARY_LIMIT, + 50, + ); const docs = await this.findStoredMatches({ context, queueIds, @@ -196,7 +204,11 @@ export class MatchHistoryService { seasonId: params.filters.seasonId, }); const { queueIds } = this.resolveQueueFilters(params.filters); - const limit = this.clampLimit(params.filters.limit, DEFAULT_RECENT_LIMIT, 30); + const limit = this.clampLimit( + params.filters.limit, + DEFAULT_RECENT_LIMIT, + 30, + ); const docs = await this.findStoredMatches({ context, queueIds, @@ -212,7 +224,10 @@ export class MatchHistoryService { return { matches: page, - nextCursor: views.length > limit ? page[page.length - 1]?.gameCreation ?? null : null, + nextCursor: + views.length > limit + ? (page[page.length - 1]?.gameCreation ?? null) + : null, lastFetchedAt: this.resolveLastFetchedAt(docs, context), season: context.season, }; @@ -455,8 +470,9 @@ export class MatchHistoryService { puuid: string, ): RiotMatchParticipantDto | null { return ( - match.info.participants.find((participant) => participant.puuid === puuid) ?? - null + match.info.participants.find( + (participant) => participant.puuid === puuid, + ) ?? null ); } @@ -570,7 +586,8 @@ export class MatchHistoryService { return { matchId: dto.metadata.matchId, queueId: dto.info.queueId, - queueLabel: RIOT_QUEUE_LABELS[dto.info.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, @@ -684,11 +701,15 @@ export class MatchHistoryService { return { puuid: participant.puuid, - gameName: participant.riotIdGameName || participant.summonerName || 'Unknown', + gameName: + participant.riotIdGameName || + participant.summonerName || + 'Unknown', tagLine: participant.riotIdTagLine || '', championId: participant.championId, championLevel: participant.champLevel, - teamPosition: participant.teamPosition || participant.individualPosition, + teamPosition: + participant.teamPosition || participant.individualPosition, kills: participant.kills, deaths: participant.deaths, assists: participant.assists, @@ -720,7 +741,9 @@ export class MatchHistoryService { })); } - private resolvePerks(participant: RiotMatchParticipantDto): RecentMatchView['perks'] { + private resolvePerks( + participant: RiotMatchParticipantDto, + ): RecentMatchView['perks'] { const primary = participant.perks.styles.find( (style) => style.description === 'primaryStyle', ); @@ -750,11 +773,19 @@ export class MatchHistoryService { ) as Partial>; } - private resolveTopChampions(views: RecentMatchView[]): RecentSummaryResponse['topChampions'] { - const byChampion = new Map(); + private resolveTopChampions( + views: RecentMatchView[], + ): RecentSummaryResponse['topChampions'] { + const byChampion = new Map< + number, + { games: number; wins: number; rating: number } + >(); for (const view of views) { - const stat = - byChampion.get(view.championId) ?? { games: 0, wins: 0, rating: 0 }; + 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; @@ -797,7 +828,8 @@ export class MatchHistoryService { participant.deaths, participant.assists, ); - const kp = teamKills > 0 ? (participant.kills + participant.assists) / teamKills : 0; + 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 = @@ -815,8 +847,13 @@ export class MatchHistoryService { ): 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; + .reduce( + (sum, candidate) => sum + candidate.totalDamageDealtToChampions, + 0, + ); + return teamDamage > 0 + ? participant.totalDamageDealtToChampions / teamDamage + : 0; } private resolveTotalCs(participant: RiotMatchParticipantDto): number { @@ -827,11 +864,16 @@ export class MatchHistoryService { match: RiotMatchDto, participant: RiotMatchParticipantDto, ): number { - return Math.max((participant.timePlayed || match.info.gameDuration) / 60, 1); + 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); + return deaths === 0 + ? kills + assists + : this.round((kills + assists) / deaths); } private resolveLastFetchedAt( @@ -841,9 +883,11 @@ export class MatchHistoryService { 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); + const oldest = docs.reduce( + (acc, doc) => + doc.fetchedAt.getTime() < acc.getTime() ? doc.fetchedAt : acc, + docs[0].fetchedAt, + ); return oldest.toISOString(); } @@ -858,14 +902,17 @@ export class MatchHistoryService { .map((row) => row.lastFetchedAt) .filter((value): value is Date => value instanceof Date) .reduce( - (acc, value) => - !acc || value.getTime() < acc.getTime() ? value : acc, + (acc, value) => (!acc || value.getTime() < acc.getTime() ? value : acc), null, ); return oldest?.toISOString() ?? null; } - private clampLimit(value: number | undefined, fallback: number, max: number): number { + 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)); } @@ -882,18 +929,12 @@ export class MatchHistoryService { return Math.round(value * 10) / 10; } - private numberField( - value: RiotMatchParticipantDto, - key: string, - ): number { + 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 { + private booleanField(value: RiotMatchParticipantDto, key: string): boolean { return value[key] === true; } } 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 index 1bfcae9d..58578d9b 100644 --- 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 @@ -8,7 +8,11 @@ import { RiotJobWorkerService } from './riot-job-worker.service'; import { RiotRefreshGateway } from './riot-refresh.gateway'; @Module({ - imports: [RiotModule, LegacyImportModule, forwardRef(() => TournamentResultModule)], + imports: [ + RiotModule, + LegacyImportModule, + forwardRef(() => TournamentResultModule), + ], controllers: [RiotJobQueueController], providers: [RiotJobQueueService, RiotJobWorkerService, RiotRefreshGateway], exports: [RiotJobQueueService], 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 index 3c416113..33b31ee2 100644 --- 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 @@ -95,7 +95,8 @@ export class RiotJobQueueService { jobId: existingJobId, queueGroup, alreadyQueued: true, - etaSeconds: existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, + etaSeconds: + existingStatus?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, queuePosition: existingStatus?.queuePosition ?? queuePosition, }); continue; @@ -127,7 +128,8 @@ export class RiotJobQueueService { jobId, queueGroup, alreadyQueued: true, - etaSeconds: status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, + etaSeconds: + status?.etaSeconds ?? queuePosition * RIOT_JOB_AVG_SECONDS, queuePosition: status?.queuePosition ?? queuePosition, }); continue; @@ -164,7 +166,10 @@ export class RiotJobQueueService { }); } - await this.setParent(parentJobId, subJobs.map((job) => job.jobId)); + await this.setParent( + parentJobId, + subJobs.map((job) => job.jobId), + ); if (params.priority === 'high' && needsNewJob) { await this.markRefreshRequested(context.user._id, context.account.puuid); } @@ -253,8 +258,8 @@ export class RiotJobQueueService { 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', + const done = subJobs.filter( + (job) => job.state === 'completed' || job.state === 'failed', ).length; const state = this.resolveParentState(subJobs); @@ -411,12 +416,14 @@ export class RiotJobQueueService { job: PollTournamentResultJob, deferUntilMs: number, ): Promise { - await this.redisService.raw().sendCommand([ - 'ZADD', - RIOT_JOB_SCHEDULED_ZSET, - String(deferUntilMs), - JSON.stringify(job), - ]); + await this.redisService + .raw() + .sendCommand([ + 'ZADD', + RIOT_JOB_SCHEDULED_ZSET, + String(deferUntilMs), + JSON.stringify(job), + ]); } private parseScheduledJob(value: string): PollTournamentResultJob | null { @@ -449,7 +456,10 @@ export class RiotJobQueueService { ); } - private async setParent(parentJobId: string, jobIds: string[]): Promise { + private async setParent( + parentJobId: string, + jobIds: string[], + ): Promise { await this.redisService.setJson( this.parentKey(parentJobId), jobIds, 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 index 45968dd0..da6d565e 100644 --- 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 @@ -1,7 +1,4 @@ -import type { - RiotPlatformRoute, - RiotRegionalRoute, -} from '../riot/riot.types'; +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'; diff --git a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts index 9f9c866b..1927caac 100644 --- a/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts +++ b/apps/api/src/modules/riot-job-queue/riot-job-worker.service.spec.ts @@ -21,14 +21,16 @@ function makeWorker() { deleteStreamEntries: jest.fn().mockResolvedValue(undefined), } as unknown as jest.Mocked; const distributedLockService = { - runWithRenewedLock: jest.fn().mockImplementation(async (options, operation) => - operation({ - lockKey: options.lockKey, - lockOwnershipToken: 'lock-owner', - lockExpirationDurationMilliseconds: - options.lockExpirationDurationMilliseconds, - }), - ), + runWithRenewedLock: jest + .fn() + .mockImplementation(async (options, operation) => + operation({ + lockKey: options.lockKey, + lockOwnershipToken: 'lock-owner', + lockExpirationDurationMilliseconds: + options.lockExpirationDurationMilliseconds, + }), + ), } as unknown as jest.Mocked; const jobQueueService = { markProcessing: jest.fn().mockResolvedValue(undefined), 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 index 02185c56..db565d41 100644 --- 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 @@ -275,10 +275,10 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { ): Promise<{ stream: string; message: StreamEntry } | null> { const result = await this.redisService.readGroup( stream, - RIOT_JOB_GROUP, - this.consumerIdentifier, - '>', - { count: 1, blockMs }, + RIOT_JOB_GROUP, + this.consumerIdentifier, + '>', + { count: 1, blockMs }, ); const message = result?.[0]?.messages[0]; return message ? { stream, message } : null; 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 index 477fd717..da75a504 100644 --- a/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts +++ b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts @@ -70,7 +70,10 @@ export class RiotRefreshGateway { if (typeof payload?.puuid === 'string' && payload.puuid.trim()) { rooms.push(`puuid:${payload.puuid.trim()}`); } - if (typeof payload?.parentJobId === 'string' && payload.parentJobId.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 index 0b379dca..fe8ccd15 100644 --- a/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts +++ b/apps/api/src/modules/riot/riot-account-enrichment.service.spec.ts @@ -101,7 +101,7 @@ function makeService(overrides?: { Promise.resolve({ riotPlatform: 'kr', riotRegion: 'asia', - }), + }), }), }), }); @@ -198,65 +198,64 @@ describe('RiotAccountEnrichmentService', () => { masteryService, recentMatchesService, recentStatsService, - } = - makeService({ - user, - summoner: { - getByPuuid: jest.fn().mockResolvedValue({ + } = 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', - 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, - }); + 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, diff --git a/apps/api/src/modules/riot/riot-ddragon.service.spec.ts b/apps/api/src/modules/riot/riot-ddragon.service.spec.ts index be6e3c7a..9dc34a79 100644 --- a/apps/api/src/modules/riot/riot-ddragon.service.spec.ts +++ b/apps/api/src/modules/riot/riot-ddragon.service.spec.ts @@ -148,14 +148,18 @@ describe('RiotDdragonService', () => { 'ddragon:manifest:v5:ko_KR', expect.objectContaining({ summonerSpells: expect.objectContaining({ - '4': expect.objectContaining({ description: '커서 방향으로 순간이동합니다.' }), + '4': expect.objectContaining({ + description: '커서 방향으로 순간이동합니다.', + }), }), runesReforged: expect.arrayContaining([ expect.objectContaining({ slots: expect.arrayContaining([ expect.objectContaining({ runes: expect.arrayContaining([ - expect.objectContaining({ longDesc: expect.stringContaining('기본 공격') }), + expect.objectContaining({ + longDesc: expect.stringContaining('기본 공격'), + }), ]), }), ]), diff --git a/apps/api/src/modules/riot/riot-ddragon.service.ts b/apps/api/src/modules/riot/riot-ddragon.service.ts index cff9ab2c..64b5f11c 100644 --- a/apps/api/src/modules/riot/riot-ddragon.service.ts +++ b/apps/api/src/modules/riot/riot-ddragon.service.ts @@ -114,7 +114,9 @@ export class RiotDdragonService { constructor(private readonly redisService: RedisService) {} - public async getManifest(locale: string = DEFAULT_LOCALE): Promise { + public async getManifest( + locale: string = DEFAULT_LOCALE, + ): Promise { const normalizedLocale = normalizeLocale(locale); const cacheKey = manifestCacheKey(normalizedLocale); @@ -139,12 +141,14 @@ export class RiotDdragonService { private async buildManifest(locale: string): Promise { const version = await this.fetchLatestVersion(); - const [champions, summonerSpells, runesReforged, items] = await Promise.all([ - this.fetchChampionMap(version, locale), - this.fetchSummonerSpellMap(version, locale), - this.fetchRuneStyles(version, locale), - this.fetchItemMap(version, locale), - ]); + const [champions, summonerSpells, runesReforged, items] = await Promise.all( + [ + this.fetchChampionMap(version, locale), + this.fetchSummonerSpellMap(version, locale), + this.fetchRuneStyles(version, locale), + this.fetchItemMap(version, locale), + ], + ); return { version, cdn: DDRAGON_CDN, @@ -158,7 +162,9 @@ export class RiotDdragonService { } private async fetchLatestVersion(): Promise { - const versions = await this.fetchJson(`${DDRAGON_BASE}/api/versions.json`); + 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.'); } @@ -219,7 +225,9 @@ export class RiotDdragonService { const url = `${DDRAGON_CDN}/${version}/data/${locale}/runesReforged.json`; const payload = await this.fetchJson(url); if (!Array.isArray(payload)) { - throw new Error(`ddragon runesReforged.json response is malformed (${url}).`); + throw new Error( + `ddragon runesReforged.json response is malformed (${url}).`, + ); } return payload @@ -229,8 +237,7 @@ export class RiotDdragonService { key: style.key, icon: style.icon, name: style.name, - shortDesc: - typeof style.shortDesc === 'string' ? style.shortDesc : '', + shortDesc: typeof style.shortDesc === 'string' ? style.shortDesc : '', longDesc: typeof style.longDesc === 'string' ? style.longDesc : '', slots: (style.slots ?? []).map((slot) => ({ runes: (slot.runes ?? []) @@ -290,9 +297,7 @@ export class RiotDdragonService { signal: controller.signal, }); if (!response.ok) { - throw new Error( - `ddragon request failed (${response.status}): ${url}`, - ); + throw new Error(`ddragon request failed (${response.status}): ${url}`); } return (await response.json()) as T; } catch (err) { diff --git a/apps/api/src/modules/riot/riot-league.service.ts b/apps/api/src/modules/riot/riot-league.service.ts index 3c3003d1..8588cae6 100644 --- a/apps/api/src/modules/riot/riot-league.service.ts +++ b/apps/api/src/modules/riot/riot-league.service.ts @@ -1,9 +1,6 @@ import { Injectable } from '@nestjs/common'; import { RiotClientService } from './riot.client.service'; -import { - RiotLeagueEntryDto, - RiotPlatformLookupOptions, -} from './riot.types'; +import { RiotLeagueEntryDto, RiotPlatformLookupOptions } from './riot.types'; @Injectable() export class RiotLeagueService { diff --git a/apps/api/src/modules/riot/riot-match.service.ts b/apps/api/src/modules/riot/riot-match.service.ts index 7dfb0020..0e415ad8 100644 --- a/apps/api/src/modules/riot/riot-match.service.ts +++ b/apps/api/src/modules/riot/riot-match.service.ts @@ -98,9 +98,7 @@ function validateMatchIdsLookupOptions( 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(', ')}`, - ); + throw new RangeError(`type must be one of: ${RIOT_MATCH_TYPES.join(', ')}`); } if ( @@ -278,7 +276,9 @@ function parseTimelineParticipant( index: number, ): RiotMatchTimelineParticipantDto { if (!isRecord(value)) { - throw new TypeError(`timeline.info.participants[${index}] must be an object.`); + throw new TypeError( + `timeline.info.participants[${index}] must be an object.`, + ); } return { @@ -287,7 +287,10 @@ function parseTimelineParticipant( value.participantId, `timeline.info.participants[${index}].participantId`, ), - puuid: requireString(value.puuid, `timeline.info.participants[${index}].puuid`), + puuid: requireString( + value.puuid, + `timeline.info.participants[${index}].puuid`, + ), }; } @@ -589,7 +592,10 @@ function parseParticipant( }; } -function parsePerks(value: unknown, participantIndex: number): RiotMatchPerksDto { +function parsePerks( + value: unknown, + participantIndex: number, +): RiotMatchPerksDto { if (!isRecord(value)) { throw new TypeError( `participants[${participantIndex}].perks must be an object.`, @@ -732,7 +738,9 @@ function parseBan( banIndex: number, ): RiotMatchBanDto { if (!isRecord(value)) { - throw new TypeError(`teams[${teamIndex}].bans[${banIndex}] must be an object.`); + throw new TypeError( + `teams[${teamIndex}].bans[${banIndex}] must be an object.`, + ); } return { @@ -781,7 +789,9 @@ function parseObjective( key: keyof RiotMatchObjectivesDto, ): RiotMatchObjectiveDto { if (!isRecord(value)) { - throw new TypeError(`teams[${teamIndex}].objectives.${key} must be an object.`); + throw new TypeError( + `teams[${teamIndex}].objectives.${key} must be an object.`, + ); } return { diff --git a/apps/api/src/modules/riot/riot-queue.constants.ts b/apps/api/src/modules/riot/riot-queue.constants.ts index 70b3ae05..16796f98 100644 --- a/apps/api/src/modules/riot/riot-queue.constants.ts +++ b/apps/api/src/modules/riot/riot-queue.constants.ts @@ -84,5 +84,10 @@ export function isRiotQueueGroup(value: string): value is RiotQueueGroup { } export function isRiotRankFilter(value: string): value is RiotRankFilter { - return value === 'all' || value === 'solo' || value === 'flex' || value === 'normal'; + return ( + value === 'all' || + value === 'solo' || + value === 'flex' || + value === 'normal' + ); } diff --git a/apps/api/src/modules/riot/riot-recent-matches.service.ts b/apps/api/src/modules/riot/riot-recent-matches.service.ts index 9dd6112e..7ba6114e 100644 --- a/apps/api/src/modules/riot/riot-recent-matches.service.ts +++ b/apps/api/src/modules/riot/riot-recent-matches.service.ts @@ -150,13 +150,16 @@ async function runWithConcurrency( 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); - } - }); + 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.ts b/apps/api/src/modules/riot/riot-recent-stats.service.ts index 62886925..6e0bc48f 100644 --- a/apps/api/src/modules/riot/riot-recent-stats.service.ts +++ b/apps/api/src/modules/riot/riot-recent-stats.service.ts @@ -44,17 +44,29 @@ export class RiotRecentStatsService { ); for (const match of filteredMatches) { - const participant = match.info.participants.find((entry) => entry.puuid === puuid); + const participant = match.info.participants.find( + (entry) => entry.puuid === puuid, + ); if (!participant) continue; - accumulateAggregate(overall, participant, match.info.gameCreation, match.info.gameDuration); + 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); + accumulateAggregate( + aggregate, + participant, + match.info.gameCreation, + match.info.gameDuration, + ); } if (overall.games === 0) { @@ -133,7 +145,8 @@ function finalizeAggregate(aggregate: Aggregate): RiotLaneStats { 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 rightLastPlayed = + aggregate.lastPlayedAtByChampion.get(right[0]) ?? 0; const leftLastPlayed = aggregate.lastPlayedAtByChampion.get(left[0]) ?? 0; if (rightLastPlayed !== leftLastPlayed) { return rightLastPlayed - leftLastPlayed; diff --git a/apps/api/src/modules/riot/riot-summoner.service.ts b/apps/api/src/modules/riot/riot-summoner.service.ts index 30248294..c5dd520b 100644 --- a/apps/api/src/modules/riot/riot-summoner.service.ts +++ b/apps/api/src/modules/riot/riot-summoner.service.ts @@ -1,9 +1,6 @@ import { Injectable } from '@nestjs/common'; import { RiotClientService } from './riot.client.service'; -import { - RiotPlatformLookupOptions, - RiotSummonerDto, -} from './riot.types'; +import { RiotPlatformLookupOptions, RiotSummonerDto } from './riot.types'; @Injectable() export class RiotSummonerService { diff --git a/apps/api/src/modules/riot/riot-webhook.controller.spec.ts b/apps/api/src/modules/riot/riot-webhook.controller.spec.ts index 78bbd913..71ac2bb6 100644 --- a/apps/api/src/modules/riot/riot-webhook.controller.spec.ts +++ b/apps/api/src/modules/riot/riot-webhook.controller.spec.ts @@ -17,8 +17,12 @@ describe('RiotWebhookController', () => { }); 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 logSpy = jest + .spyOn(console, 'log') + .mockImplementation(() => undefined); + const dirSpy = jest + .spyOn(console, 'dir') + .mockImplementation(() => undefined); const request = { method: 'POST', originalUrl: '/riot/webhooks/tournament', diff --git a/apps/api/src/modules/riot/riot-webhook.controller.ts b/apps/api/src/modules/riot/riot-webhook.controller.ts index 689b2b2e..a64a691e 100644 --- a/apps/api/src/modules/riot/riot-webhook.controller.ts +++ b/apps/api/src/modules/riot/riot-webhook.controller.ts @@ -1,10 +1,4 @@ -import { - All, - Controller, - HttpCode, - HttpStatus, - Req, -} from '@nestjs/common'; +import { All, Controller, HttpCode, HttpStatus, Req } from '@nestjs/common'; import type { Request } from 'express'; import { AllowPublicAccess } from '../auth/allow-public-access.decorator'; diff --git a/apps/api/src/modules/riot/riot.types.ts b/apps/api/src/modules/riot/riot.types.ts index 7119c6a3..f3f806ae 100644 --- a/apps/api/src/modules/riot/riot.types.ts +++ b/apps/api/src/modules/riot/riot.types.ts @@ -263,7 +263,10 @@ export interface RiotMatchTimelineInfoDto extends Record { participants?: RiotMatchTimelineParticipantDto[]; } -export interface RiotMatchTimelineParticipantDto extends Record { +export interface RiotMatchTimelineParticipantDto extends Record< + string, + unknown +> { participantId: number; puuid: string; } @@ -294,8 +297,10 @@ export interface RiotMatchTimelineEventDto extends Record { victimId?: number; } -export interface RiotMatchTimelineParticipantFrameDto - extends Record { +export interface RiotMatchTimelineParticipantFrameDto extends Record< + string, + unknown +> { participantId: number; totalGold: number; xp: number; diff --git a/apps/api/src/modules/tournament-code/round-robin.util.spec.ts b/apps/api/src/modules/tournament-code/round-robin.util.spec.ts index 50705065..a00ffae2 100644 --- a/apps/api/src/modules/tournament-code/round-robin.util.spec.ts +++ b/apps/api/src/modules/tournament-code/round-robin.util.spec.ts @@ -8,9 +8,7 @@ import { describe('round-robin util', () => { it('builds every team pair in lexicographic order', () => { - expect(roundRobinPairs(2)).toEqual([ - { teamAIndex: 1, teamBIndex: 2 }, - ]); + expect(roundRobinPairs(2)).toEqual([{ teamAIndex: 1, teamBIndex: 2 }]); expect(roundRobinPairs(4)).toEqual([ { teamAIndex: 1, teamBIndex: 2 }, { teamAIndex: 1, teamBIndex: 3 }, @@ -33,8 +31,9 @@ describe('round-robin util', () => { for (const roundNumber of [1, 2, 3, 4, 5]) { const round = schedule.filter((game) => game.roundNumber === roundNumber); expect(round).toHaveLength(3); - expect(new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex]))) - .toHaveProperty('size', 6); + expect( + new Set(round.flatMap((game) => [game.teamAIndex, game.teamBIndex])), + ).toHaveProperty('size', 6); } }); diff --git a/apps/api/src/modules/tournament-code/round-robin.util.ts b/apps/api/src/modules/tournament-code/round-robin.util.ts index 3068fd7a..5100f0e6 100644 --- a/apps/api/src/modules/tournament-code/round-robin.util.ts +++ b/apps/api/src/modules/tournament-code/round-robin.util.ts @@ -59,10 +59,7 @@ export function roundRobinGameSchedule( typeof options.maxRounds === 'number' && Number.isFinite(options.maxRounds) ? Math.floor(options.maxRounds) : fullRoundCount; - const roundLimit = Math.max( - 0, - Math.min(fullRoundCount, requestedRoundCount), - ); + const roundLimit = Math.max(0, Math.min(fullRoundCount, requestedRoundCount)); if (roundLimit === 0) return []; const bye = 0; diff --git a/apps/api/src/modules/tournament-code/tournament-code-vendor.service.spec.ts b/apps/api/src/modules/tournament-code/tournament-code-vendor.service.spec.ts index 9db7e042..5d3108b3 100644 --- a/apps/api/src/modules/tournament-code/tournament-code-vendor.service.spec.ts +++ b/apps/api/src/modules/tournament-code/tournament-code-vendor.service.spec.ts @@ -46,9 +46,7 @@ describe('TournamentCodeVendorService', () => { ok: true, status: 200, json: jest.fn().mockResolvedValue({ - tournament_code_list: [ - 'KR05090-85d64e26-0a7d-438b-9ada-11784e46add3', - ], + tournament_code_list: ['KR05090-85d64e26-0a7d-438b-9ada-11784e46add3'], }), }); const service = new TournamentCodeVendorService(); diff --git a/apps/api/src/modules/user/user.controller.ts b/apps/api/src/modules/user/user.controller.ts index 9b614966..7731c08a 100644 --- a/apps/api/src/modules/user/user.controller.ts +++ b/apps/api/src/modules/user/user.controller.ts @@ -13,10 +13,7 @@ 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 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'; @@ -56,7 +53,10 @@ export class UserController { @Body() body: RefreshRiotAccountDto, ) { const resolvedUser = - user ?? (req.identity ? await this.findUserByIdentityAndPuuid(req.identity, puuid) : null); + user ?? + (req.identity + ? await this.findUserByIdentityAndPuuid(req.identity, puuid) + : null); if (!resolvedUser) { throw new UnauthorizedException('Authentication required.'); } diff --git a/apps/api/src/scripts/api-performance-report.spec.ts b/apps/api/src/scripts/api-performance-report.spec.ts index 78220a8b..5ce74487 100644 --- a/apps/api/src/scripts/api-performance-report.spec.ts +++ b/apps/api/src/scripts/api-performance-report.spec.ts @@ -123,9 +123,8 @@ describe('api performance report generation', () => { expect(rows).toHaveLength(3); expect( - rows.find( - (row) => row.route === '/communities/:communityId/matches', - )?.status, + rows.find((row) => row.route === '/communities/:communityId/matches') + ?.status, ).toBe('document-heavy'); expect(rows.filter((row) => row.status === 'no-samples')).toHaveLength(2); }); @@ -208,11 +207,11 @@ describe('api performance report generation', () => { expect(buildNewRelicCustomEventNrql('lolympus-api', '1 day ago')).toContain( 'FACET method, route', ); - expect( - buildNewRelicTransactionNrql('lolympus-api', '1 day ago'), - ).toContain('FROM Transaction'); - expect( - buildNewRelicTransactionNrql('lolympus-api', '1 day ago'), - ).toContain('FACET name'); + expect(buildNewRelicTransactionNrql('lolympus-api', '1 day ago')).toContain( + 'FROM Transaction', + ); + expect(buildNewRelicTransactionNrql('lolympus-api', '1 day ago')).toContain( + 'FACET name', + ); }); }); diff --git a/apps/api/src/scripts/api-performance-report.ts b/apps/api/src/scripts/api-performance-report.ts index ce47931a..20df9e8c 100644 --- a/apps/api/src/scripts/api-performance-report.ts +++ b/apps/api/src/scripts/api-performance-report.ts @@ -7,10 +7,7 @@ import type { ApiRequestPerformanceEvent, } from '../modules/global/observability/performance-observer'; -export type ReportSource = - | 'local' - | 'newrelic-custom' - | 'newrelic-transaction'; +export type ReportSource = 'local' | 'newrelic-custom' | 'newrelic-transaction'; export interface ApiRoute { method: string; @@ -143,7 +140,8 @@ export function buildEndpointReportFromLocalEvents(params: { const rowsByKey = new Map(); for (const route of params.routes) { - const events = requestsByRoute.get(routeKey(route.method, route.route)) ?? []; + const events = + requestsByRoute.get(routeKey(route.method, route.route)) ?? []; rowsByKey.set( routeKey(route.method, route.route), summarizeRequestEvents(route, events, { @@ -538,8 +536,7 @@ function classifyRow( (row.docsReturnedP95 !== null && row.docsReturnedP95 > options.docsReturnedP95Budget) || (row.hydratedDocsReturnedP95 !== null && - row.hydratedDocsReturnedP95 > - options.hydratedDocsReturnedP95Budget) + row.hydratedDocsReturnedP95 > options.hydratedDocsReturnedP95Budget) ) { return 'document-heavy'; } @@ -615,7 +612,10 @@ function max(values: number[]): number | null { return Math.max(...values); } -function percentileField(value: unknown, percentileValue: number): number | null { +function percentileField( + value: unknown, + percentileValue: number, +): number | null { if (!value || typeof value !== 'object') return null; const map = value as Record; return numberOrNull(map[String(percentileValue)] ?? map[percentileValue]); @@ -654,7 +654,11 @@ function parseArgs(argv: string[]): ReportOptions { args.set(key, rawValue ?? true); } - const source = stringArg(args, 'source', defaultReportSource()) as ReportSource; + const source = stringArg( + args, + 'source', + defaultReportSource(), + ) as ReportSource; return { source, rootDir: path.resolve( @@ -739,8 +743,7 @@ async function buildReport(options: ReportOptions): Promise { events: await readLocalPerformanceEvents(options.inputFile), p95BudgetMs: options.p95BudgetMs, docsReturnedP95Budget: options.docsReturnedP95Budget, - hydratedDocsReturnedP95Budget: - options.hydratedDocsReturnedP95Budget, + hydratedDocsReturnedP95Budget: options.hydratedDocsReturnedP95Budget, }) : await fetchNewRelicEndpointRows({ source: options.source, @@ -753,8 +756,7 @@ async function buildReport(options: ReportOptions): Promise { since: options.since, p95BudgetMs: options.p95BudgetMs, docsReturnedP95Budget: options.docsReturnedP95Budget, - hydratedDocsReturnedP95Budget: - options.hydratedDocsReturnedP95Budget, + hydratedDocsReturnedP95Budget: options.hydratedDocsReturnedP95Budget, }); const notes = options.source === 'newrelic-custom' && measuredRows.length === 0 diff --git a/apps/api/src/scripts/auction-redis-rehearsal.ts b/apps/api/src/scripts/auction-redis-rehearsal.ts index 3364099e..d36ad8f2 100644 --- a/apps/api/src/scripts/auction-redis-rehearsal.ts +++ b/apps/api/src/scripts/auction-redis-rehearsal.ts @@ -11,7 +11,10 @@ import { AuctionRedisCommandService } from '../modules/auction/redis/auction-red import { buildAuctionRedisKeys } from '../modules/auction/redis/auction-redis.keys'; import { AuctionRedisService } from '../modules/auction/redis/auction-redis.service'; import { AuctionRedisStateReaderService } from '../modules/auction/redis/auction-redis-state-reader.service'; -import { ConnectionService, resolveMongoDbName } from '../modules/global/database/connection.service'; +import { + ConnectionService, + resolveMongoDbName, +} from '../modules/global/database/connection.service'; import { assertDistinctRedisInstances, resolveRedisClientOptions, @@ -69,7 +72,10 @@ async function readFirstSecret( } function requireSafeNodeEnv(): void { - if (process.env.NODE_ENV === 'prod' && process.env.ALLOW_PROD_AUCTION_REHEARSAL !== 'true') { + if ( + process.env.NODE_ENV === 'prod' && + process.env.ALLOW_PROD_AUCTION_REHEARSAL !== 'true' + ) { throw new Error( 'Refusing to run auction Redis rehearsal against prod. Set ALLOW_PROD_AUCTION_REHEARSAL=true only for an explicit production drill.', ); @@ -85,15 +91,20 @@ async function createRedisClientFromSecrets( kind: 'common' | 'auction', ): Promise { const prefix = kind === 'auction' ? 'AUCTION_REDIS' : 'REDIS'; - const urlKeys = kind === 'auction' ? [`${prefix}_URL`] : ['REDIS_URL', 'GARNET_URL']; + const urlKeys = + kind === 'auction' ? [`${prefix}_URL`] : ['REDIS_URL', 'GARNET_URL']; const endpointKeys = - kind === 'auction' ? [`${prefix}_ENDPOINT`] : ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']; + kind === 'auction' + ? [`${prefix}_ENDPOINT`] + : ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']; const usernameKeys = kind === 'auction' ? [`${prefix}_USERNAME`, `${prefix}_USERID`] : ['REDIS_USERNAME', 'REDIS_USERID', 'GARNET_USERNAME', 'GARNET_USERID']; const passwordKeys = - kind === 'auction' ? [`${prefix}_PASSWORD`] : ['REDIS_PASSWORD', 'GARNET_PASSWORD']; + kind === 'auction' + ? [`${prefix}_PASSWORD`] + : ['REDIS_PASSWORD', 'GARNET_PASSWORD']; const [url, endpoint, username, password] = await Promise.all([ readFirstSecret(secretService, urlKeys), readFirstSecret(secretService, endpointKeys), @@ -117,20 +128,17 @@ async function createRedisClientFromSecrets( return client; } -async function assertRedisTopology( - secretService: SecretService, -): Promise<{ auctionRedisClient: RedisClient; commonRedisClient: RedisClient }> { - const [ - redisUrl, - redisEndpoint, - auctionRedisUrl, - auctionRedisEndpoint, - ] = await Promise.all([ - readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']), - readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']), - readFirstSecret(secretService, ['AUCTION_REDIS_URL']), - readFirstSecret(secretService, ['AUCTION_REDIS_ENDPOINT']), - ]); +async function assertRedisTopology(secretService: SecretService): Promise<{ + auctionRedisClient: RedisClient; + commonRedisClient: RedisClient; +}> { + const [redisUrl, redisEndpoint, auctionRedisUrl, auctionRedisEndpoint] = + await Promise.all([ + readFirstSecret(secretService, ['REDIS_URL', 'GARNET_URL']), + readFirstSecret(secretService, ['REDIS_ENDPOINT', 'GARNET_ENDPOINT']), + readFirstSecret(secretService, ['AUCTION_REDIS_URL']), + readFirstSecret(secretService, ['AUCTION_REDIS_ENDPOINT']), + ]); const redisOptions = resolveRedisClientOptions({ endpoint: redisEndpoint, endpointEnvName: 'REDIS_ENDPOINT', @@ -162,49 +170,51 @@ async function cleanupRedis( matchId: mongoose.Types.ObjectId, ): Promise { const keys = buildAuctionRedisKeys(matchId.toString()); - await auctionRedisService.raw().sendCommand([ - 'DEL', - keys.liveStateKey, - keys.structureStateKey, - keys.appliedTransitionIdsKey, - keys.bidHistoryKey, - keys.bidRequestResultsKey, - keys.bidRequestResultOrderKey, - keys.actionRequestResultsKey, - keys.actionRequestResultOrderKey, - keys.rehydrateLockKey, - keys.stateTransitionLockKey, - ]); - await auctionRedisService.raw().sendCommand([ - 'ZREM', - keys.deadlineQueueKey, - matchId.toString(), - ]); + await auctionRedisService + .raw() + .sendCommand([ + 'DEL', + keys.liveStateKey, + keys.structureStateKey, + keys.appliedTransitionIdsKey, + keys.bidHistoryKey, + keys.bidRequestResultsKey, + keys.bidRequestResultOrderKey, + keys.actionRequestResultsKey, + keys.actionRequestResultOrderKey, + keys.rehydrateLockKey, + keys.stateTransitionLockKey, + ]); + await auctionRedisService + .raw() + .sendCommand(['ZREM', keys.deadlineQueueKey, matchId.toString()]); let cursor = '0'; do { - const reply = await auctionRedisService.raw().sendCommand([ - 'SCAN', - cursor, - 'MATCH', - `${keys.durabilityPayloadKeyPrefix}*`, - 'COUNT', - '100', - ]); + const reply = await auctionRedisService + .raw() + .sendCommand([ + 'SCAN', + cursor, + 'MATCH', + `${keys.durabilityPayloadKeyPrefix}*`, + 'COUNT', + '100', + ]); if (!Array.isArray(reply) || reply.length < 2) return; cursor = String(reply[0]); const payloadKeys = Array.isArray(reply[1]) ? reply[1].map(String) : []; if (payloadKeys.length > 0) { - await auctionRedisService.raw().sendCommand([ - 'ZREM', - keys.durabilityRetryQueueKey, - ...payloadKeys, - ]); - await auctionRedisService.raw().sendCommand([ - 'ZREM', - keys.durabilityDeadLetterQueueKey, - ...payloadKeys, - ]); + await auctionRedisService + .raw() + .sendCommand(['ZREM', keys.durabilityRetryQueueKey, ...payloadKeys]); + await auctionRedisService + .raw() + .sendCommand([ + 'ZREM', + keys.durabilityDeadLetterQueueKey, + ...payloadKeys, + ]); await auctionRedisService.raw().sendCommand(['DEL', ...payloadKeys]); } } while (cursor !== '0'); @@ -236,7 +246,8 @@ async function cleanupMongo( resources: RehearsalResources, ): Promise { const AuctionModel = await connectionService.getModel('auction'); - const AuctionHistoryModel = await connectionService.getModel('auctionHistory'); + const AuctionHistoryModel = + await connectionService.getModel('auctionHistory'); const SideEffectModel = await connectionService.getModel( 'auctionSideEffectApplication', ); @@ -325,7 +336,9 @@ async function seedMatch( userId, })), scheduledAt: new Date(Date.now() + 60_000), - shortCode: `R${Math.random().toString(36).slice(2, 6)}`.slice(0, 6).toUpperCase(), + shortCode: `R${Math.random().toString(36).slice(2, 6)}` + .slice(0, 6) + .toUpperCase(), status: 'recruiting', title: `${REHEARSAL_PREFIX}-${suffix}`, }); @@ -371,7 +384,8 @@ function assertState( state: Record | null, expectedPhase: string, ): Record { - if (!state) throw new Error(`Expected auction state phase=${expectedPhase}, got null`); + if (!state) + throw new Error(`Expected auction state phase=${expectedPhase}, got null`); if (state.phase !== expectedPhase) { throw new Error( `Expected auction phase=${expectedPhase}, got ${String(state.phase)}`, @@ -390,7 +404,9 @@ async function main(): Promise { const configService = new ConfigService(process.env); const secretService = new SecretService(configService); await secretService.ready(); - logStep(`secrets loaded, nodeEnv=${process.env.NODE_ENV}, db=${resolveMongoDbName()}`); + logStep( + `secrets loaded, nodeEnv=${process.env.NODE_ENV}, db=${resolveMongoDbName()}`, + ); const { auctionRedisClient, commonRedisClient } = await assertRedisTopology(secretService); @@ -498,7 +514,8 @@ async function main(): Promise { matchId: resources.matchId, teamIndex: 1, }); - if (!('revision' in bidResult)) throw new Error('Bid did not return state.'); + if (!('revision' in bidResult)) + throw new Error('Bid did not return state.'); logStep('bid OK'); await auctionService.markSold({ @@ -537,12 +554,16 @@ async function main(): Promise { ), 'bidding', ); - const secondBiddingKeys = buildAuctionRedisKeys(resources.matchId.toString()); - const queuedDeadlineScore = await auctionRedisService.raw().sendCommand([ - 'ZSCORE', - secondBiddingKeys.deadlineQueueKey, + const secondBiddingKeys = buildAuctionRedisKeys( resources.matchId.toString(), - ]); + ); + const queuedDeadlineScore = await auctionRedisService + .raw() + .sendCommand([ + 'ZSCORE', + secondBiddingKeys.deadlineQueueKey, + resources.matchId.toString(), + ]); if (!queuedDeadlineScore) { throw new Error( `Expected deadline queue item after second open-bidding, state deadline=${String( @@ -567,7 +588,8 @@ async function main(): Promise { communityId: resources.communityId, matchId: resources.matchId, }); - const undoTarget = historyBeforeUndo[historyBeforeUndo.length - 1]?.sequence; + const undoTarget = + historyBeforeUndo[historyBeforeUndo.length - 1]?.sequence; if (!undoTarget) throw new Error('No history sequence to undo.'); await auctionService.undoTo({ auctionActionRequestId: randomUUID(), @@ -584,9 +606,10 @@ async function main(): Promise { matchId: resources.matchId, }); await flushDurability(durabilityScheduler); - const resetState = await auctionRedisStateReaderService.readAuctionStateView( - resources.matchId.toString(), - ); + const resetState = + await auctionRedisStateReaderService.readAuctionStateView( + resources.matchId.toString(), + ); if (resetState) { throw new Error( `Expected reset to clear Redis state, got phase=${String(resetState.phase)}`, @@ -635,9 +658,11 @@ async function main(): Promise { } } -void main().then(() => { - process.exit(0); -}).catch((error) => { - console.error('[auction-rehearsal] FAILED:', error); - process.exit(1); -}); +void main() + .then(() => { + process.exit(0); + }) + .catch((error) => { + console.error('[auction-rehearsal] FAILED:', error); + process.exit(1); + }); diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts index 458e8cf6..0d7e7627 100644 --- a/apps/api/src/seed.ts +++ b/apps/api/src/seed.ts @@ -689,14 +689,14 @@ function createStaffRiotAccount( matchIds: [], recentStatsSummary: createRecentStatsSummary( { - games: 12, - wins: 7, - losses: 5, - avgKills: 5.1, - avgDeaths: 4.3, - avgAssists: 7.4, - avgCs: 167, - mostPlayedChampionIds: ['Orianna', 'JarvanIV'], + games: 12, + wins: 7, + losses: 5, + avgKills: 5.1, + avgDeaths: 4.3, + avgAssists: 7.4, + avgCs: 167, + mostPlayedChampionIds: ['Orianna', 'JarvanIV'], }, 'MID', ), @@ -751,8 +751,7 @@ function createRecentStatsSummary( avgDeaths: input.avgDeaths, avgAssists: input.avgAssists, avgCs: input.avgCs, - avgCsPerMin: - input.avgCsPerMin ?? Math.round((input.avgCs / 28) * 10) / 10, + avgCsPerMin: input.avgCsPerMin ?? Math.round((input.avgCs / 28) * 10) / 10, mostPlayedChampionIds: championIds, }; -- 2.54.0 From fd1fa2366cdc81cc79e59c8ed8c23a73ef8e59b4 Mon Sep 17 00:00:00 2001 From: dahyeon Date: Fri, 24 Jul 2026 21:52:35 -0700 Subject: [PATCH 3/3] fix(api): resolve lint errors --- apps/api/eslint.config.mjs | 23 ++- .../auction/auction-realtime-serializer.ts | 12 +- .../src/modules/auction/auction.gateway.ts | 136 +++++++++++------- .../modules/auction/auction.service.spec.ts | 11 +- .../auction-redis-state-reader.service.ts | 18 ++- .../auction/redis/auction-redis.module.ts | 6 +- .../auction/redis/auction-redis.service.ts | 16 ++- .../auction/redis/auction-redis.state.ts | 9 +- apps/api/src/modules/auth/jwt.guard.ts | 5 +- apps/api/src/modules/auth/jwt.service.ts | 41 ++++-- apps/api/src/modules/auth/roles.guard.ts | 4 +- .../community-stats-cache.service.ts | 21 ++- .../match-stats.repository.spec.ts | 4 +- .../competition-bootstrap.service.spec.ts | 6 +- .../modules/dakao/dakao-user.service.spec.ts | 2 +- .../src/modules/dakao/dakao-user.service.ts | 2 +- .../api/src/modules/dakao/dakao.subscriber.ts | 2 +- .../src/modules/dakao/idempotency.cache.ts | 4 +- .../double-elimination.util.ts | 2 +- .../global/database/database.module.ts | 2 +- .../20260622-auction-redis-field-rename.ts | 3 + ...20260627-tournament-code-unique-indexes.ts | 30 ++-- .../src/modules/global/nats/nats.module.ts | 1 - .../mongoose-performance.plugin.ts | 28 ++-- .../global/redis/distributed-lock.service.ts | 22 ++- .../src/modules/global/redis/redis.module.ts | 8 +- .../src/modules/global/redis/redis.service.ts | 27 +++- .../legacy-import-result-cutover.spec.ts | 1 - .../modules/match/match.controller.spec.ts | 2 +- .../background-refresh.scheduler.ts | 2 +- .../riot-job-queue/riot-job-queue.service.ts | 9 +- .../riot-job-queue/riot-job-worker.service.ts | 2 +- .../riot-job-queue/riot-refresh.gateway.ts | 6 +- .../riot/riot-recent-matches.service.ts | 2 +- .../modules/riot/riot-webhook.controller.ts | 3 +- ...competition-assignment.provisioner.spec.ts | 1 - .../competition-outbox.processor.spec.ts | 1 - .../tournament-result.cutover.spec.ts | 1 - .../tournament-result.service.spec.ts | 1 - .../api/src/scripts/api-performance-report.ts | 4 +- .../src/scripts/auction-redis-rehearsal.ts | 25 ++-- apps/api/src/seed.ts | 1 - 42 files changed, 307 insertions(+), 199 deletions(-) diff --git a/apps/api/eslint.config.mjs b/apps/api/eslint.config.mjs index 4e9f8271..914cd4e2 100644 --- a/apps/api/eslint.config.mjs +++ b/apps/api/eslint.config.mjs @@ -29,7 +29,28 @@ export default tseslint.config( '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-floating-promises': 'warn', '@typescript-eslint/no-unsafe-argument': 'warn', - "prettier/prettier": ["error", { endOfLine: "auto" }], + 'prettier/prettier': ['error', { endOfLine: 'auto' }], + }, + }, + { + files: ['**/*.spec.ts', 'test/**/*.ts'], + rules: { + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-unsafe-call': 'off', + '@typescript-eslint/no-unsafe-member-access': 'off', + '@typescript-eslint/no-unsafe-return': 'off', + '@typescript-eslint/no-this-alias': 'off', + '@typescript-eslint/require-await': 'off', + '@typescript-eslint/unbound-method': 'off', + }, + }, + { + files: ['src/modules/global/database/migrations/**/*.ts'], + rules: { + '@typescript-eslint/no-unsafe-assignment': 'off', + '@typescript-eslint/no-unsafe-call': 'off', + '@typescript-eslint/no-unsafe-member-access': 'off', + '@typescript-eslint/no-unsafe-return': 'off', }, }, ); diff --git a/apps/api/src/modules/auction/auction-realtime-serializer.ts b/apps/api/src/modules/auction/auction-realtime-serializer.ts index 2a3c75de..4630de63 100644 --- a/apps/api/src/modules/auction/auction-realtime-serializer.ts +++ b/apps/api/src/modules/auction/auction-realtime-serializer.ts @@ -74,13 +74,11 @@ function serializeRealtimeAuctionPlayer( return player; } - const { - masteries: _masteries, - puuid: _puuid, - recentStatsSummary: _recentStatsSummary, - tierHistory: _tierHistory, - ...lightweightPlayer - } = player; + const lightweightPlayer = { ...player }; + delete lightweightPlayer.masteries; + delete lightweightPlayer.puuid; + delete lightweightPlayer.recentStatsSummary; + delete lightweightPlayer.tierHistory; return lightweightPlayer; } diff --git a/apps/api/src/modules/auction/auction.gateway.ts b/apps/api/src/modules/auction/auction.gateway.ts index f71d7cf0..fc5951f9 100644 --- a/apps/api/src/modules/auction/auction.gateway.ts +++ b/apps/api/src/modules/auction/auction.gateway.ts @@ -13,7 +13,7 @@ import { } from '@nestjs/websockets'; import mongoose from 'mongoose'; import type { JWTPayload } from 'jose'; -import { Namespace, Socket } from 'socket.io'; +import type { DefaultEventsMap, Namespace, Socket } from 'socket.io'; import { AuthService } from '../auth/auth.service'; import { IdentityService } from '../auth/identity.service'; import { JwtService } from '../auth/jwt.service'; @@ -78,6 +78,20 @@ interface BidRateLimitState { windowStartedAtTimestampMS: number; } +interface AuctionSocketData { + auctionBidRateLimit?: BidRateLimitState; + identity?: IdentityDocument; + matchId?: string; + user?: UserDocument; +} + +type AuctionSocket = Socket< + DefaultEventsMap, + DefaultEventsMap, + DefaultEventsMap, + AuctionSocketData +>; + const BID_RATE_LIMIT_WINDOW_MS = 1000; const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8; const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED'; @@ -112,14 +126,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { this.auctionEventBusService.attachAuctionNamespace(server); } - public async handleConnection(socket: Socket) { + public async handleConnection(socket: AuctionSocket) { 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 + err instanceof Error ? err.message : String(err) }`, ); socket.disconnect(true); @@ -128,7 +142,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('join') public async handleJoin( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: JoinAuctionPayload, ) { if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) { @@ -156,7 +170,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('bid') public async handleBid( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: BidPayload, @Ack() ack?: (response: Record) => void, ) { @@ -220,7 +234,12 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { error, ); const bidServerTiming = this.extractBidServerTiming(rejectionAckFields); - this.emitError(socket, String(rejectionAckFields.message ?? '')); + this.emitError( + socket, + typeof rejectionAckFields.message === 'string' + ? rejectionAckFields.message + : '', + ); ack?.({ ...rejectionAckFields, bidRequestId, @@ -263,7 +282,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('open-bidding') public async handleOpenBidding( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { @@ -292,7 +311,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('sold') public async handleSold( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: SoldPayload, @Ack() ack?: (response: Record) => void, ) { @@ -322,7 +341,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('next') public async handleNext( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { @@ -351,7 +370,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('passed') public async handlePassed( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: AuctionActionPayload, @Ack() ack?: (response: Record) => void, ) { @@ -380,7 +399,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { @SubscribeMessage('chat-message') public async handleChatMessage( - @ConnectedSocket() socket: Socket, + @ConnectedSocket() socket: AuctionSocket, @MessageBody() payload: ChatMessagePayload, ) { const matchId = this.requireJoinedMatchId(socket); @@ -406,7 +425,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { } } - private requireJoinedMatchId(socket: Socket): string | null { + private requireJoinedMatchId(socket: AuctionSocket): string | null { const matchId = this.getSocketMatchId(socket); if (!matchId) { this.emitError(socket, 'Join a match room before sending events.'); @@ -415,11 +434,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { return matchId; } - private consumeBidRateLimit(socket: Socket): boolean { + private consumeBidRateLimit(socket: AuctionSocket): boolean { const currentTimestampMS = Date.now(); - const previousState = socket.data.auctionBidRateLimit as - | BidRateLimitState - | undefined; + const previousState = socket.data.auctionBidRateLimit; if ( !previousState || currentTimestampMS - previousState.windowStartedAtTimestampMS >= @@ -437,10 +454,8 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { return previousState.count <= BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW; } - private getSocketMatchId(socket: Socket): string | undefined { - return typeof socket.data.matchId === 'string' - ? socket.data.matchId - : undefined; + private getSocketMatchId(socket: AuctionSocket): string | undefined { + return socket.data.matchId; } private toAuctionActionRequest(payload?: AuctionActionPayload) { @@ -464,8 +479,9 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { }; } - private readHandshakeUserId(socket: Socket): string | undefined { - const authUserId = socket.handshake.auth['x-auth-user-id']; + private readHandshakeUserId(socket: AuctionSocket): string | undefined { + const handshakeAuth = socket.handshake.auth as Record; + const authUserId = handshakeAuth['x-auth-user-id']; if (typeof authUserId === 'string') return authUserId; const header = socket.handshake.headers['x-auth-user-id']; @@ -473,16 +489,16 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { } private resolveSocketUserId( - socket: Socket, + socket: AuctionSocket, ): mongoose.Types.ObjectId | undefined { - return (socket.data.user as UserDocument | undefined)?._id; + return socket.data.user?._id; } private resolveChatDisplayName( - socket: Socket, + socket: AuctionSocket, fallbackDisplayName?: string, ): string { - const user = socket.data.user as UserDocument | undefined; + const user = socket.data.user; const primaryRiotAccount = user?.riotAccounts.find((entry) => entry.isPrimary) ?? user?.riotAccounts[0]; @@ -495,14 +511,14 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { if (user?.kakaoTalkNickname) return user.kakaoTalkNickname; if (user?.discordNickname) return user.discordNickname; - const identity = socket.data.identity as IdentityDocument | undefined; + const identity = socket.data.identity; if (identity?.displayName) return identity.displayName; if (identity?.email) return identity.email; return fallbackDisplayName ?? '관전자'; } - private async authenticateSocket(socket: Socket): Promise { + private async authenticateSocket(socket: AuctionSocket): Promise { const fallback = await this.authService.resolveDevUserById( this.readHandshakeUserId(socket), ); @@ -532,14 +548,20 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { }); } - private readHandshakeToken(socket: Socket): string | undefined { - const authToken = socket.handshake.auth.token; + private readHandshakeToken(socket: AuctionSocket): string | undefined { + const handshakeAuth = socket.handshake.auth as Record; + const authToken = handshakeAuth.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; + const header: unknown = socket.handshake.headers.authorization; + const authorization = + typeof header === 'string' + ? header + : Array.isArray(header) && typeof header[0] === 'string' + ? header[0] + : undefined; if (authorization?.startsWith('Bearer ')) { return authorization.slice('Bearer '.length).trim(); } @@ -547,10 +569,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { } private async resolveSocketUserForMatch( - socket: Socket, + socket: AuctionSocket, matchId: string, ): Promise { if (socket.data.user || !socket.data.identity) return; + const identity = socket.data.identity; const MatchModel = await this.connectionService.getModel('match'); const match = await MatchModel.findById(matchId).select({ @@ -559,10 +582,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { if (!match) return; const UserModel = await this.connectionService.getModel('user'); - socket.data.user = await UserModel.findOne({ + const user = await UserModel.findOne({ communityId: match.communityId, - identityId: (socket.data.identity as IdentityDocument)._id, + identityId: identity._id, }).exec(); + socket.data.user = user ?? undefined; } private requireStringClaim(payload: JWTPayload, key: string): string { @@ -596,7 +620,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { this.server.to(matchId).emit('match-side-effect', delta); } - private emitChatHistory(socket: Socket, auction: AuctionDocument) { + private emitChatHistory(socket: AuctionSocket, auction: AuctionDocument) { socket.emit('chat-history', { messages: (auction.chatMessages ?? []).map((message) => this.serializeChatMessage(message), @@ -604,16 +628,21 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { }); } - private emitKnownError(socket: Socket, error: unknown) { + private emitKnownError(socket: AuctionSocket, error: unknown) { this.emitError(socket, this.resolveErrorPayload(error).message); } - private emitError(socket: Socket, message: string) { + private emitError(socket: AuctionSocket, message: string) { socket.emit('error', { message }); } - private serializeAuction(auction: AuctionStateResponse) { - return JSON.parse(JSON.stringify(auction)); + private serializeAuction( + auction: AuctionStateResponse, + ): Record { + const serialized: unknown = JSON.parse(JSON.stringify(auction)); + return typeof serialized === 'object' && serialized !== null + ? (serialized as Record) + : {}; } /** @@ -721,7 +750,8 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { bidDelta: Record | null, ): Record | null { if (!bidDelta || !('bidServerTiming' in bidDelta)) return bidDelta; - const { bidServerTiming: _bidServerTiming, ...publicBidDelta } = bidDelta; + const publicBidDelta = { ...bidDelta }; + delete publicBidDelta.bidServerTiming; return publicBidDelta; } @@ -729,10 +759,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { auction: AuctionStateResponse, bidRequestId?: string, ): Record | null { - const serialized = this.serializeAuction(auction) as Record< - string, - unknown - >; + const serialized = this.serializeAuction(auction); const revision = Number(serialized.revision); const currentHighestBidPointAmount = Number( serialized.currentHighestBidPointAmount ?? serialized.currentBid, @@ -747,11 +774,13 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { ? Date.parse(serialized.currentDeadline) : 0), ); - const redisBidHistory = Array.isArray(serialized.auctionBidHistory) - ? serialized.auctionBidHistory + const redisBidHistory: unknown[] = Array.isArray( + serialized.auctionBidHistory, + ) + ? (serialized.auctionBidHistory as unknown[]) : []; - const legacyBidHistory = Array.isArray(serialized.bids) - ? serialized.bids + const legacyBidHistory: unknown[] = Array.isArray(serialized.bids) + ? (serialized.bids as unknown[]) : []; const auctionBidHistoryEntry = redisBidHistory[redisBidHistory.length - 1] ?? @@ -810,7 +839,12 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit { }; } - private serializeChatMessage(message: AuctionChatMessage) { - return JSON.parse(JSON.stringify(message)); + private serializeChatMessage( + message: AuctionChatMessage, + ): Record { + const serialized: unknown = JSON.parse(JSON.stringify(message)); + return typeof serialized === 'object' && serialized !== null + ? (serialized as Record) + : {}; } } diff --git a/apps/api/src/modules/auction/auction.service.spec.ts b/apps/api/src/modules/auction/auction.service.spec.ts index 695e8b49..ef9974a4 100644 --- a/apps/api/src/modules/auction/auction.service.spec.ts +++ b/apps/api/src/modules/auction/auction.service.spec.ts @@ -158,12 +158,11 @@ describe('AuctionService', () => { it('rejects non-positive or fractional bid amounts before loading auction state', async () => { const matchId = new mongoose.Types.ObjectId(); const auctionFindOne = jest.fn(); - const { service, auctionRedisCommandService, auctionRedisService } = - createService({ - auction: { - findOne: auctionFindOne, - }, - }); + const { service, auctionRedisCommandService } = createService({ + auction: { + findOne: auctionFindOne, + }, + }); await expect( service.placeBid({ diff --git a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts index 593446d8..cff926bf 100644 --- a/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts +++ b/apps/api/src/modules/auction/redis/auction-redis-state-reader.service.ts @@ -151,7 +151,7 @@ export class AuctionRedisStateReaderService { revision: number; }, shouldForceAuctionStateResync: options.shouldForceAuctionStateResync, - structureState: JSON.parse(structureStateJson) as Record, + structureState: parseJsonRecord(structureStateJson), }); view.matchId = matchId; if (options.includeInternalLiveStateFields) { @@ -170,12 +170,9 @@ export class AuctionRedisStateReaderService { if (typeof structureStateJson !== 'string' || !structureStateJson) { return undefined; } - const structureState = JSON.parse(structureStateJson) as Record< - string, - unknown - >; - const auctionTeams = Array.isArray(structureState.auctionTeams) - ? structureState.auctionTeams + const structureState = parseJsonRecord(structureStateJson); + const auctionTeams: unknown[] = Array.isArray(structureState.auctionTeams) + ? (structureState.auctionTeams as unknown[]) : []; const bidderTeam = auctionTeams.find((entry) => { if (!entry || typeof entry !== 'object') return false; @@ -192,6 +189,13 @@ function stringValue(value: unknown): string | undefined { return typeof value === 'string' && value ? value : undefined; } +function parseJsonRecord(json: string): Record { + const value: unknown = JSON.parse(json); + return typeof value === 'object' && value !== null + ? (value as Record) + : {}; +} + function parseHashReply( reply: unknown, options: { includeInternalLiveStateFields?: boolean } = {}, diff --git a/apps/api/src/modules/auction/redis/auction-redis.module.ts b/apps/api/src/modules/auction/redis/auction-redis.module.ts index d3b1b3a9..5623f363 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.module.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.module.ts @@ -74,9 +74,11 @@ async function readFirstSecret( const logger = new Logger('AuctionRedisClient'); const client = createClient(auctionRedisOptions); - client.on('error', (error) => { + client.on('error', (error: unknown) => { logger.error( - `Auction Redis client error: ${error?.message ?? error}`, + `Auction Redis client error: ${ + error instanceof Error ? error.message : String(error) + }`, ); }); diff --git a/apps/api/src/modules/auction/redis/auction-redis.service.ts b/apps/api/src/modules/auction/redis/auction-redis.service.ts index 91ba3cae..0240afb3 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.service.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.service.ts @@ -85,9 +85,15 @@ export class AuctionRedisService implements OnModuleDestroy { if (!isNoscriptError(error)) throw error; } - const loadedSha = String( - await this.client.sendCommand(['SCRIPT', 'LOAD', params.script]), - ); + const loadedShaReply = await this.client.sendCommand([ + 'SCRIPT', + 'LOAD', + params.script, + ]); + if (typeof loadedShaReply !== 'string') { + throw new Error('Redis SCRIPT LOAD returned a non-string SHA.'); + } + const loadedSha = loadedShaReply; return (await this.client.sendCommand( buildEvalShaCommand(loadedSha, params.keys, params.values), )) as T; @@ -111,7 +117,7 @@ export class AuctionRedisService implements OnModuleDestroy { token: string, ttlMS: number, ): Promise { - const result = await this.client.sendCommand([ + const result = await this.client.sendCommand([ 'SET', key, token, @@ -119,7 +125,7 @@ export class AuctionRedisService implements OnModuleDestroy { String(ttlMS), 'NX', ]); - return String(result) === 'OK'; + return result === 'OK'; } public async releaseTokenLock(key: string, token: string): Promise { diff --git a/apps/api/src/modules/auction/redis/auction-redis.state.ts b/apps/api/src/modules/auction/redis/auction-redis.state.ts index 477a7396..8e6aad6f 100644 --- a/apps/api/src/modules/auction/redis/auction-redis.state.ts +++ b/apps/api/src/modules/auction/redis/auction-redis.state.ts @@ -78,9 +78,7 @@ export function assembleAuctionViewFromRedisState( return { ...params.structureState, ...params.liveState, - auctionBidHistory: params.auctionBidHistoryEntries.map((entry) => - JSON.parse(entry), - ), + auctionBidHistory: params.auctionBidHistoryEntries.map(parseJsonValue), canPlaceBidInCurrentBidRound: !isExpiring, currentServerTimestampMS: params.currentServerTimestampMS, isAuctionStateTransitionInProgress: isExpiring, @@ -90,6 +88,11 @@ export function assembleAuctionViewFromRedisState( }; } +function parseJsonValue(json: string): unknown { + const value: unknown = JSON.parse(json); + return value; +} + export function buildHydrateAuctionStateScriptInvocation( keys: AuctionRedisKeys, input: HydrateAuctionStateScriptInput, diff --git a/apps/api/src/modules/auth/jwt.guard.ts b/apps/api/src/modules/auth/jwt.guard.ts index 97b73d0d..0018b7cd 100644 --- a/apps/api/src/modules/auth/jwt.guard.ts +++ b/apps/api/src/modules/auth/jwt.guard.ts @@ -26,8 +26,7 @@ export class JwtAuthGuard implements CanActivate { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, [context.getHandler(), context.getClass()], ); - const authz = request.headers?.authorization; - const authzHeader = Array.isArray(authz) ? authz[0] : authz; + const authzHeader = request.get('authorization'); if (!authzHeader) { const fallback = @@ -74,7 +73,7 @@ export class JwtAuthGuard implements CanActivate { private pickIdPFromToken(token: string): IdentityProviderName { try { - const { iss } = decodeJwt(token) as { iss?: string }; + const { iss } = decodeJwt(token); if (!iss) { throw new Error('Token has no issuer (iss) claim'); } diff --git a/apps/api/src/modules/auth/jwt.service.ts b/apps/api/src/modules/auth/jwt.service.ts index 166ca211..729be1a6 100644 --- a/apps/api/src/modules/auth/jwt.service.ts +++ b/apps/api/src/modules/auth/jwt.service.ts @@ -35,11 +35,13 @@ export class JwtService { throw new Error('Empty token'); } - if (identityProvider !== 'MICROSOFT_ENTRAID') { - throw new Error(`Identity provider not configured: ${identityProvider}`); + const provider = + identityProvider === 'MICROSOFT_ENTRAID' + ? await this.getEntraConfig() + : undefined; + if (!provider) { + throw new Error('Identity provider not configured.'); } - - const provider = await this.getEntraConfig(); const result = await jwtVerify(token, provider.jwks, { issuer: provider.issuer, audience: provider.audience, @@ -48,14 +50,22 @@ export class JwtService { }); const { payload, protectedHeader } = result; - if (!provider.allowedAlgs.includes(protectedHeader.alg as string)) { + if (!provider.allowedAlgs.includes(protectedHeader.alg)) { 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.ver !== undefined && + (typeof payload.ver !== 'string' || payload.ver !== '2.0') + ) { + throw new Error( + `Unsupported Entra token version: ${formatClaimValue(payload.ver)}`, + ); } - if (payload.tid && payload.tid !== provider.tenantId) { - throw new Error(`Unexpected tenant: ${payload.tid}`); + if ( + payload.tid !== undefined && + (typeof payload.tid !== 'string' || payload.tid !== provider.tenantId) + ) { + throw new Error(`Unexpected tenant: ${formatClaimValue(payload.tid)}`); } return result; @@ -98,3 +108,16 @@ export class JwtService { return this.entraConfig; } } + +function formatClaimValue(value: unknown): string { + if ( + typeof value === 'string' || + typeof value === 'number' || + typeof value === 'boolean' || + typeof value === 'bigint' + ) { + return String(value); + } + if (value === null) return 'null'; + return JSON.stringify(value) ?? typeof value; +} diff --git a/apps/api/src/modules/auth/roles.guard.ts b/apps/api/src/modules/auth/roles.guard.ts index 6e76e87d..0c01989d 100644 --- a/apps/api/src/modules/auth/roles.guard.ts +++ b/apps/api/src/modules/auth/roles.guard.ts @@ -7,7 +7,7 @@ import { } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import type { Request } from 'express'; -import { CommunityRole, UserDocument } from '../global/database/schema'; +import type { CommunityRole } from '../global/database/schema'; import { ROLES_KEY } from './roles.decorator'; import './auth-request'; @@ -23,7 +23,7 @@ export class RolesGuard implements CanActivate { if (!requiredRoles || requiredRoles.length === 0) return true; const req = context.switchToHttp().getRequest(); - const user = req.user as UserDocument | undefined; + const user = req.user; if (!user && req.identity) { throw new ForbiddenException('No membership in this community.'); } 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 index 2d50765a..d454e329 100644 --- a/apps/api/src/modules/community-stats/community-stats-cache.service.ts +++ b/apps/api/src/modules/community-stats/community-stats-cache.service.ts @@ -34,16 +34,29 @@ export class CommunityStatsCacheService { let deleted = 0; do { - const reply = (await client.sendCommand([ + const reply = await client.sendCommand([ 'SCAN', cursor, 'MATCH', match, 'COUNT', '100', - ])) as [string, string[]]; - cursor = reply[0]; - const keys = reply[1] ?? []; + ]); + if (!Array.isArray(reply)) { + throw new Error('Redis SCAN returned an invalid response.'); + } + const values = reply as unknown[]; + const nextCursor = values[0]; + const rawKeys = values[1]; + if (typeof nextCursor !== 'string') { + throw new Error('Redis SCAN returned an invalid cursor.'); + } + cursor = nextCursor; + const keys = Array.isArray(rawKeys) + ? (rawKeys as unknown[]).filter( + (key): key is string => typeof key === 'string', + ) + : []; if (keys.length > 0) { deleted += await client.del(keys); } diff --git a/apps/api/src/modules/community-stats/match-stats.repository.spec.ts b/apps/api/src/modules/community-stats/match-stats.repository.spec.ts index b9a8c6ef..6513d10f 100644 --- a/apps/api/src/modules/community-stats/match-stats.repository.spec.ts +++ b/apps/api/src/modules/community-stats/match-stats.repository.spec.ts @@ -125,8 +125,8 @@ describe('MatchStatsRepository', () => { if ( stored && - stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId!) && - stored.sourceRevision! <= fragment.sourceRevision! + stored.sourceCompetitionId?.equals(fragment.sourceCompetitionId) && + stored.sourceRevision <= fragment.sourceRevision ) { stored = fragment; return { matchedCount: 1, upsertedCount: 0 }; diff --git a/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts b/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts index 5a26cdf3..423d8bb6 100644 --- a/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts +++ b/apps/api/src/modules/competition/competition-bootstrap.service.spec.ts @@ -485,11 +485,7 @@ function createHarness( let competitionCall = 0; const competitionModel = { findOneAndUpdate: jest.fn( - ( - _filter: unknown, - update: { $setOnInsert: InsertPayload }, - _queryOptions: unknown, - ) => { + (_filter: unknown, update: { $setOnInsert: InsertPayload }) => { insertedPayloads.push(update.$setOnInsert); const selected = options.competitionResults?.[competitionCall++]; if (selected instanceof Error) return rejectedQuery(selected); diff --git a/apps/api/src/modules/dakao/dakao-user.service.spec.ts b/apps/api/src/modules/dakao/dakao-user.service.spec.ts index a8b98cd0..ed34dd5c 100644 --- a/apps/api/src/modules/dakao/dakao-user.service.spec.ts +++ b/apps/api/src/modules/dakao/dakao-user.service.spec.ts @@ -105,7 +105,7 @@ describe('DakaoUserService', () => { tagLine: 'KR2', isPrimary: false, }); - expect((result.user.riotAccounts as RiotAccount[])[0]).toMatchObject({ + expect(result.user.riotAccounts[0]).toMatchObject({ puuid: 'puuid-1', isPrimary: true, }); diff --git a/apps/api/src/modules/dakao/dakao-user.service.ts b/apps/api/src/modules/dakao/dakao-user.service.ts index 15b31553..be5707a4 100644 --- a/apps/api/src/modules/dakao/dakao-user.service.ts +++ b/apps/api/src/modules/dakao/dakao-user.service.ts @@ -87,7 +87,7 @@ export class DakaoUserService { if (!community) { throw new DakaoUserError('community_not_found', dakaoProjectId); } - return community._id as mongoose.Types.ObjectId; + return community._id; } public async upsertUser(params: { diff --git a/apps/api/src/modules/dakao/dakao.subscriber.ts b/apps/api/src/modules/dakao/dakao.subscriber.ts index c875cbff..1df57846 100644 --- a/apps/api/src/modules/dakao/dakao.subscriber.ts +++ b/apps/api/src/modules/dakao/dakao.subscriber.ts @@ -301,7 +301,7 @@ export class DakaoSubscriber implements OnModuleInit { text: index === this.usageCommands.length - 1 ? ` ${command}` - : ` ${command} \n`, + : ` ${command}\u3000\n`, } as const, ]); } diff --git a/apps/api/src/modules/dakao/idempotency.cache.ts b/apps/api/src/modules/dakao/idempotency.cache.ts index 01dffeca..a45b80af 100644 --- a/apps/api/src/modules/dakao/idempotency.cache.ts +++ b/apps/api/src/modules/dakao/idempotency.cache.ts @@ -20,8 +20,8 @@ export class IdempotencyCache { 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); + const oldestKey: unknown = this.entries.keys().next().value; + if (typeof oldestKey === 'string') this.entries.delete(oldestKey); } this.entries.set(key, Date.now() + TTL_MS); } diff --git a/apps/api/src/modules/double-elimination/double-elimination.util.ts b/apps/api/src/modules/double-elimination/double-elimination.util.ts index 73dd5c58..fe807410 100644 --- a/apps/api/src/modules/double-elimination/double-elimination.util.ts +++ b/apps/api/src/modules/double-elimination/double-elimination.util.ts @@ -144,7 +144,7 @@ export function buildDoubleEliminationBracket( teamIndex, })); const bracket: DoubleEliminationBracket = { - teamCount: seededTeamIndexes.length as 4 | 8, + teamCount: seededTeamIndexes.length, resetFinalEnabled: options.resetFinalEnabled, resetFinalCreated: false, seeds, diff --git a/apps/api/src/modules/global/database/database.module.ts b/apps/api/src/modules/global/database/database.module.ts index a4b5e918..2b9d722a 100644 --- a/apps/api/src/modules/global/database/database.module.ts +++ b/apps/api/src/modules/global/database/database.module.ts @@ -1,4 +1,4 @@ -import { DynamicModule, Module } from '@nestjs/common'; +import { Module } from '@nestjs/common'; import { ConnectionService } from './connection.service'; @Module({ diff --git a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts index 970e60ff..111402c9 100644 --- a/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts +++ b/apps/api/src/modules/global/database/migrations/20260622-auction-redis-field-rename.ts @@ -330,6 +330,9 @@ function legacyAuctionLifecycleId(value: unknown): string { function stringifyId(value: unknown): string | undefined { if (value === undefined || value === null) return undefined; + // MongoDB ObjectId and migration fixture IDs intentionally rely on their + // stable string representation. + // eslint-disable-next-line @typescript-eslint/no-base-to-string return typeof value === 'string' ? value : String(value); } diff --git a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts index b8e457af..a3065972 100644 --- a/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts +++ b/apps/api/src/modules/global/database/migrations/20260627-tournament-code-unique-indexes.ts @@ -1,11 +1,4 @@ -type TournamentCodeState = - | 'available' - | 'reserved' - | 'used' - | 'released' - | 'expired' - | 'voided' - | string; +type TournamentCodeState = string; type AnyDoc = Record & { _id: unknown }; type IndexKey = Record; @@ -36,7 +29,7 @@ interface MigrationCollection { $unset?: Record; }, options?: { ordered?: boolean }, - ): Promise<{ matchedCount?: number; modifiedCount?: number } | unknown>; + ): Promise; indexes?(): Promise; dropIndex?(name: string): Promise; createIndex?( @@ -516,15 +509,17 @@ function summarizeGroups( function summarizeCode(doc: TournamentCodeDoc): TournamentCodeDuplicateSummary { return { bracketMatchId: - doc.bracketMatchId === undefined ? undefined : String(doc.bracketMatchId), - code: doc.code === undefined ? undefined : String(doc.code), + doc.bracketMatchId === undefined + ? undefined + : stringifyId(doc.bracketMatchId), + code: doc.code === undefined ? undefined : stringifyId(doc.code), gameNumber: - doc.gameNumber === undefined ? undefined : String(doc.gameNumber), + doc.gameNumber === undefined ? undefined : stringifyId(doc.gameNumber), id: stringifyId(doc._id) ?? '', matchId: doc.matchId === undefined ? undefined : stringifyId(doc.matchId), riotMatchId: - doc.riotMatchId === undefined ? undefined : String(doc.riotMatchId), - state: doc.state === undefined ? undefined : String(doc.state), + doc.riotMatchId === undefined ? undefined : stringifyId(doc.riotMatchId), + state: doc.state, }; } @@ -749,16 +744,19 @@ function readModifiedCount(result: unknown): number { } function hasField(doc: Record, key: string): boolean { - return Object.prototype.hasOwnProperty.call(doc, key); + return Object.hasOwn(doc, key); } function stringifyKeyPart(value: unknown): string { if (value === null) return ''; if (value === undefined) return ''; - return stringifyId(value) ?? String(value); + return stringifyId(value) ?? ''; } function stringifyId(value: unknown): string | undefined { if (value === undefined || value === null) return undefined; + // MongoDB ObjectId and migration fixture IDs intentionally rely on their + // stable string representation. + // eslint-disable-next-line @typescript-eslint/no-base-to-string return typeof value === 'string' ? value : String(value); } diff --git a/apps/api/src/modules/global/nats/nats.module.ts b/apps/api/src/modules/global/nats/nats.module.ts index 79d5a32b..3e5a0287 100644 --- a/apps/api/src/modules/global/nats/nats.module.ts +++ b/apps/api/src/modules/global/nats/nats.module.ts @@ -1,5 +1,4 @@ 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'; diff --git a/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts b/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts index 6b878473..1cd92f76 100644 --- a/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts +++ b/apps/api/src/modules/global/observability/mongoose-performance.plugin.ts @@ -38,27 +38,24 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void { const markedSchema = schema as SchemaWithPerformanceMarker; if (markedSchema[PERFORMANCE_PLUGIN_APPLIED]) return; markedSchema[PERFORMANCE_PLUGIN_APPLIED] = true; - const hookableSchema = schema as any; - hookableSchema.pre(QUERY_OPERATION_REGEX, function () { + schema.pre(QUERY_OPERATION_REGEX, function () { const query = this as QueryWithPerformanceState; query[QUERY_PERFORMANCE_START] = process.hrtime.bigint(); query[QUERY_PERFORMANCE_RECORDED] = false; }); - hookableSchema.post(QUERY_OPERATION_REGEX, function (result: unknown) { - recordQueryPerformance( - this as unknown as QueryWithPerformanceState, - result, - ); + schema.post(QUERY_OPERATION_REGEX, function (result: unknown) { + recordQueryPerformance(this as QueryWithPerformanceState, result); }); - hookableSchema.post( + schema.post( QUERY_OPERATION_REGEX, + { errorHandler: true }, function ( - error: unknown, + error: Error, _result: unknown, - next: (error: unknown) => void, + next: (error?: mongoose.CallbackError) => void, ) { recordQueryPerformance( this as unknown as QueryWithPerformanceState, @@ -69,22 +66,23 @@ export function applyMongoosePerformancePlugin(schema: mongoose.Schema): void { }, ); - hookableSchema.pre('aggregate', function () { + schema.pre('aggregate', function () { const aggregate = this as AggregateWithPerformanceState; aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint(); aggregate[QUERY_PERFORMANCE_RECORDED] = false; }); - hookableSchema.post('aggregate', function (result: unknown) { + schema.post('aggregate', function (result: unknown) { recordAggregatePerformance(this as AggregateWithPerformanceState, result); }); - hookableSchema.post( + schema.post( 'aggregate', + { errorHandler: true }, function ( - error: unknown, + error: Error, _result: unknown, - next: (error: unknown) => void, + next: (error?: mongoose.CallbackError) => void, ) { recordAggregatePerformance( this as AggregateWithPerformanceState, diff --git a/apps/api/src/modules/global/redis/distributed-lock.service.ts b/apps/api/src/modules/global/redis/distributed-lock.service.ts index fb2e0023..226963dc 100644 --- a/apps/api/src/modules/global/redis/distributed-lock.service.ts +++ b/apps/api/src/modules/global/redis/distributed-lock.service.ts @@ -56,16 +56,11 @@ export class DistributedLockService { const lockOwnershipToken = options.lockOwnershipToken ?? randomUUID(); const result = await this.redisService .raw() - .sendCommand([ - 'SET', - options.lockKey, - lockOwnershipToken, - 'NX', - 'PX', - String(options.lockExpirationDurationMilliseconds), - ]); + .sendCommand< + string | null + >(['SET', options.lockKey, lockOwnershipToken, 'NX', 'PX', String(options.lockExpirationDurationMilliseconds)]); - if (String(result) !== 'OK') return null; + if (result !== 'OK') return null; return { lockKey: options.lockKey, lockOwnershipToken, @@ -124,7 +119,7 @@ export class DistributedLockService { await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => { this.logger.warn( `Failed to release distributed lock ${lockOwnership.lockKey}: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); }); @@ -143,8 +138,7 @@ export class DistributedLockService { const lockOwnership = await this.acquireLockWithRetry(options); if (!lockOwnership) return null; - let lockRenewalTimer: NodeJS.Timeout | undefined; - lockRenewalTimer = setInterval(() => { + const lockRenewalTimer = setInterval(() => { void this.extendLockIfOwned(lockOwnership).then((wasExtended) => { if (wasExtended) return; this.logger.warn( @@ -157,11 +151,11 @@ export class DistributedLockService { try { return await operation(lockOwnership); } finally { - if (lockRenewalTimer) clearInterval(lockRenewalTimer); + clearInterval(lockRenewalTimer); await this.releaseLockIfOwned(lockOwnership).catch((error: unknown) => { this.logger.warn( `Failed to release distributed lock ${lockOwnership.lockKey}: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); }); diff --git a/apps/api/src/modules/global/redis/redis.module.ts b/apps/api/src/modules/global/redis/redis.module.ts index 50d9d7ca..805985f8 100644 --- a/apps/api/src/modules/global/redis/redis.module.ts +++ b/apps/api/src/modules/global/redis/redis.module.ts @@ -54,8 +54,12 @@ async function readFirstSecret( }), ); - client.on('error', (error) => { - logger.error(`Redis client error: ${error?.message ?? error}`); + client.on('error', (error: unknown) => { + logger.error( + `Redis client error: ${ + error instanceof Error ? error.message : String(error) + }`, + ); }); await client.connect(); diff --git a/apps/api/src/modules/global/redis/redis.service.ts b/apps/api/src/modules/global/redis/redis.service.ts index 666fab98..57b6df05 100644 --- a/apps/api/src/modules/global/redis/redis.service.ts +++ b/apps/api/src/modules/global/redis/redis.service.ts @@ -35,11 +35,14 @@ interface RawStreamReadResult { function normalizeStreamFields(fields: unknown): Record { if (Array.isArray(fields)) { + const values = fields as unknown[]; const normalized: Record = {}; - for (let index = 0; index < fields.length; index += 2) { - const key = fields[index]; + for (let index = 0; index < values.length; index += 2) { + const key = values[index]; if (key === undefined) continue; - normalized[String(key)] = String(fields[index + 1] ?? ''); + normalized[redisValueToString(key)] = redisValueToString( + values[index + 1], + ); } return normalized; } @@ -260,10 +263,10 @@ export class RedisService implements OnModuleDestroy { rawMessage: unknown, ): StreamEntry | null { if (Array.isArray(rawMessage)) { - const [id, fields] = rawMessage; + const [id, fields] = rawMessage as unknown[]; if (id === undefined) return null; return { - id: String(id), + id: redisValueToString(id), message: normalizeStreamFields(fields), }; } @@ -291,3 +294,17 @@ export class RedisService implements OnModuleDestroy { return null; } } + +function redisValueToString(value: unknown): string { + if (typeof value === 'string') return value; + if ( + typeof value === 'number' || + typeof value === 'boolean' || + typeof value === 'bigint' + ) { + return String(value); + } + if (Buffer.isBuffer(value)) return value.toString('utf8'); + if (value === undefined || value === null) return ''; + return JSON.stringify(value) ?? ''; +} diff --git a/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts b/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts index 4619fa50..8fd8d0e7 100644 --- a/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts +++ b/apps/api/src/modules/legacy-import/legacy-import-result-cutover.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment, @typescript-eslint/require-await, @typescript-eslint/unbound-method */ import { readFileSync } from 'node:fs'; import mongoose from 'mongoose'; import type { CompetitionBootstrapService } from '../competition/competition-bootstrap.service'; diff --git a/apps/api/src/modules/match/match.controller.spec.ts b/apps/api/src/modules/match/match.controller.spec.ts index 36d85ea7..55e9a76c 100644 --- a/apps/api/src/modules/match/match.controller.spec.ts +++ b/apps/api/src/modules/match/match.controller.spec.ts @@ -34,7 +34,7 @@ describe('MatchController participant access', () => { it('requires an authenticated community member for the self-join route', () => { // Metadata must be read from the unbound prototype method itself. - // eslint-disable-next-line @typescript-eslint/unbound-method + const handler = MatchController.prototype.joinMatch; const roles = Reflect.getMetadata(ROLES_KEY, handler) as | string[] diff --git a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts index bbb9a940..b05102dd 100644 --- a/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts +++ b/apps/api/src/modules/riot-background-refresh/background-refresh.scheduler.ts @@ -73,7 +73,7 @@ export class BackgroundRefreshScheduler .catch((err: unknown) => { this.logger.warn( `Background refresh leader release failed: ${ - err instanceof Error ? err.message : err + err instanceof Error ? err.message : String(err) }`, ); }); 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 index 33b31ee2..d1f8f298 100644 --- 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 @@ -215,7 +215,7 @@ export class RiotJobQueueService { public async promoteDueScheduledJobs(limit = 100): Promise { const client = this.redisService.raw(); - const raw = (await client.sendCommand([ + const entries = await client.sendCommand([ 'ZRANGEBYSCORE', RIOT_JOB_SCHEDULED_ZSET, '-inf', @@ -223,16 +223,15 @@ export class RiotJobQueueService { 'LIMIT', '0', String(limit), - ])) as string[] | null; - const entries = raw ?? []; + ]); let promoted = 0; for (const entry of entries) { - const removed = (await client.sendCommand([ + 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; 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 index db565d41..b28658a0 100644 --- 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 @@ -67,7 +67,7 @@ export class RiotJobWorkerService implements OnModuleInit, OnModuleDestroy { .catch((error: unknown) => { this.logger.warn( `Failed to release Riot job worker leader lock: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); }); 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 index da75a504..beef34bd 100644 --- a/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts +++ b/apps/api/src/modules/riot-job-queue/riot-refresh.gateway.ts @@ -31,10 +31,10 @@ export class RiotRefreshGateway { private readonly logger = new Logger(RiotRefreshGateway.name); @SubscribeMessage('subscribe') - public async handleSubscribe( + public handleSubscribe( @ConnectedSocket() socket: Socket, @MessageBody() payload: SubscribePayload, - ) { + ): void { const rooms = this.resolveRooms(payload); if (rooms.length === 0) { socket.emit('error', { message: 'Invalid riot refresh subscription.' }); @@ -47,7 +47,7 @@ export class RiotRefreshGateway { return; } - await Promise.all(rooms.map((room) => socket.join(room))); + void socket.join(rooms); socket.emit('subscribed', { rooms }); } diff --git a/apps/api/src/modules/riot/riot-recent-matches.service.ts b/apps/api/src/modules/riot/riot-recent-matches.service.ts index 7ba6114e..b3e6f76b 100644 --- a/apps/api/src/modules/riot/riot-recent-matches.service.ts +++ b/apps/api/src/modules/riot/riot-recent-matches.service.ts @@ -100,7 +100,7 @@ export class RiotRecentMatchesService { } catch (error: unknown) { this.logger.warn( `Skipping Riot match ${matchId} while syncing ${params.puuid}: ${ - error instanceof Error ? error.message : error + error instanceof Error ? error.message : String(error) }`, ); } diff --git a/apps/api/src/modules/riot/riot-webhook.controller.ts b/apps/api/src/modules/riot/riot-webhook.controller.ts index a64a691e..67cc130b 100644 --- a/apps/api/src/modules/riot/riot-webhook.controller.ts +++ b/apps/api/src/modules/riot/riot-webhook.controller.ts @@ -14,6 +14,7 @@ export class RiotWebhookController { public captureTournamentWebhook(@Req() req: RiotWebhookRequest) { const receivedAt = new Date().toISOString(); const rawBodyText = req.rawBody?.toString('utf8') ?? null; + const body: unknown = req.body; const logPayload = { receivedAt, method: req.method, @@ -25,7 +26,7 @@ export class RiotWebhookController { headers: req.headers, query: req.query, params: req.params, - body: req.body, + body, rawBodyLength: req.rawBody?.length ?? null, rawBodyText, }; diff --git a/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts index c903a0d8..c36c07da 100644 --- a/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts +++ b/apps/api/src/modules/tournament-result/competition-assignment.provisioner.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import type { CompetitionResultSnapshot } from './competition-result.adapter'; import { CompetitionAssignmentProvisioner } from './competition-assignment.provisioner'; diff --git a/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts b/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts index c4c4d816..92aba73e 100644 --- a/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts +++ b/apps/api/src/modules/tournament-result/competition-outbox.processor.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import { Logger } from '@nestjs/common'; import { CommunityStatsService } from '../community-stats/community-stats.service'; diff --git a/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts index 514867d4..e197c50a 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.cutover.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; import type { RiotMatchDto } from '../riot/riot.types'; diff --git a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts index 3884231d..1e714229 100644 --- a/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts +++ b/apps/api/src/modules/tournament-result/tournament-result.service.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-unsafe-assignment */ import mongoose from 'mongoose'; import type { MatchDocument } from '../global/database/schema'; import type { RiotMatchDto } from '../riot/riot.types'; diff --git a/apps/api/src/scripts/api-performance-report.ts b/apps/api/src/scripts/api-performance-report.ts index 20df9e8c..c63f87d7 100644 --- a/apps/api/src/scripts/api-performance-report.ts +++ b/apps/api/src/scripts/api-performance-report.ts @@ -485,7 +485,9 @@ function newRelicTransactionResultToRow( hydratedDocsReturnedP95Budget: number; }, ): EndpointReportRow | null { - const parsed = parseTransactionName(String(result.facet ?? '')); + const facet = result.facet; + if (typeof facet !== 'string') return null; + const parsed = parseTransactionName(facet); if (!parsed) return null; const row: EndpointReportRow = { diff --git a/apps/api/src/scripts/auction-redis-rehearsal.ts b/apps/api/src/scripts/auction-redis-rehearsal.ts index d36ad8f2..61f2edab 100644 --- a/apps/api/src/scripts/auction-redis-rehearsal.ts +++ b/apps/api/src/scripts/auction-redis-rehearsal.ts @@ -419,15 +419,15 @@ async function main(): Promise { auctionRedisService, ); const dummyTournamentCodeService = { - releaseFromMatch: async () => undefined, - reserveForMatch: async () => undefined, + releaseFromMatch: () => Promise.resolve(undefined), + reserveForMatch: () => Promise.resolve(undefined), }; const dummyTournamentResultService = { - cancelPolling: async () => undefined, - scheduleInitialPoll: async () => undefined, + cancelPolling: () => Promise.resolve(undefined), + scheduleInitialPoll: () => Promise.resolve(undefined), }; const dummySideEffectService = { - mirrorMatchSideEffectStatus: async () => true, + mirrorMatchSideEffectStatus: () => Promise.resolve(true), }; const dummyEventBus = { broadcastMatchSideEffect: () => undefined, @@ -436,13 +436,14 @@ async function main(): Promise { const auctionService = new AuctionService( connectionService, { - enrichRiotAccount: async () => ({ - account: null, - league: 'fresh', - masteries: 'fresh', - recentMatches: 'fresh', - summoner: 'fresh', - }), + enrichRiotAccount: () => + Promise.resolve({ + account: null, + league: 'fresh', + masteries: 'fresh', + recentMatches: 'fresh', + summoner: 'fresh', + }), } as never, dummyTournamentCodeService as never, dummyTournamentResultService as never, diff --git a/apps/api/src/seed.ts b/apps/api/src/seed.ts index 0d7e7627..4e6a5060 100644 --- a/apps/api/src/seed.ts +++ b/apps/api/src/seed.ts @@ -9,7 +9,6 @@ import { ConnectionService } from './modules/global/database/connection.service' import type { ChampionMasteryEntry, MatchParticipant, - MatchTeam, Position, PositionPreference, RiotLane, -- 2.54.0