Files
SupplierSystem/server/tests/tenantContextDetachedTask.integration.test.ts
Ubuntu ad36182a9e
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
fix(报告推送/订单UI): 修复"立即推送"租户上下文竞态;移除全天下单控件;抵扣批次显示商品名
1) 批次报告"立即推送"偶发丢失(租户上下文收尾竞态报 42P01 被吞,只能等 15 分钟对账):
   - 连接归还前先排空请求级查询队列,再复位 search_path;
   - triggerReportPush 改独立租户上下文(isolate)运行,失败日志带分公司;
   - webhook 绑定后即时拉取改用新增的 runDetachedTenantTask(独立连接 + 结构化错误日志)。
2) 订单管理工具栏移除「全天下单」控件及配套状态/接口调用(后端下单时段配置未改)。
3) 「选择抵扣的库存商品」弹窗:实际抵扣批次前置库存商品名(SKU),名字取自候选列表。

测试:releaseTenantSessionClient.ordering / reportPushTenantContextIsolation /
tenantContextDetachedTask.integration 共 8 用例通过;OrderItemCoverSkuModal +
orderManagement 共 138 用例通过;npm run typecheck 通过。
2026-10-21 19:21:20 +08:00

116 lines
4.4 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 { afterAll, describe, expect, it } from 'vitest';
/**
* 2026-10-21 竞态修复的**真库回归**(先探测本机 dev 库,连不上则跳过)。
*
* 复现线上故障形态(修复前会红):
* 请求级租户上下文里,业务先发一条慢查询,再在**不 await** 的情况下排一条租户表查询
* (= 旁路任务/报告推送的形态),然后 handler 返回、HTTP 响应结束触发租户上下文收尾。
* 旧实现收尾时直接复位 search_path ⇒ 排队中的查询在 `search_path=public` 下执行
* ⇒ `relation "inventory_batch_report_matches" does not exist`(42P01)。
*
* 修复后:
* ① `releaseTenantSessionClient` 先排空串行队列再复位 ⇒ 排队查询正常返回;
* ② `runDetachedTenantTask`(isolate)自取连接 ⇒ 完全不受请求收尾影响。
*/
const BRANCH = 'BR002';
const TENANT_TABLE_SQL = 'SELECT count(*)::int AS c FROM inventory_batch_report_matches';
let dbReady: boolean | null = null;
async function hasDb(): Promise<boolean> {
if (dbReady !== null) return dbReady;
dbReady = false;
try {
const { loadEnv } = await import('../src/env');
loadEnv();
if (!process.env.DATABASE_URL) return dbReady;
const pg = (await import('pg')).default as unknown as {
Client: new (cfg: { connectionString: string }) => {
connect: () => Promise<void>;
end: () => Promise<void>;
query: (sql: string, params?: unknown[]) => Promise<{ rowCount?: number }>;
};
};
const client = new pg.Client({ connectionString: process.env.DATABASE_URL });
await client.connect();
const registry = await client.query(
`SELECT 1 FROM public.tenant_schema_registry WHERE branch_code = $1 AND status = 'active'`,
[BRANCH]
);
await client.end();
dbReady = Boolean(registry.rowCount);
return dbReady;
} catch {
dbReady = false;
return dbReady;
}
}
async function waitFor<T>(read: () => T, timeoutMs = 3000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
if (read()) return;
await new Promise((resolve) => setTimeout(resolve, 20));
}
}
describe('租户上下文收尾竞态(真实 PG)', () => {
it('请求收尾时已排队的租户查询,不会跑到复位后的 public search_path 上(A2)', async () => {
if (!(await hasDb())) return;
const { runWithTenantDbContext } = await import('../src/services/tenantDbContext');
const { pool } = await import('../src/db');
let result: { rows: Array<{ c: number }> } | Error | null = null;
await runWithTenantDbContext(BRANCH, async () => {
// 请求里先发一条慢查询(制造"队列非空"的收尾时机)
const slow = pool.query('SELECT pg_sleep(0.1)');
// 旁路任务形态:排一条租户表查询,但**不 await**,随请求一起返回
void pool
.query<{ c: number }>(TENANT_TABLE_SQL)
.then((r) => {
result = r;
})
.catch((error: unknown) => {
result = error as Error;
});
void slow.catch(() => undefined);
});
await waitFor(() => result !== null);
expect(result).not.toBeInstanceOf(Error);
expect(Number((result as { rows: Array<{ c: number }> }).rows[0]?.c)).toBeGreaterThanOrEqual(0);
});
it('runDetachedTenantTask 在请求上下文里也能拿到正确的租户 schema(A1)', async () => {
if (!(await hasDb())) return;
const { runWithTenantDbContext } = await import('../src/services/tenantDbContext');
const { runDetachedTenantTask } = await import('../src/services/detachedTenantTask');
const { pool } = await import('../src/db');
let result: { rows: Array<{ c: number }> } | Error | null = null;
await runWithTenantDbContext(BRANCH, async () => {
const slow = pool.query('SELECT pg_sleep(0.1)');
runDetachedTenantTask(BRANCH, '回归测试-旁路查询', async () => {
try {
result = await pool.query<{ c: number }>(TENANT_TABLE_SQL);
} catch (error) {
result = error as Error;
}
});
void slow.catch(() => undefined);
});
await waitFor(() => result !== null);
expect(result).not.toBeInstanceOf(Error);
expect(Number((result as { rows: Array<{ c: number }> }).rows[0]?.c)).toBeGreaterThanOrEqual(0);
});
afterAll(async () => {
if (!dbReady) return;
const { pool } = await import('../src/db');
await pool.end().catch(() => undefined);
});
});