import { readFileSync } from 'node:fs'; import path from 'node:path'; import { describe, expect, it } from 'vitest'; import { canAcceptNotificationStream, getNotificationStreamStats, registerNotificationStreamClient, MAX_NOTIFICATION_STREAMS_PER_USER, } from '../src/services/notificationStreamService'; /** * M16(助手入口无限流)+ M17(SSE 无连接上限)—— 2026-09-24 修。 * * - M16:`/api/mcp/order-entry/chat` 与 `/chat/stream` 是**一次请求 = 一次付费 LLM 调用**的入口, * 此前只有 `authMiddleware`,没有任何限速。 * - M17:SSE 会长期占用连接与执行上下文;通知流与助手流此前都无上限。 * 通知流上限必须在**写响应头之前**判定(头一 flush 就只能断连,回不了 429)。 */ const SRC = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8'); const fakeRes = () => ({ write: () => true }) as any; describe('M17 通知流连接上限', () => { it('单用户达到上限后不再接收新连接,解除后可再次接入', () => { const user = `u-limit-${Date.now()}`; const releases: Array<() => void> = []; for (let i = 0; i < MAX_NOTIFICATION_STREAMS_PER_USER; i += 1) { expect(canAcceptNotificationStream(user)).toBe(true); releases.push(registerNotificationStreamClient(user, fakeRes())); } expect(canAcceptNotificationStream(user)).toBe(false); // 其他用户不受影响(隔离性) expect(canAcceptNotificationStream(`${user}-other`)).toBe(true); // 释放一个(浏览器关页面)后应恢复 releases[0](); expect(canAcceptNotificationStream(user)).toBe(true); for (const release of releases) release(); expect(getNotificationStreamStats().connections).toBeGreaterThanOrEqual(0); }); it('路由在超限时回 429,且容量判定发生在写 SSE 头之前', () => { const svc = SRC('src/services/notificationStreamService.ts'); const attach = svc.slice(svc.indexOf('export function attachNotificationStream')); // 容量判定必须在 setHeader 之前 expect(attach.indexOf('canAcceptNotificationStream')).toBeLessThan( attach.indexOf("setHeader('Content-Type', 'text/event-stream") ); const route = SRC('src/modules/workflow/routes/notificationRoutes.ts'); expect(route).toContain('if (!attachNotificationStream(req.userId, res))'); expect(route).toContain("status(429)"); }); }); describe('M16 助手 LLM 入口限速与并发流上限', () => { const agent = SRC('src/routes/orderEntryAgent.ts'); it('两个 LLM 入口都挂限速器,且按登录用户计数(IP 可被伪造)', () => { expect(agent).toContain("router.post('/chat', authMiddleware, assistantChatLimiter"); expect(agent).toContain("router.post('/chat/stream', authMiddleware, assistantChatLimiter"); expect(agent).toContain('keyGenerator: (req: AuthRequest) => `u:${req.userId || ipKeyGenerator('); expect(agent).toContain('const assistantChatLimiter = rateLimit({'); }); it('并发流上限:先判再 flush,并在 close/finish 释放', () => { expect(agent).toContain('MAX_CONCURRENT_CHAT_STREAMS'); expect(agent).toContain("res.on('close', releaseStream)"); expect(agent).toContain("res.on('finish', releaseStream)"); const block = agent.slice(agent.indexOf("router.post('/chat/stream'")); expect(block.indexOf('activeStreamCount() >=')).toBeLessThan( block.indexOf("setHeader('Content-Type', 'text/event-stream") ); }); });