Files
SupplierSystem/server/src/services/notificationStreamService.ts
T
Ubuntu deb3e72750
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
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

219 lines
6.7 KiB
TypeScript

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<string, Set<StreamClient>>();
const REDIS_CHANNEL = 'notification:push';
let redisSubscriber: ReturnType<typeof getRedisClient> | 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<string>();
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 };
}