chore: add deployment and maintenance tooling

This commit is contained in:
dahyeon committed 2026-04-27 03:51:00 +09:00
1 parent 7989da96d0
commit b689fa6a46
9 files changed
+2585

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
# syntax=docker/dockerfile:1.7
FROM node:24-bookworm-slim AS pnpm-base
ENV PNPM_HOME=/pnpm
ENV PATH="${PNPM_HOME}:${PATH}"
RUN corepack enable
WORKDIR /app
FROM pnpm-base AS deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json
RUN pnpm install --frozen-lockfile --filter api... --filter lolympus-tournament-support
FROM deps AS build
COPY apps/api apps/api
RUN pnpm --filter api build
FROM pnpm-base AS prod-deps
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
COPY apps/api/package.json apps/api/package.json
COPY apps/web/package.json apps/web/package.json
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
FROM gcr.io/distroless/nodejs24-debian13:nonroot AS runtime
WORKDIR /app
ENV NODE_ENV=prod
COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
COPY --chown=nonroot:nonroot apps/project.env ./project.env
COPY --chown=nonroot:nonroot apps/api/docker-entrypoint.js ./apps/api/docker-entrypoint.js
EXPOSE 10712
CMD ["apps/api/docker-entrypoint.js"]
+72
View File
@@ -0,0 +1,72 @@
'use strict';
const fs = require('node:fs');
const path = require('node:path');
const MACHINE_ENV_PATHS = [
process.env.MachineEnvFile,
process.env.MACHINE_ENV_FILE,
'/source/global-env-vars.txt',
process.env.HOME
? path.join(process.env.HOME, 'source/global-env-vars.txt')
: '',
].filter(Boolean);
const PROJECT_ENV_PATHS = [
'project.env',
'/app/project.env',
'apps/project.env',
];
function stripQuotes(value) {
const trimmed = value.trim();
if (
(trimmed.startsWith('"') && trimmed.endsWith('"')) ||
(trimmed.startsWith("'") && trimmed.endsWith("'"))
) {
return trimmed.slice(1, -1);
}
return trimmed;
}
function loadEnvFile(filePath, options = {}) {
const { override = false } = options;
const content = fs.readFileSync(filePath, 'utf8');
for (const line of content.split(/\r?\n/u)) {
if (!line.trim() || /^\s*#/u.test(line)) continue;
const match = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$/u);
if (!match) continue;
if (!override && process.env[match[1]] !== undefined) continue;
process.env[match[1]] = stripQuotes(match[2]);
}
}
const machineEnvFile = MACHINE_ENV_PATHS.find((candidate) =>
fs.existsSync(candidate),
);
if (machineEnvFile) {
loadEnvFile(machineEnvFile, { override: true });
}
for (const projectEnvFile of PROJECT_ENV_PATHS) {
if (fs.existsSync(projectEnvFile)) {
loadEnvFile(projectEnvFile);
}
}
const missing = [
'INFISICAL_CLIENT_ID',
'INFISICAL_CLIENT_SECRET',
'INFISICAL_PROJECT_ID',
].filter((key) => !process.env[key]);
if (missing.length > 0) {
console.error(
`Missing required environment variables: ${missing.join(', ')}`,
);
process.exit(1);
}
require('./dist/main.js');
+68
View File
@@ -0,0 +1,68 @@
param(
[switch]$UsePm2,
[string]$Pm2Name = "lolympus-tournament-support"
)
if (-not $env:NODE_ENV) {
$env:NODE_ENV = "dev"
}
$MainScript = Join-Path $PSScriptRoot "dist/main.js"
if ($isMacOS -or $isLinux) {
$env:MachineEnvFile = "$env:HOME/source/global-env-vars.txt"
} elseif ($isWindows) {
$env:MachineEnvFile = "$env:USERPROFILE/source/global-env-vars.txt"
}
function Set-EnvFromFile {
param([string]$Path)
if (-not (Test-Path $Path)) {
throw "File not found: $Path"
}
foreach ($line in Get-Content $Path) {
if ([string]::IsNullOrWhiteSpace($line)) { continue }
if ($line -match '^\s*#') { continue }
if ($line -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)\s*$') {
$key = $matches[1]
$value = $matches[2].Trim()
if (
($value.StartsWith('"') -and $value.EndsWith('"')) -or
($value.StartsWith("'") -and $value.EndsWith("'"))
) {
$value = $value.Substring(1, $value.Length - 2)
}
[System.Environment]::SetEnvironmentVariable($key, $value)
}
}
}
if (Test-Path $env:MachineEnvFile) {
Set-EnvFromFile $env:MachineEnvFile
}
if (-not $env:INFISICAL_CLIENT_ID) {
Write-Error "INFISICAL_CLIENT_ID is not set."
exit 1
}
if (-not $env:INFISICAL_CLIENT_SECRET) {
Write-Error "INFISICAL_CLIENT_SECRET is not set."
exit 1
}
if (-not $env:INFISICAL_PROJECT_ID) {
Write-Error "INFISICAL_PROJECT_ID is not set."
exit 1
}
if ($UsePm2) {
pm2 start $MainScript --name $Pm2Name --update-env
} else {
node $MainScript
}
+4
View File
@@ -0,0 +1,4 @@
INFISICAL_PROJECT_ID=26a80d59-a424-4e33-adfc-2b6e84d6e25f
SERVICE_NAME=lolympus-tournament-support
VERSION=0.1
+389
View File
@@ -0,0 +1,389 @@
import { createClient } from "redis";
import { getSecret } from "@common/secret-manager";
import { getLogger } from "@obs/logger";
type GarnetRedisClient = ReturnType<typeof createClient>;
export interface StreamEntry {
deliveriesCounter?: number | undefined;
id: string;
message: Record<string, string>;
millisElapsedFromDelivery?: number | undefined;
}
export interface StreamReadResult {
messages: StreamEntry[];
name: string;
}
export interface StreamPendingEntry {
consumer: string;
deliveriesCounter: number;
id: string;
millisecondsSinceLastDelivery: number;
}
interface RawStreamMessage {
deliveriesCounter?: number | undefined;
id: string;
message: unknown;
millisElapsedFromDelivery?: number | undefined;
}
interface RawStreamReadResult {
messages: RawStreamMessage[];
name: string;
}
function normalizeGarnetUrl(endpoint: string): string {
const trimmed = endpoint.trim();
if (!trimmed) {
throw new Error("GARNET_ENDPOINT cannot be empty");
}
if (/^redis(s)?:\/\//iu.test(trimmed)) {
return trimmed;
}
return `redis://${trimmed}`;
}
function normalizeStreamFields(fields: unknown): Record<string, string> {
if (fields instanceof Map) {
return Object.fromEntries(
[...fields.entries()].map(([key, value]) => [String(key), String(value)]),
);
}
if (typeof fields === "object" && fields !== null) {
return Object.fromEntries(
Object.entries(fields as Record<string, unknown>).map(([key, value]) => [
key,
String(value),
]),
);
}
return {};
}
export class GarnetClient {
private client: GarnetRedisClient | null = null;
private readonly logger = getLogger();
private getClient(): GarnetRedisClient {
if (!this.client) {
throw new Error("Garnet client not connected");
}
return this.client;
}
async connect(): Promise<void> {
const endpoint = getSecret("GARNET_ENDPOINT");
const username = getSecret("GARNET_USERID");
const password = getSecret("GARNET_PASSWORD");
if (!endpoint || !username || !password) {
throw new Error("Missing Garnet credentials in secrets");
}
const client = createClient({
password,
url: normalizeGarnetUrl(endpoint),
username,
});
client.on("error", (error) => {
this.logger.error({ err: error }, "[Garnet] Client error");
});
await client.connect();
this.client = client;
this.logger.info("✓ Garnet connected");
}
async getJson<T>(key: string): Promise<T | null> {
const rawValue = await this.getClient().get(key);
if (!rawValue) {
return null;
}
return JSON.parse(rawValue) as T;
}
async setJson(
key: string,
value: unknown,
ttlSeconds?: number,
): Promise<void> {
const serialized = JSON.stringify(value);
const client = this.getClient();
if (ttlSeconds && ttlSeconds > 0) {
await client.set(key, serialized, { EX: ttlSeconds });
return;
}
await client.set(key, serialized);
}
async getString(key: string): Promise<string | null> {
return this.getClient().get(key);
}
async setString(
key: string,
value: string,
ttlSeconds?: number,
): Promise<void> {
const client = this.getClient();
if (ttlSeconds && ttlSeconds > 0) {
await client.set(key, value, { EX: ttlSeconds });
return;
}
await client.set(key, value);
}
async setStringIfAbsent(
key: string,
value: string,
ttlSeconds?: number,
): Promise<boolean> {
const client = this.getClient();
const setOptions: {
EX?: number;
NX: true;
} = {
NX: true,
};
if (ttlSeconds && ttlSeconds > 0) {
setOptions.EX = ttlSeconds;
}
const result = await client.set(key, value, {
...setOptions,
});
return result === "OK";
}
async delete(key: string): Promise<number> {
return this.getClient().del(key);
}
async getHash(key: string): Promise<Record<string, string>> {
return this.getClient().hGetAll(key);
}
async setHash(key: string, fields: Record<string, string>): Promise<void> {
await this.getClient().hSet(key, fields);
}
async appendStream(
key: string,
fields: Record<string, string>,
options?: { maxLen?: number | undefined },
): Promise<string> {
const trimOptions =
options?.maxLen && options.maxLen > 0
? {
TRIM: {
strategy: "MAXLEN" as const,
strategyModifier: "~" as const,
threshold: options.maxLen,
},
}
: undefined;
return this.getClient().xAdd(key, "*", fields, trimOptions);
}
async createConsumerGroup(
key: string,
group: string,
startId = "$",
): Promise<void> {
await this.getClient().xGroupCreate(key, group, startId, {
MKSTREAM: true,
});
}
async readGroup(
key: string,
group: string,
consumer: string,
startId: string,
options?: {
blockMs?: number | undefined;
count?: number | undefined;
},
): Promise<StreamReadResult[] | null> {
const readOptions: {
BLOCK?: number;
COUNT?: number;
} = {};
if (options?.blockMs !== undefined) {
readOptions.BLOCK = options.blockMs;
}
if (options?.count !== undefined) {
readOptions.COUNT = options.count;
}
const reply = await this.getClient().xReadGroup(
group,
consumer,
{
key,
id: startId,
},
readOptions,
);
if (!reply) {
return null;
}
return (reply as RawStreamReadResult[]).map((stream) => ({
name: String(stream.name),
messages: stream.messages.map((message) => ({
deliveriesCounter:
typeof message.deliveriesCounter === "number"
? message.deliveriesCounter
: undefined,
id: String(message.id),
message: normalizeStreamFields(message.message),
millisElapsedFromDelivery:
typeof message.millisElapsedFromDelivery === "number"
? message.millisElapsedFromDelivery
: undefined,
})),
}));
}
async acknowledgeStream(
key: string,
group: string,
ids: string | string[],
): Promise<number> {
return this.getClient().xAck(key, group, ids);
}
async getPendingStreamRange(
key: string,
group: string,
count: number,
options?: {
consumer?: string | undefined;
idleMs?: number | undefined;
start?: string | undefined;
end?: string | undefined;
},
): Promise<StreamPendingEntry[]> {
const pendingOptions: {
IDLE?: number;
consumer?: string;
} = {};
if (options?.idleMs !== undefined) {
pendingOptions.IDLE = options.idleMs;
}
if (options?.consumer !== undefined) {
pendingOptions.consumer = options.consumer;
}
const reply = await this.getClient().xPendingRange(
key,
group,
options?.start ?? "-",
options?.end ?? "+",
count,
pendingOptions,
);
return reply.map((entry) => ({
consumer: String(entry.consumer),
deliveriesCounter: entry.deliveriesCounter,
id: String(entry.id),
millisecondsSinceLastDelivery: entry.millisecondsSinceLastDelivery,
}));
}
async claimPendingStream(
key: string,
group: string,
consumer: string,
minIdleTimeMs: number,
ids: string | string[],
options?: {
retryCount?: number | undefined;
},
): Promise<StreamEntry[]> {
const claimOptions: {
RETRYCOUNT?: number;
} = {};
if (options?.retryCount !== undefined) {
claimOptions.RETRYCOUNT = options.retryCount;
}
const claimed = await this.getClient().xClaim(
key,
group,
consumer,
minIdleTimeMs,
ids,
claimOptions,
);
return claimed.flatMap((message) => {
if (!message) {
return [];
}
return [
{
deliveriesCounter:
typeof message.deliveriesCounter === "number"
? message.deliveriesCounter
: undefined,
id: String(message.id),
message: normalizeStreamFields(message.message),
millisElapsedFromDelivery:
typeof message.millisElapsedFromDelivery === "number"
? message.millisElapsedFromDelivery
: undefined,
},
];
});
}
async scanKeys(pattern: string): Promise<string[]> {
const keys: string[] = [];
for await (const batch of this.getClient().scanIterator({
COUNT: 100,
MATCH: pattern,
})) {
for (const key of batch) {
keys.push(String(key));
}
}
return keys;
}
async close(): Promise<void> {
if (!this.client) {
return;
}
const client = this.client;
this.client = null;
try {
await client.quit();
} catch {
client.destroy();
}
}
}
+406
View File
@@ -0,0 +1,406 @@
/**
* Add or update one lolympus user manually from Kakao + Riot identity.
*
* This is for the last few users that need manual handling.
*
* Install:
* npm install mongodb
*
* Dry-run with Riot API enrichment:
* MONGODB_URI="mongodb://..." \
* RIOT_API_KEY="RGAPI-..." \
* KAKAO_TALK_ID="7448687768283723562" \
* KAKAO_TALK_NICKNAME="탑은죄악이다/95/남/G" \
* RIOT_ID="탑은죄악이다#망나니" \
* PREFERRED_POSITIONS="TOP,JGL" \
* node add-manual-dakao-riot-user.js
*
* Write:
* DRY_RUN=false MONGODB_URI="..." RIOT_API_KEY="..." ... node add-manual-dakao-riot-user.js
*
* Fallback without Riot API:
* PUUID="..." RIOT_ID="..." node add-manual-dakao-riot-user.js
*/
"use strict";
const { MongoClient, ObjectId } = require("mongodb");
const CONFIG = {
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test",
COMMUNITY_ID: new ObjectId(
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
),
RIOT_API_KEY: process.env.RIOT_API_KEY ?? "",
RIOT_REGION: process.env.RIOT_REGION ?? "asia",
RIOT_PLATFORM: process.env.RIOT_PLATFORM ?? "kr",
MASTERY_COUNT: Number(process.env.MASTERY_COUNT ?? 10),
RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20),
FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false",
DRY_RUN: process.env.DRY_RUN !== "false",
FAIL_ON_CONFLICT: process.env.FAIL_ON_CONFLICT !== "false",
};
const INPUT = {
kakaoTalkId: process.env.KAKAO_TALK_ID ?? "",
kakaoTalkNickname: process.env.KAKAO_TALK_NICKNAME ?? "",
riotId: process.env.RIOT_ID ?? "",
puuid: process.env.PUUID ?? "",
preferredPositions: process.env.PREFERRED_POSITIONS ?? "",
role: process.env.ROLE ?? "member",
isActivated: process.env.IS_ACTIVATED !== "false",
};
function normalizeString(value) {
return typeof value === "string" ? value.trim() : "";
}
function splitRiotId(riotId) {
const value = normalizeString(riotId);
const hashIndex = value.lastIndexOf("#");
if (hashIndex <= 0 || hashIndex === value.length - 1) {
throw new Error(`Invalid RIOT_ID. Expected "gameName#tagLine": ${riotId}`);
}
return {
gameName: value.slice(0, hashIndex).trim(),
tagLine: value.slice(hashIndex + 1).trim(),
};
}
function normalizePositions(value) {
const allowed = new Set(["TOP", "JGL", "MID", "ADC", "SUP"]);
return normalizeString(value)
.split(",")
.map((position) => normalizeString(position).toUpperCase())
.filter((position) => allowed.has(position))
.map((position, index) => ({ position, priority: index + 1 }));
}
function removeUndefined(value) {
if (Array.isArray(value)) return value.map(removeUndefined);
if (
value &&
typeof value === "object" &&
!(value instanceof Date) &&
!(value instanceof ObjectId)
) {
return Object.fromEntries(
Object.entries(value)
.filter(([, entryValue]) => entryValue !== undefined)
.map(([key, entryValue]) => [key, removeUndefined(entryValue)]),
);
}
return value;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function maskConfig() {
return {
...CONFIG,
MONGODB_URI: CONFIG.MONGODB_URI.replace(/\/\/.*@/u, "//***@"),
RIOT_API_KEY: CONFIG.RIOT_API_KEY ? "***" : "",
};
}
function requireInput() {
const missing = [];
if (!normalizeString(INPUT.kakaoTalkId)) missing.push("KAKAO_TALK_ID");
if (!normalizeString(INPUT.kakaoTalkNickname)) {
missing.push("KAKAO_TALK_NICKNAME");
}
if (!normalizeString(INPUT.riotId)) missing.push("RIOT_ID");
if (!CONFIG.RIOT_API_KEY && !normalizeString(INPUT.puuid)) {
missing.push("RIOT_API_KEY or PUUID");
}
if (missing.length > 0) {
throw new Error(`Missing required env: ${missing.join(", ")}`);
}
}
async function fetchRiotJson({ host, path, query }) {
if (!CONFIG.RIOT_API_KEY) return null;
const url = new URL(`https://${host}${path}`);
for (const [key, value] of Object.entries(query ?? {})) {
if (value !== undefined && value !== null) {
url.searchParams.set(key, String(value));
}
}
for (;;) {
const response = await fetch(url, {
headers: { "X-Riot-Token": CONFIG.RIOT_API_KEY },
});
if (response.status === 429) {
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1);
await sleep(Math.max(1, retryAfterSeconds) * 1000);
continue;
}
if (response.status === 404) return null;
if (!response.ok) {
const body = await response.text().catch(() => "");
throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`);
}
return response.json();
}
}
async function fetchAccountByRiotId({ gameName, tagLine }) {
return fetchRiotJson({
host: `${CONFIG.RIOT_REGION}.api.riotgames.com`,
path: `/riot/account/v1/accounts/by-riot-id/${encodeURIComponent(gameName)}/${encodeURIComponent(tagLine)}`,
});
}
async function fetchSummonerByPuuid(puuid) {
return fetchRiotJson({
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
path: `/lol/summoner/v4/summoners/by-puuid/${encodeURIComponent(puuid)}`,
});
}
async function fetchLeagueEntriesByPuuid(puuid) {
return fetchRiotJson({
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
path: `/lol/league/v4/entries/by-puuid/${encodeURIComponent(puuid)}`,
});
}
async function fetchChampionMasteriesByPuuid(puuid) {
return fetchRiotJson({
host: `${CONFIG.RIOT_PLATFORM}.api.riotgames.com`,
path: `/lol/champion-mastery/v4/champion-masteries/by-puuid/${encodeURIComponent(puuid)}/top`,
query: { count: CONFIG.MASTERY_COUNT },
});
}
async function fetchRecentMatchIdsByPuuid(puuid) {
if (!CONFIG.FETCH_RECENT_MATCH_IDS) return [];
return fetchRiotJson({
host: `${CONFIG.RIOT_REGION}.api.riotgames.com`,
path: `/lol/match/v5/matches/by-puuid/${encodeURIComponent(puuid)}/ids`,
query: { start: 0, count: CONFIG.RECENT_MATCH_COUNT },
});
}
async function fetchRiotData({ riotId }) {
const fallback = splitRiotId(riotId);
const account =
(await fetchAccountByRiotId(fallback)) ?? {
...fallback,
puuid: normalizeString(INPUT.puuid),
};
if (!account?.puuid) {
throw new Error(`Riot account not found and PUUID was not provided: ${riotId}`);
}
const [summoner, leagueEntries, championMasteries, matchIds] =
await Promise.all([
fetchSummonerByPuuid(account.puuid).catch(() => null),
fetchLeagueEntriesByPuuid(account.puuid).catch(() => []),
fetchChampionMasteriesByPuuid(account.puuid).catch(() => []),
fetchRecentMatchIdsByPuuid(account.puuid).catch(() => []),
]);
return {
account: {
puuid: account.puuid,
gameName: normalizeString(account.gameName) || fallback.gameName,
tagLine: normalizeString(account.tagLine) || fallback.tagLine,
},
summoner,
leagueEntries: Array.isArray(leagueEntries) ? leagueEntries : [],
championMasteries: Array.isArray(championMasteries)
? championMasteries
: [],
matchIds: Array.isArray(matchIds) ? matchIds : [],
};
}
function toTierInfo(entry, fetchedAt) {
return {
leagueId: entry.leagueId,
queueType: entry.queueType,
tier: entry.tier,
rank: entry.rank,
puuid: entry.puuid,
leaguePoints: entry.leaguePoints ?? 0,
wins: entry.wins ?? 0,
losses: entry.losses ?? 0,
veteran: entry.veteran,
inactive: entry.inactive,
freshBlood: entry.freshBlood,
hotStreak: entry.hotStreak,
miniSeries: entry.miniSeries,
fetchedAt,
};
}
function toTierHistory(entry, recordedAt) {
return {
queueType: entry.queueType,
tier: entry.tier,
rank: entry.rank,
leaguePoints: entry.leaguePoints ?? 0,
wins: entry.wins ?? 0,
losses: entry.losses ?? 0,
recordedAt,
};
}
function toChampionMastery(entry) {
return {
puuid: entry.puuid,
championId: entry.championId,
championLevel: entry.championLevel,
championPoints: entry.championPoints,
lastPlayTime: entry.lastPlayTime,
championPointsSinceLastLevel: entry.championPointsSinceLastLevel,
championPointsUntilNextLevel: entry.championPointsUntilNextLevel,
markRequiredForNextLevel: entry.markRequiredForNextLevel,
tokensEarned: entry.tokensEarned,
championSeasonMilestone: entry.championSeasonMilestone,
milestoneGrades: entry.milestoneGrades,
nextSeasonMilestone: entry.nextSeasonMilestone,
};
}
function buildRiotAccount(riotData, now) {
return removeUndefined({
puuid: riotData.account.puuid,
gameName: riotData.account.gameName,
tagLine: riotData.account.tagLine,
profileIconId: riotData.summoner?.profileIconId ?? 0,
revisionDate: riotData.summoner?.revisionDate ?? 0,
summonerLevel: riotData.summoner?.summonerLevel ?? 0,
isPrimary: true,
tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)),
tierHistory: riotData.leagueEntries.map((entry) => toTierHistory(entry, now)),
matchIds: riotData.matchIds,
matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined,
championMasteries: riotData.championMasteries
.slice(0, CONFIG.MASTERY_COUNT)
.map(toChampionMastery),
championMasteriesFetchedAt:
riotData.championMasteries.length > 0 ? now : undefined,
championRecords: {},
createdAt: now,
updatedAt: now,
});
}
function mergeRiotAccount(existingAccounts, nextAccount) {
const merged = (existingAccounts ?? [])
.filter(
(account) =>
account.puuid !== nextAccount.puuid &&
!(
normalizeString(account.gameName).toLowerCase() ===
normalizeString(nextAccount.gameName).toLowerCase() &&
normalizeString(account.tagLine).toLowerCase() ===
normalizeString(nextAccount.tagLine).toLowerCase()
),
)
.map((account) => ({ ...account, isPrimary: false }));
return [nextAccount, ...merged];
}
async function buildPlan(User) {
const now = new Date();
const riotData = await fetchRiotData({ riotId: INPUT.riotId });
const account = buildRiotAccount(riotData, now);
const conflict = await User.findOne({
communityId: CONFIG.COMMUNITY_ID,
kakaoTalkId: { $ne: INPUT.kakaoTalkId },
"riotAccounts.puuid": account.puuid,
});
if (conflict && CONFIG.FAIL_ON_CONFLICT) {
throw new Error(
`Riot puuid conflict. existingUserId=${conflict._id.toString()} existingKakaoTalkId=${conflict.kakaoTalkId}`,
);
}
const filter = {
communityId: CONFIG.COMMUNITY_ID,
kakaoTalkId: INPUT.kakaoTalkId,
};
const existing = await User.findOne(filter);
const doc = removeUndefined({
_id: existing?._id ?? new ObjectId(),
communityId: CONFIG.COMMUNITY_ID,
role: INPUT.role,
kakaoTalkId: INPUT.kakaoTalkId,
kakaoTalkNickname: INPUT.kakaoTalkNickname,
riotAccounts: mergeRiotAccount(existing?.riotAccounts, account),
preferredPositions: normalizePositions(INPUT.preferredPositions),
isActivated: INPUT.isActivated,
createdAt: existing?.createdAt ?? now,
updatedAt: now,
});
return {
mode: existing ? "update" : "insert",
filter,
doc,
conflict: conflict
? {
existingUserId: conflict._id,
existingKakaoTalkId: conflict.kakaoTalkId,
}
: null,
};
}
async function applyPlan(User, plan) {
if (CONFIG.DRY_RUN) return { dryRun: true, plan };
if (plan.mode === "update") {
const { _id, createdAt, ...setDoc } = plan.doc;
await User.updateOne({ _id: plan.doc._id }, { $set: setDoc });
return { updated: 1, inserted: 0, userId: plan.doc._id };
}
await User.insertOne(plan.doc);
return { updated: 0, inserted: 1, userId: plan.doc._id };
}
async function run() {
requireInput();
const client = new MongoClient(CONFIG.MONGODB_URI);
await client.connect();
try {
const db = client.db(CONFIG.LOLYMPUS_DB_NAME);
const User = db.collection("user");
const plan = await buildPlan(User);
const result = await applyPlan(User, plan);
return {
config: maskConfig(),
input: {
...INPUT,
puuid: INPUT.puuid ? "***provided***" : "",
},
result,
};
} finally {
await client.close();
}
}
if (require.main === module) {
run()
.then((result) => {
console.log(JSON.stringify(result, null, 2));
})
.catch((error) => {
console.error(error);
process.exitCode = 1;
});
}
+424
View File
@@ -0,0 +1,424 @@
/**
* Apply already-saved Dakao user bootstrap data into lolympus-test.user.
*
* This script does NOT call Riot API.
*
* It reads saved documents from one of:
* 1. lolympus-test.DakaoUserBootstrapRun
* 2. lolympus-test.DakaoUserBootstrapCandidate
*
* It only applies users that already have a valid Riot identity:
* - dryRunUsers[].doc.riotAccounts[0].puuid, or
* - candidate.riotApiResult.puuid, or
* - candidate.matchedRiotAccount.puuid
*
* Install:
* npm install mongodb
*
* Dry-run latest saved run:
* MONGODB_URI="mongodb://..." node apply-saved-dakao-riot-users.js
*
* Dry-run specific saved run:
* MONGODB_URI="mongodb://..." SOURCE=run RUN_ID="..." node apply-saved-dakao-riot-users.js
*
* Dry-run from candidate collection:
* MONGODB_URI="mongodb://..." SOURCE=candidate node apply-saved-dakao-riot-users.js
*
* Write:
* DRY_RUN=false MONGODB_URI="mongodb://..." node apply-saved-dakao-riot-users.js
*/
"use strict";
const { MongoClient, ObjectId } = require("mongodb");
const CONFIG = {
MONGODB_URI: process.env.MONGODB_URI ?? "mongodb://127.0.0.1:27017",
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-test",
COMMUNITY_ID: new ObjectId(
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
),
RUNS_COLLECTION_NAME:
process.env.RUNS_COLLECTION_NAME ?? "DakaoUserBootstrapRun",
CANDIDATES_COLLECTION_NAME:
process.env.CANDIDATES_COLLECTION_NAME ?? "DakaoUserBootstrapCandidate",
SOURCE: process.env.SOURCE ?? "run", // run | candidate
RUN_ID: process.env.RUN_ID ?? "",
DRY_RUN: process.env.DRY_RUN !== "false",
FORCE_REAPPLY_RUN: process.env.FORCE_REAPPLY_RUN === "true",
};
function normalizeString(value) {
return typeof value === "string" ? value.trim() : "";
}
function toObjectId(value, fieldName) {
if (value instanceof ObjectId) return value;
if (typeof value === "string" && ObjectId.isValid(value)) {
return new ObjectId(value);
}
throw new Error(`Invalid ObjectId for ${fieldName}: ${value}`);
}
function removeUndefined(value) {
if (Array.isArray(value)) {
return value.map(removeUndefined);
}
if (
value &&
typeof value === "object" &&
!(value instanceof Date) &&
!(value instanceof ObjectId)
) {
return Object.fromEntries(
Object.entries(value)
.filter(([, entryValue]) => entryValue !== undefined)
.map(([key, entryValue]) => [key, removeUndefined(entryValue)]),
);
}
return value;
}
function maskConfig() {
return {
...CONFIG,
MONGODB_URI: CONFIG.MONGODB_URI.replace(/\/\/.*@/u, "//***@"),
};
}
function hasValidRiotAccount(account) {
return Boolean(
normalizeString(account?.puuid) &&
normalizeString(account?.gameName) &&
normalizeString(account?.tagLine),
);
}
function ensureRiotAccountShape(account, now) {
return removeUndefined({
puuid: normalizeString(account.puuid),
gameName: normalizeString(account.gameName),
tagLine: normalizeString(account.tagLine),
profileIconId: account.profileIconId ?? 0,
revisionDate: account.revisionDate ?? 0,
summonerLevel: account.summonerLevel ?? 0,
isPrimary: true,
tiers: Array.isArray(account.tiers) ? account.tiers : [],
tierHistory: Array.isArray(account.tierHistory) ? account.tierHistory : [],
matchIds: Array.isArray(account.matchIds) ? account.matchIds : [],
matchIdsFetchedAt: account.matchIdsFetchedAt,
lastRefreshRequestedAt: account.lastRefreshRequestedAt,
recentStatsSummary: account.recentStatsSummary,
recentStatsFetchedAt: account.recentStatsFetchedAt,
championMasteries: Array.isArray(account.championMasteries)
? account.championMasteries
: [],
championMasteriesFetchedAt: account.championMasteriesFetchedAt,
championRecords: account.championRecords ?? {},
championRecordsFetchedAt: account.championRecordsFetchedAt,
createdAt: account.createdAt ?? now,
updatedAt: now,
});
}
function mergeRiotAccount(existingAccounts, nextAccount) {
const merged = (existingAccounts ?? [])
.filter(
(account) =>
account.puuid !== nextAccount.puuid &&
!(
normalizeString(account.gameName).toLowerCase() ===
normalizeString(nextAccount.gameName).toLowerCase() &&
normalizeString(account.tagLine).toLowerCase() ===
normalizeString(nextAccount.tagLine).toLowerCase()
),
)
.map((account) => ({ ...account, isPrimary: false }));
return [nextAccount, ...merged];
}
function buildPlanFromDryRunUser(planned, now) {
const doc = planned.doc ?? {};
const primary = doc.riotAccounts?.[0];
if (!hasValidRiotAccount(primary)) return null;
return {
source: "dryRunUsers",
originalMode: planned.mode,
filter: {
communityId: toObjectId(
planned.filter?.communityId ?? doc.communityId ?? CONFIG.COMMUNITY_ID,
"planned.communityId",
),
kakaoTalkId: normalizeString(planned.filter?.kakaoTalkId ?? doc.kakaoTalkId),
},
doc: removeUndefined({
_id:
doc._id && ObjectId.isValid(String(doc._id))
? toObjectId(doc._id, "planned.doc._id")
: new ObjectId(),
communityId: toObjectId(doc.communityId ?? CONFIG.COMMUNITY_ID, "doc.communityId"),
role: doc.role ?? "member",
kakaoTalkId: normalizeString(doc.kakaoTalkId),
kakaoTalkNickname: normalizeString(doc.kakaoTalkNickname),
riotAccounts: [ensureRiotAccountShape(primary, now)],
preferredPositions: Array.isArray(doc.preferredPositions)
? doc.preferredPositions
: [],
isActivated: doc.isActivated ?? true,
createdAt: doc.createdAt ?? now,
updatedAt: now,
}),
};
}
function buildPlanFromCandidate(candidate, now) {
const api = candidate.riotApiResult;
const matched = candidate.matchedRiotAccount;
const accountSource = hasValidRiotAccount(api) ? api : matched;
if (!hasValidRiotAccount(accountSource)) return null;
const account = ensureRiotAccountShape(
{
...matched,
...api,
profileIconId: candidate.riotEnrichment?.summoner?.profileIconId ?? 0,
revisionDate: candidate.riotEnrichment?.summoner?.revisionDate ?? 0,
summonerLevel: candidate.riotEnrichment?.summoner?.summonerLevel ?? 0,
tiers: (candidate.riotEnrichment?.leagueEntries ?? []).map((entry) => ({
leagueId: entry.leagueId,
queueType: entry.queueType,
tier: entry.tier,
rank: entry.rank,
puuid: entry.puuid,
leaguePoints: entry.leaguePoints ?? 0,
wins: entry.wins ?? 0,
losses: entry.losses ?? 0,
veteran: entry.veteran,
inactive: entry.inactive,
freshBlood: entry.freshBlood,
hotStreak: entry.hotStreak,
miniSeries: entry.miniSeries,
fetchedAt: now,
})),
tierHistory: (candidate.riotEnrichment?.leagueEntries ?? []).map(
(entry) => ({
queueType: entry.queueType,
tier: entry.tier,
rank: entry.rank,
leaguePoints: entry.leaguePoints ?? 0,
wins: entry.wins ?? 0,
losses: entry.losses ?? 0,
recordedAt: now,
}),
),
matchIds: candidate.riotEnrichment?.matchIds ?? [],
matchIdsFetchedAt:
candidate.riotEnrichment?.matchIds?.length > 0 ? now : undefined,
championMasteries: candidate.riotEnrichment?.championMasteries ?? [],
championMasteriesFetchedAt:
candidate.riotEnrichment?.championMasteries?.length > 0
? now
: undefined,
},
now,
);
return {
source: "candidate",
filter: {
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"),
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
},
doc: removeUndefined({
_id: new ObjectId(),
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"),
role: candidate.role ?? "member",
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
kakaoTalkNickname: normalizeString(
candidate.targetKakaoTalkNickname || candidate.kakaoTalkNickname,
),
riotAccounts: [account],
preferredPositions: Array.isArray(candidate.preferredPositions)
? candidate.preferredPositions
: [],
isActivated: candidate.isActivated ?? true,
createdAt: now,
updatedAt: now,
}),
};
}
function dedupePlans(plans) {
const byKakaoTalkId = new Map();
for (const plan of plans) {
if (!plan?.filter?.kakaoTalkId) continue;
byKakaoTalkId.set(plan.filter.kakaoTalkId, plan);
}
return [...byKakaoTalkId.values()];
}
async function loadLatestRun(Runs) {
if (CONFIG.RUN_ID) {
return Runs.findOne({ _id: toObjectId(CONFIG.RUN_ID, "RUN_ID") });
}
return Runs.findOne(
{ communityId: CONFIG.COMMUNITY_ID },
{ sort: { createdAt: -1 } },
);
}
async function loadPlansFromRun(lolympusDb, now) {
const Runs = lolympusDb.collection(CONFIG.RUNS_COLLECTION_NAME);
const run = await loadLatestRun(Runs);
if (!run) {
throw new Error("No saved DakaoUserBootstrapRun found.");
}
if (run.state === "applied" && !CONFIG.FORCE_REAPPLY_RUN) {
throw new Error(
`Run ${run._id.toString()} is already applied. Set FORCE_REAPPLY_RUN=true to re-apply.`,
);
}
const fromDryRunUsers = (run.upsertResult?.dryRunUsers ?? [])
.map((planned) => buildPlanFromDryRunUser(planned, now))
.filter(Boolean);
const fromCandidates = (run.candidates ?? [])
.map((candidate) => buildPlanFromCandidate(candidate, now))
.filter(Boolean);
const plans = dedupePlans(
fromDryRunUsers.length > 0 ? fromDryRunUsers : fromCandidates,
);
return { sourceRun: run, plans };
}
async function loadPlansFromCandidates(lolympusDb, now) {
const Candidate = lolympusDb.collection(CONFIG.CANDIDATES_COLLECTION_NAME);
const candidates = await Candidate.find({
communityId: CONFIG.COMMUNITY_ID,
}).toArray();
const plans = dedupePlans(
candidates.map((candidate) => buildPlanFromCandidate(candidate, now)).filter(Boolean),
);
return { sourceRun: null, plans };
}
async function applyPlans(lolympusDb, plans) {
const User = lolympusDb.collection("user");
const result = {
inserted: 0,
updated: 0,
skippedConflict: [],
errors: [],
dryRunUsers: [],
};
for (const plan of plans) {
try {
const primary = plan.doc.riotAccounts?.[0];
const conflict = await User.findOne({
communityId: plan.doc.communityId,
kakaoTalkId: { $ne: plan.doc.kakaoTalkId },
"riotAccounts.puuid": primary.puuid,
});
if (conflict) {
result.skippedConflict.push({
kakaoTalkId: plan.doc.kakaoTalkId,
riotId: `${primary.gameName}#${primary.tagLine}`,
puuid: primary.puuid,
existingUserId: conflict._id,
existingKakaoTalkId: conflict.kakaoTalkId,
});
continue;
}
const existing = await User.findOne(plan.filter);
const nextDoc = removeUndefined({
...plan.doc,
_id: existing?._id ?? plan.doc._id,
createdAt: existing?.createdAt ?? plan.doc.createdAt,
riotAccounts: mergeRiotAccount(existing?.riotAccounts, primary),
});
if (CONFIG.DRY_RUN) {
result.dryRunUsers.push({
mode: existing ? "update" : "insert",
filter: plan.filter,
doc: nextDoc,
});
continue;
}
if (existing) {
const { _id, createdAt, ...setDoc } = nextDoc;
await User.updateOne({ _id: existing._id }, { $set: setDoc });
result.updated += 1;
} else {
await User.insertOne(nextDoc);
result.inserted += 1;
}
} catch (error) {
result.errors.push({
kakaoTalkId: plan?.doc?.kakaoTalkId,
message: error instanceof Error ? error.message : String(error),
});
}
}
return result;
}
async function markRunApplied(lolympusDb, sourceRun, applyResult) {
if (!sourceRun || CONFIG.DRY_RUN) return;
const Runs = lolympusDb.collection(CONFIG.RUNS_COLLECTION_NAME);
await Runs.updateOne(
{ _id: sourceRun._id },
{
$set: {
state: applyResult.errors.length > 0 ? "apply-partial" : "applied",
appliedAt: new Date(),
updatedAt: new Date(),
applyResult,
},
},
);
}
async function run() {
const client = new MongoClient(CONFIG.MONGODB_URI);
await client.connect();
try {
const lolympusDb = client.db(CONFIG.LOLYMPUS_DB_NAME);
const now = new Date();
const { sourceRun, plans } =
CONFIG.SOURCE === "candidate"
? await loadPlansFromCandidates(lolympusDb, now)
: await loadPlansFromRun(lolympusDb, now);
const applyResult = await applyPlans(lolympusDb, plans);
await markRunApplied(lolympusDb, sourceRun, applyResult);
return {
config: maskConfig(),
source: CONFIG.SOURCE,
sourceRunId: sourceRun?._id ?? null,
planCount: plans.length,
applyResult,
};
} finally {
await client.close();
}
}
if (require.main === module) {
run()
.then((result) => {
console.log(JSON.stringify(result, null, 2));
})
.catch((error) => {
console.error(error);
process.exitCode = 1;
});
}
File diff suppressed because it is too large. Load diff
+109
View File
@@ -0,0 +1,109 @@
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const repoRoot = resolve(__dirname, '..');
const webDir = resolve(repoRoot, 'apps/web');
const target = process.argv[2];
if (target !== 'test' && target !== 'prod') {
console.error('Usage: node scripts/deploy-cloudflare-pages.mjs <test|prod>');
process.exit(1);
}
const viteMode = target === 'prod' ? 'production' : 'test';
const projectName =
process.env.CF_PAGES_PROJECT_NAME ??
process.env.CLOUDFLARE_PAGES_PROJECT_NAME ??
'lolympus';
const testBranch = process.env.CF_PAGES_TEST_BRANCH ?? 'test';
validateEnv(viteMode);
run('pnpm', ['--filter', 'web', 'run', `build:${target}`], repoRoot);
const deployArgs = [
'exec',
'wrangler',
'pages',
'deploy',
'dist',
'--project-name',
projectName,
];
if (target === 'test') {
deployArgs.push('--branch', testBranch);
}
run('pnpm', deployArgs, webDir);
function run(command, args, cwd) {
const result = spawnSync(command, args, {
cwd,
stdio: 'inherit',
shell: process.platform === 'win32',
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
}
function validateEnv(mode) {
const fileEnv = [
'.env',
'.env.local',
`.env.${mode}`,
`.env.${mode}.local`,
].reduce((acc, fileName) => {
const envFile = resolve(webDir, fileName);
if (!existsSync(envFile)) return acc;
return { ...acc, ...parseEnvFile(envFile) };
}, {});
const requiredKeys = [
'VITE_API_BASE_URL',
'VITE_DEFAULT_COMMUNITY_ID',
'VITE_MSAL_CLIENT_ID',
'VITE_MSAL_AUTHORITY',
'VITE_MSAL_API_SCOPE',
'VITE_MSAL_REDIRECT_URI',
];
const missing = requiredKeys.filter((key) => {
const value = process.env[key] ?? fileEnv[key];
return !value || value.includes('<');
});
if (missing.length === 0) return;
console.error(
[
`Missing Cloudflare Pages ${mode} build env: ${missing.join(', ')}`,
`Create apps/web/.env.${mode}, apps/web/.env.${mode}.local, or export these variables before deploy.`,
`Use apps/web/.env.${mode}.example as a template.`,
].join('\n'),
);
process.exit(1);
}
function parseEnvFile(path) {
return Object.fromEntries(
readFileSync(path, 'utf8')
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'))
.map((line) => {
const separatorIndex = line.indexOf('=');
if (separatorIndex === -1) return [line, ''];
const key = line.slice(0, separatorIndex).trim();
let value = line.slice(separatorIndex + 1).trim();
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
return [key, value];
}),
);
}