import { readFileSync } from 'node:fs'; import path from 'node:path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 2026-10-21 报告推送稳定性修复:**旁路异步必须使用隔离租户上下文**。 * * 1) `pushBranchReports` 必须用 `runWithTenantDbContext(..., { isolate: true })`: * 旁路任务不得继承请求级 ALS 租户上下文,否则请求收尾复位 search_path 时会让它跑到 public 上(42P01)。 * 2) `triggerReportPush` 的失败日志必须带分公司(原来「已吞」且无上下文,线上排障看不到)。 * 3) webhook 绑定后的即时拉单必须改走 `runDetachedTenantTask`(同类根因的第二个现场)。 */ const H = vi.hoisted(() => ({ tenantCalls: [] as Array<{ code: string; opts: unknown }>, failNextTenantRun: false, })); vi.mock('../src/services/tenantDbContext', () => ({ runWithTenantDbContext: async (code: string, fn: () => Promise, opts?: unknown) => { H.tenantCalls.push({ code, opts }); if (H.failNextTenantRun) { H.failNextTenantRun = false; throw new Error('simulated tenant context failure'); } return fn(); }, })); vi.mock('../src/db', () => ({ pool: { query: async () => ({ rows: [], rowCount: 0 }), connect: async () => ({ query: async () => ({ rows: [], rowCount: 0 }), release: () => undefined }), }, query: async () => ({ rows: [], rowCount: 0 }), getRawPoolQuery: () => async () => ({ rows: [], rowCount: 0 }), getRawPoolConnect: async () => ({ query: async () => ({ rows: [], rowCount: 0 }), release: () => undefined }), isRlsRoleAvailable: async () => true, allowRlsFailOpen: () => true, runWithBranchRls: async (_branch: string, fn: (client: unknown) => Promise) => fn({}), })); vi.mock('../src/services/storageProvider', () => ({ getStorageProvider: () => ({ getObject: async () => null }), })); vi.mock('../src/services/mainSystem/api/qualityReports', () => ({ registerBatchReportOnPreparation: async () => ({ kind: 'not_configured', reason: 'test' }), uploadBatchReportFile: async () => ({ kind: 'not_configured', reason: 'test' }), isUploadableReportFileName: () => true, voidSupplierBatchReport: async () => ({ kind: 'not_configured' }), })); const SERVICE = path.resolve(__dirname, '../src/services/mainSystemReportPushService.ts'); const INTEGRATION_ROUTE = path.resolve(__dirname, '../src/routes/mainSystemIntegration.ts'); describe('报告推送旁路异步的租户上下文隔离', () => { beforeEach(() => { H.tenantCalls = []; H.failNextTenantRun = false; process.env.MAIN_SYSTEM_REPORT_ENABLED = 'true'; }); it('pushBranchReports 以 isolate:true 自取租户连接(不复用请求上下文)', async () => { const { pushBranchReports } = await import('../src/services/mainSystemReportPushService'); const stat = await pushBranchReports({ branchCode: 'BR002' }); expect(H.tenantCalls).toHaveLength(1); expect(H.tenantCalls[0]).toEqual({ code: 'BR002', opts: { isolate: true } }); expect(stat.candidates).toBe(0); }); it('triggerReportPush 失败日志带分公司上下文(不再静默无上下文)', async () => { const { triggerReportPush } = await import('../src/services/mainSystemReportPushService'); const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined); H.failNextTenantRun = true; triggerReportPush('BR002'); // 等旁路 promise 的 catch 执行 await new Promise((resolve) => setTimeout(resolve, 20)); const messages = errorSpy.mock.calls.map((args) => args.map(String).join(' ')); expect(messages.some((m) => m.includes('[report-push]') && m.includes('BR002'))).toBe(true); errorSpy.mockRestore(); }); it('源码合同:webhook 绑定后拉单改走 runDetachedTenantTask,不再裸 void importMainSystemOrders', () => { const source = readFileSync(INTEGRATION_ROUTE, 'utf8'); expect(source).toContain("runDetachedTenantTask(branch, 'webhook-import'"); expect(source).not.toContain('void importMainSystemOrders({ branchCode: branch, userId: null })'); }); it('源码合同:pushBranchReports 的 isolate 标记仍在(防以后被顺手删掉)', () => { const source = readFileSync(SERVICE, 'utf8'); expect(source).toContain('{ isolate: true }'); }); });