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], ]); }); });