import { readFileSync } from 'node:fs'; import path from 'path'; import { afterEach, describe, expect, it } from 'vitest'; import { getAllocationSlotStats, withAllocationSlot } from '../src/services/allocationConcurrency'; /** * 两个 P0 的防回退测试(2026-09-18) * 设计:docs/design/20260918-nested-txn-and-slot-deadlock.md * * 共同前提:TENANT_REQUEST_CLIENT=1 时,请求级 pool.connect() 返回同一条连接的 facade * (db.ts:283-289,release 为空操作)。以下两处曾把它当成「新连接」使用。 */ const ORIGINAL_CONCURRENCY = process.env.ORDER_ALLOCATION_CONCURRENCY; afterEach(() => { if (ORIGINAL_CONCURRENCY === undefined) delete process.env.ORDER_ALLOCATION_CONCURRENCY; else process.env.ORDER_ALLOCATION_CONCURRENCY = ORIGINAL_CONCURRENCY; }); describe('P0-A 分配信号量重入', () => { it('① 槽内再调 withAllocationSlot 不再二次取槽 → 不死锁', async () => { // 上限设为 1:外层已占满唯一槽位,内层若再取槽必然永久等待 process.env.ORDER_ALLOCATION_CONCURRENCY = '1'; let innerRan = false; const run = (async () => { await withAllocationSlot(async () => { await withAllocationSlot(async () => { innerRan = true; }); }); return 'done'; })(); const outcome = await Promise.race([ run, new Promise((resolve) => setTimeout(() => resolve('timeout'), 1000)), ]); expect(outcome).toBe('done'); expect(innerRan).toBe(true); }); it('② 重入不放大并发占用:嵌套期间 active 不增加', async () => { process.env.ORDER_ALLOCATION_CONCURRENCY = '4'; let outerActive = -1; let innerActive = -1; await withAllocationSlot(async () => { outerActive = getAllocationSlotStats().active; await withAllocationSlot(async () => { innerActive = getAllocationSlotStats().active; }); }); expect(outerActive).toBe(1); expect(innerActive).toBe(outerActive); // 重入不占额外槽位 // 出栈后全部归还 expect(getAllocationSlotStats().active).toBe(0); expect(getAllocationSlotStats().waiting).toBe(0); }); it('③ 并发上限仍生效:超出上限的请求排队,不并发进入', async () => { process.env.ORDER_ALLOCATION_CONCURRENCY = '2'; let running = 0; let peak = 0; const task = () => withAllocationSlot(async () => { running += 1; peak = Math.max(peak, running); await new Promise((r) => setTimeout(r, 20)); running -= 1; }); await Promise.all([task(), task(), task(), task(), task(), task()]); expect(peak).toBeLessThanOrEqual(2); // 闸门语义未被破坏 expect(getAllocationSlotStats().active).toBe(0); }); }); describe('P0-B 竞价自动中标:外层有事务时不得裸 COMMIT', () => { const src = readFileSync(path.join(__dirname, '../src/services/bidRoundService.ts'), 'utf8'); const fn = (() => { const start = src.indexOf('export async function tryAutoAwardAndAllocate'); expect(start).toBeGreaterThan(-1); // 取到下一个顶层 export 之前 const rest = src.slice(start); const next = rest.indexOf('\nexport ', 1); return next > 0 ? rest.slice(0, next) : rest; })(); it('④ 判定是否处于外层事务(与 tenantSchemaService 同一判据)', () => { expect(src).toContain("import { getTenantDbStore } from './tenantDbContext'"); expect(fn).toContain('getTenantDbStore()?.client'); expect(fn).toContain('txid_current_if_assigned()'); }); it('⑤ 外层有事务时用 SAVEPOINT,绝不提交外层事务', () => { expect(fn).toContain('SAVEPOINT ${AUTO_AWARD_SAVEPOINT}'); expect(fn).toContain('RELEASE SAVEPOINT ${AUTO_AWARD_SAVEPOINT}'); expect(fn).toContain('ROLLBACK TO SAVEPOINT ${AUTO_AWARD_SAVEPOINT}'); expect(fn).toContain('if (inOuterTxn)'); // COMMIT 只允许出现在「无外层事务」的 else 分支,且全文只有这一处 expect(fn).toContain("else await client.query('COMMIT');"); expect(fn.split("client.query('COMMIT')").length - 1).toBe(1); // ROLLBACK 同理:只允许 else 分支里的那一处(裸回滚) expect(fn.split("client.query('ROLLBACK')").length - 1).toBe(1); // 且该裸 ROLLBACK 必须紧跟 else(即受 inOuterTxn 保护) expect(fn).toContain("else {\n await client.query('ROLLBACK').catch(() => undefined);\n }"); }); it('⑥ 无外层事务时保留原 BEGIN/COMMIT 语义(行为等价)', () => { // 非共享请求连接 → inOuterTxn 恒 false → 走原路径 expect(fn).toContain("await client.query('BEGIN')"); expect(fn).toContain('else await client.query(\'COMMIT\')'); }); });