/** * 使用者與個人統計儲存庫。結構比照 `repository.ts`(鬼影): * InMemoryUserRepository(基底)→ UpstashUserRepository(跨重啟保存)/ JsonFileUserRepository(本機檔)。 * * 設計取捨: * - **使用者與統計持久化**(Upstash / JSON 檔)——這是「跨裝置」的關鍵。 * - **session 只存記憶體**(不持久化):重啟後 token 失效、使用者重新 OAuth 登入即可(一鍵、體驗可接受), * 換來介面同步、無 Redis session 讀寫成本與過期管理複雜度。統計不受 session 失效影響。 */ import { randomUUID } from "node:crypto"; import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; import { dirname } from "node:path"; import type { Campaign, ClassType, RunSummary } from "@wcg/battle-core"; export type RunKind = "single" | "pvp" | "pve"; /** 單場紀錄:單人=該場摘要欄位;pvp/pve=勝負+對手/Boss 名(單人專屬欄位省略)。kind 省略=單人(相容舊資料)。 */ export interface RunRecord { at: string; kind?: RunKind; classType: ClassType; cleared: boolean; campaign?: Campaign; hardMode?: boolean; extreme?: boolean; // 極難(insane);隱含 hardMode reachedStage?: number; peakAtk?: number; peakDef?: number; turns?: number; outcome?: "VICTORY" | "GAME_OVER"; enemyName?: string; // 連線專屬:pvp="對手"、pve=Boss 名 } /** 連線(pvp/pve)結果輸入(後端無法重播 → 直接採信此結果,只進逐場紀錄與職業計數)。 */ export interface OnlineRunInput { kind: "pvp" | "pve"; classType: ClassType; cleared: boolean; enemyName: string; } const MAX_RUNS = 100; export interface UserStats { plays: number; // 遊玩次數(總場數) clears: number; // 過關次數(破完整 campaign) peakAtk: number; // 單回合峰值 ATK(跨場取 max) peakDef: number; // 單回合峰值 DEF(跨場取 max) maxReachedStage: number; // 未過關時到達的最高 Stage(全路線合併;保留相容) // 各「敵人×難度」的最高到達 Stage(含破關=到達該路線最終關)。key:`slime`/`slime:hard`/`sanctus`/`sanctus:hard` maxStageByMode?: Record; totalTurns: number; // 生涯總回合數(累加型統計示範) classPlays: Partial>; // 各職業遊玩場數(動態 key:日後新增職業免改此型別) recentClasses: ClassType[]; // 最近 100 場的職業序列(算「前 100 場最常使用職業」用,最新在尾) lastPlayedAt?: string; // 最後遊玩時間(後端 now,不信 client 時鐘) runs?: RunRecord[]; // 最近 N 場逐場紀錄(舊→新);統計頁點數字可跳出「遊玩紀錄」 } export interface UserRecord { id: string; provider: string; // "discord" | "google" | "dev" providerUserId: string; displayName: string; email?: string; // 目前只有 Google 帶;僅供管理員白名單比對,不對外投影 createdAt: string; stats: UserStats; } export function emptyStats(): UserStats { return { plays: 0, clears: 0, peakAtk: 0, peakDef: 0, maxReachedStage: 0, maxStageByMode: {}, totalTurns: 0, classPlays: {}, recentClasses: [], runs: [] }; } /** 「敵人×難度」統計 key:normal=campaign 本身;hard=加 :hard;insane(extreme)=加 :extreme。 */ export function stageModeKey(campaign: string, hardMode?: boolean, extreme?: boolean): string { if (extreme) return `${campaign}:extreme`; return hardMode ? `${campaign}:hard` : campaign; } /** * 把一場 RunSummary 聚合進既有統計(純函式、冪等於 peak)。 * 注意:summary 由後端重播產生(權威),此處不再夾值;除錯關卡數的 cleared 修正在 runService 先處理。 */ export function applyRun(stats: UserStats, s: RunSummary, nowIso: string): UserStats { // 舊帳號的 stats 可能缺後來才加的欄位(recentClasses/runs/maxStageByMode…)→ 下方 spread 到 undefined 會拋 // 「not iterable」讓 /api/me/runs 回 500、戰績永遠記不進去。先用 emptyStats() 補齊缺欄位:修崩潰, // 且首次成功聚合後該帳號即被寫成完整結構(自我修復),無須額外資料遷移。 const prev = { ...emptyStats(), ...stats }; const prevStage = prev.maxStageByMode ?? {}; const k = stageModeKey(s.campaign, s.hardMode, s.extreme); return { plays: prev.plays + 1, clears: prev.clears + (s.cleared ? 1 : 0), peakAtk: Math.max(prev.peakAtk, s.peakAtk), peakDef: Math.max(prev.peakDef, s.peakDef), // 「未過關時到達的最高 Stage」:破關場不更新此值(破關走 clears)。 maxReachedStage: s.cleared ? prev.maxReachedStage : Math.max(prev.maxReachedStage, s.reachedStage), // 各敵人×難度的最高 Stage:含破關(reachedStage=最終關),普通/困難分開累積。 maxStageByMode: { ...prevStage, [k]: Math.max(prevStage[k] ?? 0, s.reachedStage) }, totalTurns: prev.totalTurns + s.turns, // 動態累加:以 classType 為 key 累加 → 日後新增職業不必改這裡(新 key 自動長出來)。 classPlays: { ...prev.classPlays, [s.classType]: (prev.classPlays[s.classType] ?? 0) + 1 }, // 最近 100 場職業(環形緩衝,最新在尾)→ 算「前 100 場最常使用職業」。 recentClasses: [...(prev.recentClasses ?? []), s.classType].slice(-100), // 逐場紀錄(含難度/敵人/到達/結果/峰值),只留最近 N 場供「遊玩紀錄」彈窗。 runs: [...(prev.runs ?? []), { ...s, at: nowIso }].slice(-MAX_RUNS), lastPlayedAt: nowIso, }; } /** 把一場連線(pvp/pve)結果聚合進統計:只進逐場紀錄與職業計數,不污染單人關卡/峰值聚合。 */ export function applyOnlineRun(stats: UserStats, o: OnlineRunInput, nowIso: string): UserStats { const prev = { ...emptyStats(), ...stats }; const rec: RunRecord = { at: nowIso, kind: o.kind, classType: o.classType, cleared: o.cleared, enemyName: o.enemyName }; return { ...prev, classPlays: { ...prev.classPlays, [o.classType]: (prev.classPlays[o.classType] ?? 0) + 1 }, recentClasses: [...(prev.recentClasses ?? []), o.classType].slice(-MAX_RUNS), runs: [...(prev.runs ?? []), rec].slice(-MAX_RUNS), lastPlayedAt: nowIso, }; } export interface UserRepository { /** 依 OAuth 身分找既有帳號或建新帳號(並更新顯示名 / email)。 */ upsertByOAuth(provider: string, providerUserId: string, displayName: string, email?: string): UserRecord; getById(id: string): UserRecord | null; /** 聚合一場單人結果到該使用者統計,回傳更新後統計;找不到使用者回 null。 */ updateStats(id: string, summary: RunSummary, nowIso: string): UserStats | null; /** 聚合一場連線(pvp/pve)結果;找不到使用者回 null。 */ updateOnlineStats(id: string, online: OnlineRunInput, nowIso: string): UserStats | null; putSession(token: string, userId: string, ttlSec: number, nowMs: number): void; getSession(token: string, nowMs: number): string | null; deleteSession(token: string): void; count(): number; /** 列出所有使用者(管理用;Upstash/JSON 版都已把全部載入記憶體快取,故由基底實作即可)。 */ listAll(): UserRecord[]; } /** 純記憶體(測試用,亦為基底)。session 一律在此層、不持久化。 */ export class InMemoryUserRepository implements UserRepository { protected byId = new Map(); protected oauthIndex = new Map(); // `${provider}:${providerUserId}` → userId private sessions = new Map(); static readonly MAX_SESSIONS = 50000; // 防無界成長 private oauthKey(provider: string, providerUserId: string): string { return `${provider}:${providerUserId}`; } upsertByOAuth(provider: string, providerUserId: string, displayName: string, email?: string): UserRecord { const key = this.oauthKey(provider, providerUserId); const existingId = this.oauthIndex.get(key); if (existingId) { const rec = this.byId.get(existingId)!; let changed = false; if (displayName && rec.displayName !== displayName) { rec.displayName = displayName; changed = true; } if (email && rec.email !== email) { rec.email = email; changed = true; } if (changed) this.persistUser(rec, false); return rec; } const rec: UserRecord = { id: randomUUID(), provider, providerUserId, displayName: displayName || `${provider}-user`, email, createdAt: new Date().toISOString(), stats: emptyStats(), }; this.byId.set(rec.id, rec); this.oauthIndex.set(key, rec.id); this.persistUser(rec, true); return rec; } getById(id: string): UserRecord | null { return this.byId.get(id) ?? null; } updateStats(id: string, summary: RunSummary, nowIso: string): UserStats | null { const rec = this.byId.get(id); if (!rec) return null; rec.stats = applyRun(rec.stats, summary, nowIso); // 讀-改-寫,單實例同步完成 → 無覆寫競態 this.persistUser(rec, false); return rec.stats; } updateOnlineStats(id: string, online: OnlineRunInput, nowIso: string): UserStats | null { const rec = this.byId.get(id); if (!rec) return null; rec.stats = applyOnlineRun(rec.stats, online, nowIso); this.persistUser(rec, false); return rec.stats; } putSession(token: string, userId: string, ttlSec: number, nowMs: number): void { // 達上限不再整批 clear()(會讓所有在線 token 同時失效):先回收過期死 session,仍滿才用插入序砍最舊一批。 if (this.sessions.size >= InMemoryUserRepository.MAX_SESSIONS) { for (const [t, s] of this.sessions) if (s.exp <= nowMs) this.sessions.delete(t); // 回收死 session if (this.sessions.size >= InMemoryUserRepository.MAX_SESSIONS) { const drop = Math.ceil(InMemoryUserRepository.MAX_SESSIONS * 0.1); // Map 天然 FIFO → 砍最舊 10% let i = 0; for (const t of this.sessions.keys()) { if (i++ >= drop) break; this.sessions.delete(t); } } } this.sessions.set(token, { userId, exp: nowMs + ttlSec * 1000 }); } getSession(token: string, nowMs: number): string | null { const s = this.sessions.get(token); if (!s) return null; if (s.exp <= nowMs) { this.sessions.delete(token); return null; } // 過期 lazy 清除 return s.userId; } deleteSession(token: string): void { this.sessions.delete(token); } count(): number { return this.byId.size; } listAll(): UserRecord[] { return [...this.byId.values()]; } /** 持久化單一使用者。記憶體版不做事;isNew 供子類決定是否一併寫索引。 */ protected persistUser(_rec: UserRecord, _isNew: boolean): void { /* 記憶體版不持久化 */ } } /** JSON 檔持久化版(本機)。每次變更寫整份使用者清單(量小、夠用)。 */ export class JsonFileUserRepository extends InMemoryUserRepository { private file: string; constructor(file: string) { super(); this.file = file; if (existsSync(file)) { try { const parsed = JSON.parse(readFileSync(file, "utf8")) as UserRecord[]; if (Array.isArray(parsed)) { for (const rec of parsed) { if (rec && typeof rec.id === "string") { this.byId.set(rec.id, rec); this.oauthIndex.set(`${rec.provider}:${rec.providerUserId}`, rec.id); } } } } catch { /* 壞檔則以空起始 */ } } } protected override persistUser(_rec: UserRecord, _isNew: boolean): void { mkdirSync(dirname(this.file), { recursive: true }); const tmp = `${this.file}.tmp`; writeFileSync(tmp, JSON.stringify([...this.byId.values()]), "utf8"); // 緊湊序列化(去 pretty) renameSync(tmp, this.file); // 原子置換:避免崩潰留下半截檔讓整份使用者資料毀損 } } /** * Upstash Redis(REST)持久化版。比照 UpstashGhostRepository:開機 load() 載入記憶體快取, * 之後讀走同步介面;變更同步更新快取後「背景」寫回(失敗只記錄)。 */ export class UpstashUserRepository extends InMemoryUserRepository { private url: string; private token: string; private static readonly IDS_KEY = "wcg:user_ids"; private static readonly SESSION_PREFIX = "wcg:session:"; private userKey(id: string): string { return `wcg:user:${id}`; } private oauthRedisKey(provider: string, providerUserId: string): string { return `wcg:oauth:${provider}:${providerUserId}`; } private sessionKey(token: string): string { return `${UpstashUserRepository.SESSION_PREFIX}${token}`; } constructor(url: string, token: string) { super(); this.url = url.trim().replace(/\/+$/, ""); this.token = token.trim(); } private async redis(cmd: string[]): Promise { const res = await fetch(this.url, { method: "POST", headers: { Authorization: `Bearer ${this.token}`, "Content-Type": "application/json" }, body: JSON.stringify(cmd), }); if (!res.ok) throw new Error(`upstash HTTP ${res.status}`); const json = (await res.json()) as { result?: unknown; error?: string }; if (json.error) throw new Error(json.error); return json.result; } private async pipeline(cmds: string[][]): Promise { const res = await fetch(`${this.url}/pipeline`, { method: "POST", headers: { Authorization: `Bearer ${this.token}`, "Content-Type": "application/json" }, body: JSON.stringify(cmds), }); if (!res.ok) throw new Error(`upstash HTTP ${res.status}`); const arr = (await res.json()) as { result?: unknown; error?: string }[]; for (const j of arr) if (j.error) throw new Error(j.error); } /** 開機載入:把 Upstash 內使用者與未過期 session 載入記憶體快取。 */ async load(): Promise { const ids = (await this.redis(["LRANGE", UpstashUserRepository.IDS_KEY, "0", "-1"])) as string[] | null; if (ids && ids.length > 0) { const vals = (await this.redis(["MGET", ...ids.map((id) => this.userKey(id))])) as (string | null)[]; for (const v of vals) { if (!v) continue; try { const rec = JSON.parse(v) as UserRecord; if (rec && typeof rec.id === "string") { this.byId.set(rec.id, rec); this.oauthIndex.set(`${rec.provider}:${rec.providerUserId}`, rec.id); } } catch { /* 略過壞資料 */ } } } await this.loadSessions(); } /** 載入未過期 session 到記憶體快取(SCAN 自清:已過 Redis TTL 的 key 不會出現 → 重啟後登入狀態仍在)。 */ private async loadSessions(): Promise { const now = Date.now(); let cursor = "0"; do { const reply = (await this.redis(["SCAN", cursor, "MATCH", `${UpstashUserRepository.SESSION_PREFIX}*`, "COUNT", "300"])) as [string, string[]]; cursor = reply?.[0] ?? "0"; const keys = reply?.[1] ?? []; if (keys.length > 0) { const vals = (await this.redis(["MGET", ...keys])) as (string | null)[]; for (let i = 0; i < keys.length; i++) { const v = vals[i]; if (!v) continue; try { const { userId, exp } = JSON.parse(v) as { userId: string; exp: number }; const ttlSec = Math.ceil((exp - now) / 1000); if (userId && ttlSec > 0) super.putSession(keys[i]!.slice(UpstashUserRepository.SESSION_PREFIX.length), userId, ttlSec, now); } catch { /* 略過壞資料 */ } } } } while (cursor !== "0"); } protected override persistUser(rec: UserRecord, isNew: boolean): void { const cmds: string[][] = [["SET", this.userKey(rec.id), JSON.stringify(rec)]]; if (isNew) { cmds.push(["SET", this.oauthRedisKey(rec.provider, rec.providerUserId), rec.id]); cmds.push(["RPUSH", UpstashUserRepository.IDS_KEY, rec.id]); } void this.pipeline(cmds).catch((e) => console.error("[users] Upstash 持久化失敗:", e)); } // session 也持久化到 Redis(帶原生 TTL)→ 容器休眠/重啟後登入狀態仍在,不會把使用者打成遊客。 // 記憶體快取(基底 Map)仍是同步讀的唯一來源;Redis 僅供重啟後由 loadSessions() 還原。 override putSession(token: string, userId: string, ttlSec: number, nowMs: number): void { super.putSession(token, userId, ttlSec, nowMs); const ttl = Math.max(1, Math.ceil(ttlSec)); const val = JSON.stringify({ userId, exp: nowMs + ttl * 1000 }); void this.redis(["SET", this.sessionKey(token), val, "EX", String(ttl)]).catch((e) => console.error("[session] Upstash 寫入失敗:", e)); } override deleteSession(token: string): void { super.deleteSession(token); void this.redis(["DEL", this.sessionKey(token)]).catch((e) => console.error("[session] Upstash 刪除失敗:", e)); } }