Files
SupplierSystem/server/tests/tenantScaleConcurrency.test.ts
Ubuntu 1d47267a8d
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore(sync): 提交剩余本地改动(规则文档 / 部署配置 / 小程序入库归档 / 工具与测试)
- .cursor/rules + AGENTS.md:供应商二次开发的隔离硬规则落库(库/端口/上传目录/对象前缀)
- 部署与本地配置:docker-compose*.yml、.env.*.example(仅占位值)、start-split-native / sync-prod-db-to-local 脚本
- 小程序:入库归档识别(stockInboundArchive + 识别与入库面板改动)
- tools:设计门禁脚本(check-migrations / run-all / verify-facts)与架构图脚本更新
- docs:跨系统改价改量审核、第三方订单退货跟随、免入库推进、500+ 分公司规模改造、
  拍照入库识别与档案回写等设计文档;对接清单新增 §4.5.4 我方回执(第六批端到端)
- server:存量修数脚本(legacy CS / 供应商应付 / 结算口径)、采购耳标核对脚本;
  新增测试:入库归档回写、租户优选顺序、规模并发
2026-10-09 22:28:15 +08:00

175 lines
5.8 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
/**
* 规模改造 §6/§7 回归:
* ① 有界并发工具保持结果顺序、遵守并发上限、单个失败不炸整轮;
* ② 并发度读环境变量时非法值/超上限都有确定行为,且 =1 可退回串行(回滚开关);
* ③ 租户清单 30 s 缓存真的省掉重复打库,且能主动失效(新建分公司立刻可见)。
*/
const query = vi.hoisted(() => vi.fn());
vi.mock('../src/db', () => ({
pool: { query: (...args: unknown[]) => query(...args), connect: vi.fn() },
getRawPoolQuery: () => query,
}));
import { mapWithConcurrency, resolveConcurrency } from '../src/utils/concurrency';
import {
invalidateActiveTenantBranchesCache,
listActiveTenantBranches,
resetActiveTenantBranchesCacheForTest,
} from '../src/services/tenantSchemaFallback';
describe('mapWithConcurrency', () => {
it('结果与入参同序同长', async () => {
const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10);
expect(out).toEqual([10, 20, 30, 40, 50]);
});
it('遵守并发上限', async () => {
let inFlight = 0;
let peak = 0;
await mapWithConcurrency([...new Array(20).keys()], 4, async () => {
inFlight += 1;
peak = Math.max(peak, inFlight);
await new Promise((r) => setTimeout(r, 1));
inFlight -= 1;
return true;
});
expect(peak).toBeLessThanOrEqual(4);
expect(peak).toBeGreaterThan(1);
});
it('并发度 1 等价串行(回滚开关)', async () => {
let inFlight = 0;
let peak = 0;
await mapWithConcurrency([1, 2, 3], 1, async () => {
inFlight += 1;
peak = Math.max(peak, inFlight);
await new Promise((r) => setTimeout(r, 1));
inFlight -= 1;
return true;
});
expect(peak).toBe(1);
});
it('单项抛错不中断其余项,该项记为 undefined', async () => {
const out = await mapWithConcurrency([1, 2, 3], 3, async (n) => {
if (n === 2) throw new Error('boom');
return n;
});
expect(out).toEqual([1, undefined, 3]);
});
it('空数组与超长并发度都安全', async () => {
expect(await mapWithConcurrency([], 4, async () => 1)).toEqual([]);
expect(await mapWithConcurrency([1], 99, async (n) => n)).toEqual([1]);
});
});
describe('resolveConcurrency', () => {
it('非法值退回 fallback', () => {
expect(resolveConcurrency(undefined, 6, 10)).toBe(6);
expect(resolveConcurrency('', 6, 10)).toBe(6);
expect(resolveConcurrency('abc', 6, 10)).toBe(6);
expect(resolveConcurrency(0, 6, 10)).toBe(6);
expect(resolveConcurrency(-3, 6, 10)).toBe(6);
});
it('合法值生效但受上限约束', () => {
expect(resolveConcurrency('2', 6, 10)).toBe(2);
expect(resolveConcurrency('50', 6, 10)).toBe(10);
expect(resolveConcurrency('1', 6, 10)).toBe(1);
});
});
describe('租户清单缓存(§7)', () => {
const rows = [{ branch_code: 'BR001', schema_name: 'tenant_br001' }];
beforeEach(() => {
query.mockReset();
query.mockResolvedValue({ rows });
resetActiveTenantBranchesCacheForTest();
});
afterEach(() => {
delete process.env.TENANT_LIST_CACHE_TTL_MS;
resetActiveTenantBranchesCacheForTest();
});
it('TTL 内只打库一次', async () => {
await listActiveTenantBranches();
await listActiveTenantBranches();
await listActiveTenantBranches();
expect(query).toHaveBeenCalledTimes(1);
});
it('主动失效后立刻重查(新建分公司不等 TTL)', async () => {
await listActiveTenantBranches();
invalidateActiveTenantBranchesCache();
await listActiveTenantBranches();
expect(query).toHaveBeenCalledTimes(2);
});
it('TTL=0 关闭缓存,行为与改造前一致', async () => {
process.env.TENANT_LIST_CACHE_TTL_MS = '0';
resetActiveTenantBranchesCacheForTest();
await listActiveTenantBranches();
await listActiveTenantBranches();
expect(query).toHaveBeenCalledTimes(2);
});
it('缓存保留原有过滤与字段清洗', async () => {
query.mockResolvedValue({
rows: [
{ branch_code: ' BR001 ', schema_name: 'tenant_br001' },
{ branch_code: 'BAD', schema_name: 'public' },
{ branch_code: '', schema_name: 'tenant_x' },
],
});
resetActiveTenantBranchesCacheForTest();
const out = await listActiveTenantBranches();
expect(out).toEqual([{ branch_code: 'BR001', schema_name: 'tenant_br001' }]);
});
});
describe('并发度受连接池预算约束(复查修复:池调小后不再按默认并发占满)', () => {
it('池 30(默认)时默认值原样生效', () => {
expect(resolveConcurrency(undefined, 6, 10, 30)).toBe(6);
expect(resolveConcurrency(undefined, 4, 8, 30)).toBe(4);
});
it('池调小时自动收敛到 pool/5', () => {
expect(resolveConcurrency(undefined, 6, 10, 10)).toBe(2);
expect(resolveConcurrency('8', 4, 8, 10)).toBe(2);
expect(resolveConcurrency('3', 6, 10, 10)).toBe(2); // 业务值也不能超过池预算
});
it('池很小也至少保证 1(退回串行)', () => {
expect(resolveConcurrency('6', 6, 10, 3)).toBe(1);
expect(resolveConcurrency('6', 6, 10, 0)).toBe(6); // 非法池值 → 不施加池预算
expect(resolveConcurrency('6', 6, 10, 'abc')).toBe(6);
});
});
describe('mapWithConcurrency 的失败不再静默', () => {
it('onError 收到每一次失败', async () => {
const seen: Array<[unknown, number]> = [];
const out = await mapWithConcurrency(
[1, 2, 3],
3,
async (n) => {
if (n !== 2) throw new Error(`boom-${n}`);
return n;
},
(error, item) => seen.push([(error as Error).message, item as number])
);
expect(out).toEqual([undefined, 2, undefined]);
expect(seen.sort((a, b) => a[1] - b[1])).toEqual([
['boom-1', 1],
['boom-3', 3],
]);
});
});