chore(env): rename test environment to staging

This commit is contained in:
dahyeon committed 2026-06-07 01:01:13 -07:00
1 parent d0d578b2b0
commit eadae789c8
17 files changed
+160 -107

No files matched your search

+17 -10
View File
@@ -28,7 +28,7 @@ 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",
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-staging",
COMMUNITY_ID: new ObjectId(
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
),
@@ -137,14 +137,18 @@ async function fetchRiotJson({ host, path, query }) {
});
if (response.status === 429) {
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1);
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}`);
throw new Error(
`Riot API failed ${response.status} ${url.pathname}: ${body}`,
);
}
return response.json();
}
@@ -190,13 +194,14 @@ async function fetchRecentMatchIdsByPuuid(puuid) {
async function fetchRiotData({ riotId }) {
const fallback = splitRiotId(riotId);
const account =
(await fetchAccountByRiotId(fallback)) ?? {
...fallback,
puuid: normalizeString(INPUT.puuid),
};
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}`);
throw new Error(
`Riot account not found and PUUID was not provided: ${riotId}`,
);
}
const [summoner, leagueEntries, championMasteries, matchIds] =
@@ -280,7 +285,9 @@ function buildRiotAccount(riotData, now) {
summonerLevel: riotData.summoner?.summonerLevel ?? 0,
isPrimary: true,
tiers: riotData.leagueEntries.map((entry) => toTierInfo(entry, now)),
tierHistory: riotData.leagueEntries.map((entry) => toTierHistory(entry, now)),
tierHistory: riotData.leagueEntries.map((entry) =>
toTierHistory(entry, now),
),
matchIds: riotData.matchIds,
matchIdsFetchedAt: riotData.matchIds.length > 0 ? now : undefined,
championMasteries: riotData.championMasteries
+24 -11
View File
@@ -1,11 +1,11 @@
/**
* Apply already-saved Dakao user bootstrap data into lolympus-test.user.
* Apply already-saved Dakao user bootstrap data into lolympus-staging.user.
*
* This script does NOT call Riot API.
*
* It reads saved documents from one of:
* 1. lolympus-test.DakaoUserBootstrapRun
* 2. lolympus-test.DakaoUserBootstrapCandidate
* 1. lolympus-staging.DakaoUserBootstrapRun
* 2. lolympus-staging.DakaoUserBootstrapCandidate
*
* It only applies users that already have a valid Riot identity:
* - dryRunUsers[].doc.riotAccounts[0].puuid, or
@@ -34,7 +34,7 @@ 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",
LOLYMPUS_DB_NAME: process.env.LOLYMPUS_DB_NAME ?? "lolympus-staging",
COMMUNITY_ID: new ObjectId(
process.env.COMMUNITY_ID ?? "69ebe0adf627c11be2f020a1",
),
@@ -89,8 +89,8 @@ function maskConfig() {
function hasValidRiotAccount(account) {
return Boolean(
normalizeString(account?.puuid) &&
normalizeString(account?.gameName) &&
normalizeString(account?.tagLine),
normalizeString(account?.gameName) &&
normalizeString(account?.tagLine),
);
}
@@ -151,14 +151,19 @@ function buildPlanFromDryRunUser(planned, now) {
planned.filter?.communityId ?? doc.communityId ?? CONFIG.COMMUNITY_ID,
"planned.communityId",
),
kakaoTalkId: normalizeString(planned.filter?.kakaoTalkId ?? doc.kakaoTalkId),
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"),
communityId: toObjectId(
doc.communityId ?? CONFIG.COMMUNITY_ID,
"doc.communityId",
),
role: doc.role ?? "member",
kakaoTalkId: normalizeString(doc.kakaoTalkId),
kakaoTalkNickname: normalizeString(doc.kakaoTalkNickname),
@@ -228,12 +233,18 @@ function buildPlanFromCandidate(candidate, now) {
return {
source: "candidate",
filter: {
communityId: toObjectId(candidate.communityId ?? CONFIG.COMMUNITY_ID, "candidate.communityId"),
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"),
communityId: toObjectId(
candidate.communityId ?? CONFIG.COMMUNITY_ID,
"candidate.communityId",
),
role: candidate.role ?? "member",
kakaoTalkId: normalizeString(candidate.kakaoTalkId),
kakaoTalkNickname: normalizeString(
@@ -300,7 +311,9 @@ async function loadPlansFromCandidates(lolympusDb, now) {
communityId: CONFIG.COMMUNITY_ID,
}).toArray();
const plans = dedupePlans(
candidates.map((candidate) => buildPlanFromCandidate(candidate, now)).filter(Boolean),
candidates
.map((candidate) => buildPlanFromCandidate(candidate, now))
.filter(Boolean),
);
return { sourceRun: null, plans };
}
+32 -15
View File
@@ -19,7 +19,7 @@
* -> join nickname base with RiotAccount.gameName
* -> verify/fetch puuid from Riot Account API
* -> fetch summoner / league / mastery / recent match ids from Riot API
* -> upsert lolympus-test.user
* -> upsert lolympus-staging.user
*/
"use strict";
@@ -32,7 +32,7 @@ const CONFIG = {
RIOT_API_KEY: process.env.RIOT_API_KEY ?? "",
DAKAO_DB_NAME: "dakao",
LOLYMPUS_DB_NAME: "lolympus-test",
LOLYMPUS_DB_NAME: "lolympus-staging",
RIOT_ACCOUNT_DB_NAME: process.env.RIOT_ACCOUNT_DB_NAME ?? "dakao",
RIOT_ACCOUNT_COLLECTION_NAME:
process.env.RIOT_ACCOUNT_COLLECTION_NAME ?? "RiotAccount",
@@ -50,7 +50,7 @@ const CONFIG = {
RECENT_MATCH_COUNT: Number(process.env.RECENT_MATCH_COUNT ?? 20),
FETCH_RECENT_MATCH_IDS: process.env.FETCH_RECENT_MATCH_IDS !== "false",
// Safe default. Set DRY_RUN=false to write into lolympus-test.user.
// Safe default. Set DRY_RUN=false to write into lolympus-staging.user.
DRY_RUN: process.env.DRY_RUN !== "false",
SAVE_DRY_RUN_RESULT: process.env.SAVE_DRY_RUN_RESULT !== "false",
OUTPUT_ONLY_RIOT_MATCHED: process.env.OUTPUT_ONLY_RIOT_MATCHED !== "false",
@@ -163,10 +163,10 @@ function maskConfigForStorage() {
function isRiotMatchedCandidate(candidate) {
return Boolean(
candidate.matchedRiotAccount &&
candidate.ambiguousRiotAccounts?.length === 0 &&
candidate.riotApiResult &&
!candidate.riotApiError &&
!candidate.riotEnrichmentError,
candidate.ambiguousRiotAccounts?.length === 0 &&
candidate.riotApiResult &&
!candidate.riotApiError &&
!candidate.riotEnrichmentError,
);
}
@@ -214,7 +214,10 @@ function remember(map, kakaoTalkId, patch) {
const nickname =
normalizeString(patch.kakaoTalkNickname) ||
normalizeString(current.kakaoTalkNickname);
const sources = new Set([...(current.sources ?? []), ...(patch.sources ?? [])]);
const sources = new Set([
...(current.sources ?? []),
...(patch.sources ?? []),
]);
const lastSeenCandidates = [current.lastSeenAt, patch.lastSeenAt]
.filter(Boolean)
.map((value) => new Date(value));
@@ -229,7 +232,9 @@ function remember(map, kakaoTalkId, patch) {
sources: [...sources],
lastSeenAt:
lastSeenCandidates.length > 0
? new Date(Math.max(...lastSeenCandidates.map((date) => date.getTime())))
? new Date(
Math.max(...lastSeenCandidates.map((date) => date.getTime())),
)
: null,
recentMessageCount:
(current.recentMessageCount ?? 0) + (patch.recentMessageCount ?? 0),
@@ -361,7 +366,12 @@ function pickRiotAccountForCandidate(candidate, index) {
const nicknameBase = candidate.nicknameBase;
if (!nicknameBase) {
return { source: "no-nickname-base", account: null, override, ambiguous: [] };
return {
source: "no-nickname-base",
account: null,
override,
ambiguous: [],
};
}
const exactMatches = index.exact.get(normalizeJoinKey(nicknameBase)) ?? [];
@@ -422,7 +432,9 @@ async function fetchRiotJson({ host, path, query }) {
});
if (response.status === 429) {
const retryAfterSeconds = Number(response.headers.get("retry-after") ?? 1);
const retryAfterSeconds = Number(
response.headers.get("retry-after") ?? 1,
);
await sleep(Math.max(1, retryAfterSeconds) * 1000);
continue;
}
@@ -431,7 +443,9 @@ async function fetchRiotJson({ host, path, query }) {
if (!response.ok) {
const body = await response.text().catch(() => "");
throw new Error(`Riot API failed ${response.status} ${url.pathname}: ${body}`);
throw new Error(
`Riot API failed ${response.status} ${url.pathname}: ${body}`,
);
}
return response.json();
@@ -670,11 +684,14 @@ async function enrichCandidatesWithRiot({ candidates, riotAccountIndex }) {
riotApiError,
riotEnrichment,
riotEnrichmentError,
preferredPositions: normalizePositions(match.override?.preferredPositions),
preferredPositions: normalizePositions(
match.override?.preferredPositions,
),
role: match.override?.role ?? "member",
isActivated: match.override?.isActivated ?? true,
targetKakaoTalkNickname:
normalizeString(match.override?.nickname) || candidate.kakaoTalkNickname,
normalizeString(match.override?.nickname) ||
candidate.kakaoTalkNickname,
});
}
@@ -798,7 +815,7 @@ async function upsertUsers({ lolympusDb, candidates }) {
preferredPositions:
candidate.preferredPositions?.length > 0
? candidate.preferredPositions
: existing?.preferredPositions ?? [],
: (existing?.preferredPositions ?? []),
isActivated: candidate.isActivated ?? true,
updatedAt: now,
};
+40 -38
View File
@@ -1,49 +1,51 @@
import { spawnSync } from 'node:child_process';
import { existsSync, readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
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 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>');
if (target !== "staging" && target !== "prod") {
console.error(
"Usage: node scripts/deploy-cloudflare-pages.mjs <staging|prod>",
);
process.exit(1);
}
const viteMode = target === 'prod' ? 'production' : 'test';
const viteMode = target === "prod" ? "production" : "staging";
const projectName =
process.env.CF_PAGES_PROJECT_NAME ??
process.env.CLOUDFLARE_PAGES_PROJECT_NAME ??
'lolympus';
const testBranch = process.env.CF_PAGES_TEST_BRANCH ?? 'test';
"lolympus";
const stagingBranch = process.env.CF_PAGES_STAGING_BRANCH ?? "staging";
validateEnv(viteMode);
run('pnpm', ['--filter', 'web', 'run', `build:${target}`], repoRoot);
run("pnpm", ["--filter", "web", "run", `build:${target}`], repoRoot);
const deployArgs = [
'exec',
'wrangler',
'pages',
'deploy',
'dist',
'--project-name',
"exec",
"wrangler",
"pages",
"deploy",
"dist",
"--project-name",
projectName,
];
if (target === 'test') {
deployArgs.push('--branch', testBranch);
if (target === "staging") {
deployArgs.push("--branch", stagingBranch);
}
run('pnpm', deployArgs, webDir);
run("pnpm", deployArgs, webDir);
function run(command, args, cwd) {
const result = spawnSync(command, args, {
cwd,
stdio: 'inherit',
shell: process.platform === 'win32',
stdio: "inherit",
shell: process.platform === "win32",
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
@@ -52,8 +54,8 @@ function run(command, args, cwd) {
function validateEnv(mode) {
const fileEnv = [
'.env',
'.env.local',
".env",
".env.local",
`.env.${mode}`,
`.env.${mode}.local`,
].reduce((acc, fileName) => {
@@ -62,39 +64,39 @@ function validateEnv(mode) {
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',
"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('<');
return !value || value.includes("<");
});
if (missing.length === 0) return;
console.error(
[
`Missing Cloudflare Pages ${mode} build env: ${missing.join(', ')}`,
`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'),
].join("\n"),
);
process.exit(1);
}
function parseEnvFile(path) {
return Object.fromEntries(
readFileSync(path, 'utf8')
readFileSync(path, "utf8")
.split(/\r?\n/)
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'))
.filter((line) => line && !line.startsWith("#"))
.map((line) => {
const separatorIndex = line.indexOf('=');
if (separatorIndex === -1) return [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 (