背景:开发者问「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(容量评估 + 加固记录 + 未做项)。
114 lines
5.4 KiB
TypeScript
114 lines
5.4 KiB
TypeScript
import { describe, expect, it, vi } from 'vitest';
|
||
import { readFileSync } from 'node:fs';
|
||
import path from 'node:path';
|
||
|
||
/**
|
||
* 规模加固(2026-10-13,开发者问「扛得住 500 家绑码分公司吗」后落地):
|
||
*
|
||
* · **P0**:跨系统任务收进**独立分布式锁**并在回调里 await —— 否则 N 个实例各跑一遍,
|
||
* 出站请求 ×N(原来的 10 分钟限流是进程内变量,挡不住多实例);
|
||
* · **P1b**:拉货并发 6→4 + **错峰**:把 N 家的开始时刻在窗口内均匀铺开,
|
||
* 500 家从"~11 s 内打完 500 次"变成"~2 分钟摊平",峰值从 30–45 QPS 降到个位数。
|
||
*/
|
||
|
||
const importSrc = readFileSync(
|
||
path.join(__dirname, '../src/services/mainSystemOrderImport.ts'),
|
||
'utf8'
|
||
);
|
||
const schedulerSrc = readFileSync(
|
||
path.join(__dirname, '../src/services/scheduledJobs.ts'),
|
||
'utf8'
|
||
);
|
||
|
||
const { planImportSpread, resolveImportSpreadWindowMs } = await import(
|
||
'../src/services/mainSystemOrderImport'
|
||
);
|
||
|
||
describe('P1b:拉货错峰槽位(纯函数)', () => {
|
||
it('① 均匀铺开:槽位在窗口内等距,且顺序确定(同输入两次结果一致)', () => {
|
||
const branches = ['BR003', 'BR002', 'BR010', 'BR007', 'BR001'];
|
||
const a = planImportSpread(branches, { windowMs: 120_000, perBranchMs: 400 });
|
||
const b = planImportSpread(branches, { windowMs: 120_000, perBranchMs: 400 });
|
||
expect(a).toEqual(b);
|
||
expect([...a].map((s) => s.branchCode).sort()).toEqual([...branches].sort());
|
||
// 5 家 × 400 ms = 2000 ms 窗口(远小于 120 s)⇒ 小规模不白等
|
||
expect(a.map((s) => s.atMs)).toEqual([0, 500, 1000, 1500, 2000]);
|
||
});
|
||
|
||
it('② 大规模:500 家用满窗口,等距铺开(间隔 ≈ 窗口/家数)', () => {
|
||
const branches = Array.from({ length: 500 }, (_, i) => `BR${String(i).padStart(3, '0')}`);
|
||
const slots = planImportSpread(branches, { windowMs: 120_000 });
|
||
expect(slots).toHaveLength(500);
|
||
expect(slots[0].atMs).toBe(0);
|
||
expect(slots[slots.length - 1].atMs).toBe(120_000);
|
||
const gaps = slots.slice(1).map((s, i) => s.atMs - slots[i].atMs);
|
||
expect(Math.max(...gaps)).toBeLessThanOrEqual(2 * (120_000 / 499) + 1);
|
||
// 每家的开始时刻互不相同(不挤在同一毫秒)
|
||
expect(new Set(slots.map((s) => s.atMs)).size).toBe(500);
|
||
});
|
||
|
||
it('③ 窗口上限 = 家数 × 每槽宽度(小规模不等满窗口)', () => {
|
||
const slots = planImportSpread(['BR002', 'BR003'], { windowMs: 120_000, perBranchMs: 400 });
|
||
expect(slots.map((s) => s.atMs).sort((x, y) => x - y)).toEqual([0, 800]);
|
||
});
|
||
|
||
it('④ 关闭错峰:windowMs=0 ⇒ 全部 0(回到"尽快跑完")', () => {
|
||
const slots = planImportSpread(['BR002', 'BR003', 'BR004'], { windowMs: 0 });
|
||
expect(slots.every((s) => s.atMs === 0)).toBe(true);
|
||
});
|
||
|
||
it('⑤ 环境变量解析:空/非法 ⇒ 默认 120 s;0 ⇒ 关闭;超上限封顶 1 h', () => {
|
||
expect(resolveImportSpreadWindowMs('')).toBe(120_000);
|
||
expect(resolveImportSpreadWindowMs(undefined)).toBe(120_000);
|
||
expect(resolveImportSpreadWindowMs('abc')).toBe(0);
|
||
expect(resolveImportSpreadWindowMs('0')).toBe(0);
|
||
expect(resolveImportSpreadWindowMs('-5')).toBe(0);
|
||
expect(resolveImportSpreadWindowMs('300')).toBe(300_000);
|
||
expect(resolveImportSpreadWindowMs('99999')).toBe(3_600_000);
|
||
});
|
||
|
||
it('⑥ 接线(源码钉):并发默认 4、按槽位等待、把原并发参数留给运维上调', () => {
|
||
expect(importSrc).toContain('planImportSpread(branches, { windowMs: resolveImportSpreadWindowMs() })');
|
||
expect(importSrc).toMatch(/MAIN_SYSTEM_IMPORT_CONCURRENCY,\s*\n\s*4,/);
|
||
expect(importSrc).toContain('await sleepMs(waitMs)');
|
||
expect(importSrc).toContain('const branchCode = slot.branchCode;');
|
||
});
|
||
});
|
||
|
||
describe('P0:跨系统任务在独立分布式锁内(源码钉)', () => {
|
||
const lockAt = schedulerSrc.indexOf('MAIN_SYSTEM_LOCK_KEY');
|
||
|
||
it('① 存在独立锁常量与 TTL', () => {
|
||
expect(lockAt).toBeGreaterThan(-1);
|
||
expect(schedulerSrc).toContain("const MAIN_SYSTEM_LOCK_KEY = 'main-system-reconcile-tick'");
|
||
expect(schedulerSrc).toMatch(/MAIN_SYSTEM_LOCK_TTL_SEC = 10 \* 60/);
|
||
});
|
||
|
||
it('② 八个跨系统任务都在锁回调里,并且**被 await**(void 起飞=没锁)', () => {
|
||
const callbackAt = schedulerSrc.indexOf('withDistributedLock(MAIN_SYSTEM_LOCK_KEY');
|
||
expect(callbackAt).toBeGreaterThan(-1);
|
||
const body = schedulerSrc.slice(callbackAt, callbackAt + 2000);
|
||
expect(body).toContain('await Promise.all([');
|
||
for (const fn of [
|
||
'runMainSystemImportReconcile()',
|
||
'runPriceQtyRequestReconcile()',
|
||
'runStockCoverBatchPlanBackfill()',
|
||
'runCoverBatchesSweep()',
|
||
'runReturnedCoverResidueSweep()',
|
||
'runDeferredUnitResendSweep()',
|
||
'runReportPushReconcile()',
|
||
'runEmptyMirrorOrderClosure()',
|
||
]) {
|
||
expect(body, `${fn} 必须在锁回调内`).toContain(fn);
|
||
// 旧形态(锁外 void 起飞)必须消失
|
||
expect(schedulerSrc, `${fn} 不得再以 void 形态出现在锁外`).not.toContain(`void ${fn}`);
|
||
}
|
||
});
|
||
|
||
it('③ 锁回调自身兜异常(不能被 Promise 拒绝掀翻进程)', () => {
|
||
const callbackAt = schedulerSrc.indexOf('withDistributedLock(MAIN_SYSTEM_LOCK_KEY');
|
||
const body = schedulerSrc.slice(callbackAt, callbackAt + 2000);
|
||
expect(body).toContain("console.error('[scheduler] 跨系统任务异常:'");
|
||
});
|
||
});
|