import type { Response } from 'express'; import { getRawPoolQuery, pool } from '../db'; import { getTenantDbStore } from './tenantDbContext'; import { listActiveTenantBranches, runInBranchSchema } from './tenantSchemaFallback'; import { getRedisClient, isRedisConfigured } from './redisClient'; const rawQuery = getRawPoolQuery(); export interface NotificationRow { id: string; user_id: string | null; notify_type: string | null; title: string | null; content: string | null; related_order_code: string | null; is_read: boolean | null; created_at: string | Date | null; } type StreamClient = { userId: string; send: (event: string, data: unknown) => void; }; const clientsByUser = new Map>(); const REDIS_CHANNEL = 'notification:push'; let redisSubscriber: ReturnType | null = null; let bridgeReady = false; function serializeNotification(row: NotificationRow) { return { id: row.id, user_id: row.user_id, notify_type: row.notify_type, title: row.title, content: row.content, related_order_code: row.related_order_code, is_read: row.is_read, created_at: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at, }; } function writeSse(res: Response, event: string, data: unknown) { res.write(`event: ${event}\n`); res.write(`data: ${JSON.stringify(data)}\n\n`); } function deliverLocal(userId: string, event: string, data: unknown) { const set = clientsByUser.get(userId); if (!set?.size) return; for (const client of set) { try { client.send(event, data); } catch { // ignore broken stream } } } export async function initNotificationStreamBridge() { if (bridgeReady || !isRedisConfigured()) return; const base = getRedisClient(); if (!base) return; try { redisSubscriber = base.duplicate(); await redisSubscriber.connect(); await redisSubscriber.subscribe(REDIS_CHANNEL); redisSubscriber.on('message', (_channel, message) => { try { const payload = JSON.parse(message) as { userId?: string; event?: string; data?: unknown }; if (!payload.userId || !payload.event) return; deliverLocal(payload.userId, payload.event, payload.data); } catch { // ignore malformed pub/sub payload } }); bridgeReady = true; } catch (error: any) { console.warn('[notification-stream] redis bridge disabled:', error?.message || error); redisSubscriber = null; } } async function publishRemote(userId: string, event: string, data: unknown) { const redis = getRedisClient(); if (!redis) return; try { await redis.publish(REDIS_CHANNEL, JSON.stringify({ userId, event, data })); } catch { // local delivery still works } } export async function publishNotificationEvent(userId: string, event: string, data: unknown) { deliverLocal(userId, event, data); await publishRemote(userId, event, data); } export async function pushNotificationCreated(userId: string, row: NotificationRow) { await publishNotificationEvent(userId, 'notification', serializeNotification(row)); } /** M17:SSE 连接上限(单实例,整机 + 单用户双层),防连接耗尽 */ export const MAX_NOTIFICATION_STREAMS = 300; export const MAX_NOTIFICATION_STREAMS_PER_USER = 3; /** * 是否还能接入新的通知流连接。 * ⚠️ 必须在**写 SSE 响应头之前**调用:响应头一 flush 就只能断开,无法再回 429。 */ export function canAcceptNotificationStream(userId: string): boolean { let connections = 0; for (const set of clientsByUser.values()) connections += set.size; if (connections >= MAX_NOTIFICATION_STREAMS) return false; return (clientsByUser.get(userId)?.size ?? 0) < MAX_NOTIFICATION_STREAMS_PER_USER; } export function registerNotificationStreamClient(userId: string, res: Response) { const client: StreamClient = { userId, send: (event, data) => writeSse(res, event, data), }; let set = clientsByUser.get(userId); if (!set) { set = new Set(); clientsByUser.set(userId, set); } set.add(client); return () => { set?.delete(client); if (set && set.size === 0) clientsByUser.delete(userId); }; } export async function listBellNotifications(userId: string, limit = 20) { const als = getTenantDbStore()?.branchCode || null; let branch = als; if (!branch) { const profile = await rawQuery(`SELECT branch_code FROM public.profiles WHERE id = $1 LIMIT 1`, [userId]); branch = String(profile.rows[0]?.branch_code || '').trim() || null; } const load = async () => { const result = await pool.query( `SELECT * FROM notifications WHERE user_id = $1 OR user_id IS NULL ORDER BY created_at DESC LIMIT $2`, [userId, limit] ); return result.rows as NotificationRow[]; }; if (branch) { const rows = await runInBranchSchema(branch, load); return rows.map((row) => serializeNotification(row)); } const tenants = await listActiveTenantBranches(); const merged: NotificationRow[] = []; const seen = new Set(); for (const t of tenants) { const rows = await runInBranchSchema(t.branch_code, load); for (const row of rows) { const id = String(row.id || ''); if (!id || seen.has(id)) continue; seen.add(id); merged.push(row); } } merged.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || ''))); return merged.slice(0, limit).map((row) => serializeNotification(row)); } export function attachNotificationStream(userId: string, res: Response): boolean { // M17:先判容量再写响应头(头一 flush 就无法回 429 了) if (!canAcceptNotificationStream(userId)) return false; res.setHeader('Content-Type', 'text/event-stream; charset=utf-8'); res.setHeader('Cache-Control', 'no-cache, no-transform'); res.setHeader('Connection', 'keep-alive'); res.setHeader('X-Accel-Buffering', 'no'); res.flushHeaders?.(); const unregister = registerNotificationStreamClient(userId, res); writeSse(res, 'ready', { ok: true }); void listBellNotifications(userId, 20).then((items) => { writeSse(res, 'snapshot', { items, unread_count: items.filter((item) => !item.is_read).length }); }); const heartbeat = setInterval(() => { try { res.write(': ping\n\n'); } catch { clearInterval(heartbeat); } }, 25_000); reqOnClose(res, () => { clearInterval(heartbeat); unregister(); }); return true; } function reqOnClose(res: Response, cleanup: () => void) { res.on('close', cleanup); res.on('finish', cleanup); } export function getNotificationStreamStats() { let connections = 0; for (const set of clientsByUser.values()) connections += set.size; return { connections, users: clientsByUser.size, redisBridge: bridgeReady }; }