/** * 有界并发映射(2026-10-08 规模改造 §6/§7 引入)。 * * 背景:本系统按「主系统供应商数」放大成 N 个租户,多处循环是「逐租户串行」。 * 500 个分公司时,一次 HTTP 型任务串行跑完要几十秒。这里提供最小可用的 * 「保持结果顺序 + 固定并发度 + 单个失败不炸整轮」的工具。 * * 约定: * - 返回数组与入参**同序同长**,第 i 项对应 items[i]; * - 并发度最小 1(=1 即退回串行,用于回滚); * - `fn` 抛错时该项记 `undefined`,不会中断其余项。**调用方必须自己记日志/计数** * (可传 `onError`,避免失败只以 undefined 形式静默消失)。 */ export async function mapWithConcurrency( items: readonly T[], concurrency: number, fn: (item: T, index: number) => Promise, onError?: (error: unknown, item: T, index: number) => void ): Promise> { const results: Array = new Array(items.length); const limit = Math.max(1, Math.min(Math.floor(concurrency) || 1, items.length || 1)); let cursor = 0; const workers = new Array(limit).fill(null).map(async () => { for (;;) { const index = cursor; cursor += 1; if (index >= items.length) return; try { results[index] = await fn(items[index], index); } catch (error) { results[index] = undefined; if (onError) { try { onError(error, items[index], index); } catch { /* 回调自身出错不影响其它项 */ } } else { console.error( `[concurrency] 第 ${index} 项失败(调用方未传 onError,请看调用点是否漏了日志):`, (error as Error)?.message || error ); } } } }); await Promise.all(workers); return results; } /** * 读环境变量里的并发度;非法值退回 fallback,并受两个上限约束: * `cap`(业务上限)与 `poolMax / 5`(连接池预算)。 * * 为什么要池预算(规模改造复查):每个并发租户上下文会**独占一条池连接直到任务结束** * (含回主系统的 HTTP 等待),`PG_POOL_MAX` 默认 30。若运维把池调小(如 10), * 仍按默认 6 并发就会把池占满、让正常请求排队到 10s 超时。这里按池大小自动收敛。 */ export function resolveConcurrency( raw: string | number | undefined, fallback: number, cap = 10, poolMax?: number | string ): number { const value = Number(raw); const base = !Number.isFinite(value) || value < 1 ? Math.max(1, Math.floor(fallback) || 1) : Math.floor(value); const pool = Number(poolMax); const poolBudget = Number.isFinite(pool) && pool > 0 ? Math.max(1, Math.floor(pool / 5)) : cap; return Math.max(1, Math.min(base, cap, poolBudget)); }