File size: 9,144 Bytes
1302ebc
 
 
 
 
 
76e92fa
1302ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebdbff1
1302ebc
 
 
76e92fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1302ebc
 
 
 
 
 
 
 
758be85
 
 
 
 
 
 
 
 
 
3443892
 
 
 
 
 
 
 
 
1302ebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e92fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1302ebc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
import { describe, it, expect, vi, afterEach } from "vitest";
import {
  InMemoryUserRepository,
  UpstashUserRepository,
  emptyStats,
  type UserRecord,
  type UserStats,
} from "../src/userRepository.js";
import type { RunSummary } from "@wcg/battle-core";

afterEach(() => { vi.unstubAllGlobals(); });

const sum = (over: Partial<RunSummary> = {}): RunSummary => ({
  classType: "WARRIOR", campaign: "slime",
  peakAtk: 0, peakDef: 0, reachedStage: 1, turns: 0, cleared: false, outcome: "GAME_OVER", ...over,
});

describe("InMemoryUserRepository — 帳號", () => {
  it("upsertByOAuth:同 provider+id 視為同帳號,改名會更新", () => {
    const repo = new InMemoryUserRepository();
    const a = repo.upsertByOAuth("discord", "123", "Alice");
    expect(repo.count()).toBe(1);
    const again = repo.upsertByOAuth("discord", "123", "Alice2");
    expect(again.id).toBe(a.id); // 同帳號
    expect(repo.count()).toBe(1);
    expect(repo.getById(a.id)?.displayName).toBe("Alice2"); // 改名
    // 不同 provider 即使同 id 也是不同帳號
    repo.upsertByOAuth("google", "123", "Bob");
    expect(repo.count()).toBe(2);
  });
});

describe("InMemoryUserRepository — 統計聚合", () => {
  it("連報兩場:peak 取 max、plays/clears 累加、maxReachedStage 僅未過關更新、classPlays 計數", () => {
    const repo = new InMemoryUserRepository();
    const u = repo.upsertByOAuth("dev", "u", "U");
    repo.updateStats(u.id, sum({ outcome: "GAME_OVER", reachedStage: 4, peakAtk: 10, peakDef: 3, turns: 5, cleared: false }), "t1");
    const s = repo.updateStats(u.id, sum({ outcome: "VICTORY", reachedStage: 11, peakAtk: 20, peakDef: 1, turns: 7, cleared: true }), "t2");
    expect(s).toMatchObject({ plays: 2, clears: 1, peakAtk: 20, peakDef: 3, maxReachedStage: 4, totalTurns: 12 });
    expect(s?.classPlays.WARRIOR).toBe(2);
    expect(s?.recentClasses).toEqual(["WARRIOR", "WARRIOR"]); // 最近 100 場序列
    expect(s?.lastPlayedAt).toBe("t2");
  });

  // 回歸:早期版本存下的精簡 stats 缺 recentClasses/runs/maxStageByMode → 舊版 applyRun 的 [...undefined]
  // 會丟「recentClasses is not iterable」讓 /api/me/runs 回 500、戰績永遠記不進去。修法應補齊缺欄位、不再拋。
  it("舊帳號 stats 缺欄位(早期 schema)→ updateStats 不再丟例外、且補齊結構", () => {
    const repo = new InMemoryUserRepository();
    const u = repo.upsertByOAuth("google", "legacy", "李侑霖");
    const rec = repo.getById(u.id)!;
    // 模擬線上實際看到的精簡 stats(缺 recentClasses / runs / maxStageByMode)
    rec.stats = { plays: 0, clears: 0, peakAtk: 0, peakDef: 0, maxReachedStage: 0, totalTurns: 0, classPlays: {} } as unknown as UserStats;
    const run = () => repo.updateStats(u.id, sum({ campaign: "sanctus", hardMode: true, reachedStage: 3, peakAtk: 7, turns: 4 }), "t1");
    expect(run).not.toThrow();
    const s = run(); // 第二場:驗證已補齊的結構能正常累加
    expect(s).toMatchObject({ plays: 2, peakAtk: 7, totalTurns: 8 });
    expect(s?.recentClasses).toEqual(["WARRIOR", "WARRIOR"]);
    expect(s?.runs?.length).toBe(2);
    expect(s?.maxStageByMode).toEqual({ "sanctus:hard": 3 });
  });

  it("職業比率計數分流(WARRIOR / BARBARIAN)", () => {
    const repo = new InMemoryUserRepository();
    const u = repo.upsertByOAuth("dev", "u", "U");
    repo.updateStats(u.id, sum({ classType: "BARBARIAN" }), "t1");
    const s = repo.updateStats(u.id, sum({ classType: "WARRIOR" }), "t2");
    expect(s?.classPlays).toEqual({ WARRIOR: 1, BARBARIAN: 1 });
  });

  it("maxStageByMode:敵人×難度各自記最高(取 max、含破關)", () => {
    const repo = new InMemoryUserRepository();
    const u = repo.upsertByOAuth("dev", "u2", "U2");
    repo.updateStats(u.id, sum({ campaign: "slime", reachedStage: 7 }), "t1"); // 史萊姆普通 7
    repo.updateStats(u.id, sum({ campaign: "slime", reachedStage: 4 }), "t2"); // 取 max → 不覆蓋
    repo.updateStats(u.id, sum({ campaign: "slime", hardMode: true, reachedStage: 5 }), "t3"); // 史萊姆困難 5
    const s = repo.updateStats(u.id, sum({ campaign: "sanctus", reachedStage: 11, cleared: true }), "t4"); // Sanctus 普通 破關也算
    expect(s?.maxStageByMode).toEqual({ slime: 7, "slime:hard": 5, sanctus: 11 });
  });

  it("runs:逐場紀錄(舊→新),含敵人/難度/結果/時間", () => {
    const repo = new InMemoryUserRepository();
    const u = repo.upsertByOAuth("dev", "u3", "U3");
    repo.updateStats(u.id, sum({ campaign: "slime", reachedStage: 7 }), "t1");
    const s = repo.updateStats(u.id, sum({ campaign: "sanctus", hardMode: true, reachedStage: 3 }), "t2");
    expect(s?.runs?.length).toBe(2);
    expect(s?.runs?.[1]).toMatchObject({ campaign: "sanctus", hardMode: true, reachedStage: 3, at: "t2" });
  });

  it("找不到使用者 → updateStats 回 null", () => {
    expect(new InMemoryUserRepository().updateStats("nope", sum(), "t")).toBeNull();
  });
});

describe("InMemoryUserRepository — session(記憶體、帶過期)", () => {
  it("put/get/過期/delete", () => {
    const repo = new InMemoryUserRepository();
    repo.putSession("tok", "uid", 100, 1000); // exp = 1000 + 100*1000
    expect(repo.getSession("tok", 2000)).toBe("uid");
    expect(repo.getSession("tok", 1000 + 100 * 1000 + 1)).toBeNull(); // 過期 → lazy 清除
    repo.putSession("tok2", "uid", 100, 1000);
    repo.deleteSession("tok2");
    expect(repo.getSession("tok2", 1000)).toBeNull();
  });
});

describe("UpstashUserRepository", () => {
  it("新建使用者 → 背景 pipeline 寫 SET(user)/SET(oauth 索引)/RPUSH(ids)", async () => {
    const calls: { url: string; body: unknown }[] = [];
    vi.stubGlobal("fetch", vi.fn(async (url: string, init: { body: string }) => {
      calls.push({ url, body: JSON.parse(init.body) });
      return { ok: true, json: async () => [{ result: "OK" }, { result: "OK" }, { result: 1 }] } as unknown as Response;
    }));
    const repo = new UpstashUserRepository("https://x.upstash.io/", "tok");
    repo.upsertByOAuth("discord", "9", "Bob");
    expect(repo.count()).toBe(1); // 記憶體快取立即可用
    await new Promise((r) => setTimeout(r, 0));
    const pipe = calls.find((c) => c.url.endsWith("/pipeline"));
    expect(pipe).toBeTruthy();
    expect((pipe!.body as string[][]).map((c) => c[0])).toEqual(["SET", "SET", "RPUSH"]);
  });

  it("load():從 LRANGE→MGET 還原使用者到記憶體快取", async () => {
    const rec: UserRecord = { id: "abc", provider: "discord", providerUserId: "9", displayName: "Bob", createdAt: "t", stats: emptyStats() };
    vi.stubGlobal("fetch", vi.fn(async (_url: string, init: { body: string }) => {
      const body = JSON.parse(init.body) as string[];
      const result = body[0] === "LRANGE" ? [rec.id] : body[0] === "MGET" ? [JSON.stringify(rec)] : null;
      return { ok: true, json: async () => ({ result }) } as unknown as Response;
    }));
    const repo = new UpstashUserRepository("https://x.upstash.io", "tok");
    await repo.load();
    expect(repo.count()).toBe(1);
    expect(repo.getById("abc")?.displayName).toBe("Bob");
    // 還原 oauth 索引 → 同身分再登入視為同帳號
    expect(repo.upsertByOAuth("discord", "9", "Bob").id).toBe("abc");
  });

  it("session 持久化:putSession 背景 SET(帶 EX)、重啟後 load 由 SCAN→MGET 還原、deleteSession 發 DEL", async () => {
    const calls: string[][] = [];
    const futureExp = Date.now() + 100_000; // 還原時要比真實 now 晚 → 才不會被當過期
    const stored = JSON.stringify({ userId: "u1", exp: futureExp });
    vi.stubGlobal("fetch", vi.fn(async (_url: string, init: { body: string }) => {
      const cmd = JSON.parse(init.body) as string[];
      calls.push(cmd);
      let result: unknown = "OK";
      if (cmd[0] === "LRANGE") result = []; // 無使用者
      else if (cmd[0] === "SCAN") result = ["0", ["wcg:session:tokA"]]; // 一個 session key,cursor 收斂為 0
      else if (cmd[0] === "MGET") result = [stored];
      return { ok: true, json: async () => ({ result }) } as unknown as Response;
    }));

    const repo = new UpstashUserRepository("https://x.upstash.io", "tok");
    repo.putSession("tokA", "u1", 100, 1000);
    expect(repo.getSession("tokA", 2000)).toBe("u1"); // 記憶體快取立即可讀
    await new Promise((r) => setTimeout(r, 0));
    const setCmd = calls.find((c) => c[0] === "SET" && c[1] === "wcg:session:tokA");
    expect(setCmd).toBeTruthy();
    expect(setCmd!.slice(-2)).toEqual(["EX", "100"]); // 帶 Redis 原生 TTL

    // 模擬容器重啟:新實例 load() 應由 SCAN→MGET 還原 session(不會把使用者打成遊客)
    const repo2 = new UpstashUserRepository("https://x.upstash.io", "tok");
    await repo2.load();
    expect(repo2.getSession("tokA", Date.now())).toBe("u1");

    calls.length = 0;
    repo2.deleteSession("tokA");
    await new Promise((r) => setTimeout(r, 0));
    expect(calls.some((c) => c[0] === "DEL" && c[1] === "wcg:session:tokA")).toBe(true);
  });
});