import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 主系统对接 Token 的**规模加固**(2026-10-13): * · **提前刷新 + 散列**:token 约 24 h 过期,几百家若同时换发就会**同时过期** * ⇒ 同一轮里叠几百次换发请求。按 code 稳定散列提前到 0.80–0.95 刷新,把过期时刻摊开; * · **失败退避**:失败原来不缓存 ⇒ 被撤授权的那几家每轮都各发一次(纯浪费 + 刷日志)。 * 授权类(401/403/404)退避 5 分钟,瞬时类(网络/5xx)退避 30 秒,成功即清空。 */ const requestMainSystem = vi.hoisted(() => vi.fn()); const enabled = vi.hoisted(() => ({ value: true })); vi.mock('../src/services/mainSystem/http', () => ({ requestMainSystem: (...args: unknown[]) => requestMainSystem(...args), })); vi.mock('../src/services/mainSystem/config', () => ({ MAIN_SYSTEM_OAUTH_TIMEOUT_MS: 5000, mainSystemCredentials: () => ({ clientId: 'cid', clientSecret: 'sec' }), isMainSystemIntegrationEnabled: () => enabled.value, })); const { getMainSystemToken, resetMainSystemTokenCache, tokenRefreshRatio } = await import( '../src/services/mainSystem/token' ); const TTL_SECONDS = 86_400; function okToken(token = 'tok-1') { return { kind: 'ok', status: 200, data: { access_token: token, expires_in: TTL_SECONDS, branch_code: 'BR002' }, payload: null, }; } function forbidden() { return { kind: 'unavailable', status: 403, reason: 'forbidden', payload: { error: 'forbidden', error_description: '未授权访问该供应商' }, }; } function serverError() { return { kind: 'unavailable', status: 502, reason: 'bad_gateway', payload: null }; } beforeEach(() => { requestMainSystem.mockReset(); enabled.value = true; resetMainSystemTokenCache(); vi.useRealTimers(); }); describe('Token 提前刷新(散列,避免几百家同时过期)', () => { it('① 成功换发:过期时刻被提前到 80%–95%(绝不晚于真实 TTL)', async () => { requestMainSystem.mockResolvedValue(okToken()); const before = Date.now(); const result = await getMainSystemToken('SUP_A'); expect(result.kind).toBe('ok'); if (result.kind !== 'ok') return; const ttlMs = TTL_SECONDS * 1000; const lead = result.expiresAt - before; const ratio = lead / ttlMs; expect(ratio).toBeGreaterThanOrEqual(0.8); expect(ratio).toBeLessThanOrEqual(0.95); expect(result.expiresAt).toBeLessThanOrEqual(before + ttlMs); }); it('② 散列稳定且确实摊开:同一家恒定,不同家不全相同', async () => { expect(tokenRefreshRatio('SUP_A')).toBe(tokenRefreshRatio('SUP_A')); const ratios = new Set( Array.from({ length: 30 }, (_, i) => tokenRefreshRatio(`SUP${i}`)) ); expect(ratios.size, '30 家不应挤在同一个刷新点').toBeGreaterThan(5); for (const r of ratios) { expect(r).toBeGreaterThanOrEqual(0.8); expect(r).toBeLessThanOrEqual(0.95); } }); it('③ 命中缓存 ⇒ 不再换发', async () => { requestMainSystem.mockResolvedValue(okToken()); await getMainSystemToken('SUP_A'); await getMainSystemToken('SUP_A'); expect(requestMainSystem).toHaveBeenCalledTimes(1); }); }); describe('Token 失败退避(授权类 5 分钟 / 瞬时类 30 秒)', () => { it('① 403 之后不发第二次:立即再问直接返回"失败退避中"', async () => { requestMainSystem.mockResolvedValue(forbidden()); const first = await getMainSystemToken('SUP_A'); expect(first.kind).toBe('unavailable'); const second = await getMainSystemToken('SUP_A'); expect(second.kind).toBe('unavailable'); if (second.kind === 'unavailable') { expect(second.reason).toContain('失败退避中'); } expect(requestMainSystem, '退避窗口内不得再发请求').toHaveBeenCalledTimes(1); }); it('② 授权类退避 5 分钟:4 分钟仍退避、6 分钟后重试', async () => { vi.useFakeTimers(); vi.setSystemTime(new Date('2026-10-13T00:00:00.000Z')); requestMainSystem.mockResolvedValue(forbidden()); await getMainSystemToken('SUP_A'); vi.setSystemTime(new Date('2026-10-13T00:04:00.000Z')); await getMainSystemToken('SUP_A'); expect(requestMainSystem).toHaveBeenCalledTimes(1); vi.setSystemTime(new Date('2026-10-13T00:06:00.000Z')); await getMainSystemToken('SUP_A'); expect(requestMainSystem, '退避过期后应重试').toHaveBeenCalledTimes(2); vi.useRealTimers(); }); it('③ 瞬时类退避更短:10 秒仍退避、31 秒后重试(下一轮就能自愈)', async () => { vi.useFakeTimers(); vi.setSystemTime(new Date('2026-10-13T00:00:00.000Z')); requestMainSystem.mockResolvedValue(serverError()); await getMainSystemToken('SUP_A'); vi.setSystemTime(new Date('2026-10-13T00:00:10.000Z')); await getMainSystemToken('SUP_A'); expect(requestMainSystem).toHaveBeenCalledTimes(1); vi.setSystemTime(new Date('2026-10-13T00:00:31.000Z')); await getMainSystemToken('SUP_A'); expect(requestMainSystem).toHaveBeenCalledTimes(2); vi.useRealTimers(); }); it('④ 成功即清空退避:失败 → 退避过期重试成功 → 再问命中缓存', async () => { vi.useFakeTimers(); vi.setSystemTime(new Date('2026-10-13T00:00:00.000Z')); requestMainSystem.mockResolvedValueOnce(forbidden()).mockResolvedValue(okToken('tok-2')); await getMainSystemToken('SUP_A'); vi.setSystemTime(new Date('2026-10-13T00:06:00.000Z')); const ok = await getMainSystemToken('SUP_A'); expect(ok.kind).toBe('ok'); const cached = await getMainSystemToken('SUP_A'); expect(cached.kind).toBe('ok'); expect(requestMainSystem).toHaveBeenCalledTimes(2); vi.useRealTimers(); }); it('⑤ forceRefresh 无视缓存与退避(排障手动重试)', async () => { requestMainSystem.mockResolvedValue(forbidden()); await getMainSystemToken('SUP_A'); requestMainSystem.mockResolvedValue(okToken('tok-3')); const forced = await getMainSystemToken('SUP_A', { forceRefresh: true }); expect(forced.kind).toBe('ok'); expect(requestMainSystem).toHaveBeenCalledTimes(2); }); it('⑥ 不同分公司各自退避(互不牵连)', async () => { requestMainSystem.mockResolvedValue(forbidden()); await getMainSystemToken('SUP_A'); await getMainSystemToken('SUP_B'); expect(requestMainSystem).toHaveBeenCalledTimes(2); await getMainSystemToken('SUP_A'); await getMainSystemToken('SUP_B'); expect(requestMainSystem).toHaveBeenCalledTimes(2); }); });