背景:开发者问「500 家绑了编码的分公司,当前设计扛得住吗」。实测(真库+真 HTTP): 单家 fan-out 283–884 ms / 25–27 次 DB 查询;500 家外推 ≈15–28 s/轮(并发 6)、12.5k 查询/轮、 500 次出站(0.56 QPS 均值、突发 30–45 QPS)。结论:单实例扛得住(余量 20–30 倍), 但最先破的是下面两件事 —— 本轮修掉。 P0 多实例会把出站 ×N: - 跨系统任务原先写在 withDistributedLock(SCHEDULER_LOCK_KEY) **外面**(void 起飞), 10 分钟限流又是进程内变量 ⇒ 2 个实例 = 每家每轮被拉 2 次。 - 改为独立锁 main-system-reconcile-tick(TTL 10 min)+ 回调内 await Promise.all([...]) (必须 await,否则锁在任务跑完前释放 —— 正是原漏洞形态);异常兜在回调里。 - 冒烟:并发第二个实例拿不到锁(回调未执行)、释放后可再取。 P1-a token 集中过期 + 失败不缓存: - 提前刷新按 supplier_code 稳定散列到 0.80–0.95(过期时刻摊到 ~3.6 h 窗口,且只提前不延后); - 失败退避:401/403/404 ⇒ 5 分钟、网络/5xx ⇒ 30 秒,成功即清空(原来每次都真发)。 - 冒烟:真实换发 178 ms;二次命中缓存 0 ms;不存在的供应商第二次 0 ms 且 reason 变「失败退避中」。 P1-b 拉货峰值: - 并发默认 6 → 4(env 可回调,上限 10); - 新增错峰窗口 MAIN_SYSTEM_IMPORT_SPREAD_SEC(默认 120 s,0=关闭):按编码稳定散列重排后 在窗口内均匀铺开,窗口再被「家数 × 400 ms」封顶 ⇒ 小规模只等几百毫秒。 - 冒烟:500 家槽位 0 → 120000 ms 铺满;2 家真实 fan-out 939 ms、failed=0。 测试与门禁: - 新增 mainSystemScaleGuards.test.ts(9 例)、mainSystemTokenBackoff.test.ts(9 例); - 更新 stockCoverBatchPlan.test.ts 的 ⑧(原钉 `void runStockCoverBatchPlanBackfill()`; 该钉的意图是"兜底挂在 15 分钟 tick 上",改为钉调用 + 必须在跨系统锁回调内 —— 只暂存了这一段, 同文件里对方的 WIP 未纳入本提交); - 全量 26 failed / 2648 passed 与基线持平(唯一差异仍是对方 WIP 的 pickingZoneOrder); 服务端 tsc 0 错;门禁 8 通过 / 1 既定红 / 1 未执行(与改前一致)。 - 新增环境变量已登记:server/.env.example + docs/manual/02-环境要求与安装部署.md(env 覆盖闸门复绿)。 - 设计文 docs/design/20261013-主系统订单被本地拉取机制与绑定缺陷.md §10(容量评估 + 加固记录 + 未做项)。
165 lines
6.5 KiB
TypeScript
165 lines
6.5 KiB
TypeScript
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);
|
||
});
|
||
});
|