Files
SupplierSystem/src/hooks/useNotificationStream.ts
T
Ubuntu 5fa2bbfd55
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(audit-20261019): T1-T9 审计修复、存储归属与审计日志列宽
- T1 资金/库存/报价/自采 P1(BIZ-1/2/3/4/10/13/14)
- T2 主系统反向事件墓碑/改派/孤儿处理(BIZ-6/8/9)
- T3 选分公司 ticket、trust proxy、角色权限收口(SEC-2/3/4)
- T4 缺列/RLS/tenant 名单/FK/迁移执行器(DATA-1..8)
- T5 401 登出/分页/映射口径/blob/ZIP 中文名(FE-1..4/BIZ-15)
- T6 测试脚本目标守卫/config fail-fast/容器配置(OPS-2..8)
- T7 前后端测试与 lint 门禁清零
- T8 应付卡片按关联订单日(口径 A)
- T9 存储对象全链路归属校验、敏感列禁写、审计 target_id 超长修复
2026-10-19 16:16:51 +08:00

189 lines
5.6 KiB
TypeScript
Raw 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 { useEffect, useRef } from 'react';
import { buildApiUrl } from '../lib/apiConfig';
import { readAuthSessionRaw } from '../lib/authSession';
export interface StreamNotificationItem {
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 | null;
}
function readAccessToken(): string | null {
try {
const raw = readAuthSessionRaw();
if (!raw) return null;
const session = JSON.parse(raw);
return session?.access_token ? String(session.access_token) : null;
} catch {
return null;
}
}
/** 解析一块 SSE 文本(可能含多条事件),返回已消费长度与事件列表 */
function consumeSseChunk(
buffer: string
): { rest: string; events: Array<{ event: string; data: string }> } {
const events: Array<{ event: string; data: string }> = [];
let rest = buffer;
// 事件以空行分隔(\n\n 或 \r\n\r\n)
while (true) {
const idxLf = rest.indexOf('\n\n');
const idxCrlf = rest.indexOf('\r\n\r\n');
let sep = -1;
let sepLen = 0;
if (idxLf >= 0 && (idxCrlf < 0 || idxLf <= idxCrlf)) {
sep = idxLf;
sepLen = 2;
} else if (idxCrlf >= 0) {
sep = idxCrlf;
sepLen = 4;
}
if (sep < 0) break;
const block = rest.slice(0, sep);
rest = rest.slice(sep + sepLen);
let event = 'message';
const dataLines: string[] = [];
for (const rawLine of block.split(/\r?\n/)) {
if (!rawLine || rawLine.startsWith(':')) continue;
if (rawLine.startsWith('event:')) {
event = rawLine.slice(6).trim();
} else if (rawLine.startsWith('data:')) {
dataLines.push(rawLine.slice(5).trimStart());
}
}
if (dataLines.length) {
events.push({ event, data: dataLines.join('\n') });
}
}
return { rest, events };
}
/**
* A7: 原生 EventSource 无法带 Authorization;改用 fetch 流 + Bearer,
* 避免 ?access_token= 进入 URL/网关日志。
*/
export function useNotificationStream(options: {
enabled: boolean;
onSnapshot: (items: StreamNotificationItem[]) => void;
onNotification?: (item: StreamNotificationItem) => void;
onRefresh?: (items: StreamNotificationItem[]) => void;
}) {
const onSnapshotRef = useRef(options.onSnapshot);
const onNotificationRef = useRef(options.onNotification);
const onRefreshRef = useRef(options.onRefresh);
useEffect(() => {
onSnapshotRef.current = options.onSnapshot;
}, [options.onSnapshot]);
useEffect(() => {
onNotificationRef.current = options.onNotification;
}, [options.onNotification]);
useEffect(() => {
onRefreshRef.current = options.onRefresh;
}, [options.onRefresh]);
useEffect(() => {
if (!options.enabled) return undefined;
let stopped = false;
let retryTimer: number | null = null;
let retryMs = 2000;
let abort: AbortController | null = null;
const dispatch = (eventName: string, data: string) => {
try {
if (eventName === 'snapshot') {
const payload = JSON.parse(data) as { items?: StreamNotificationItem[] };
onSnapshotRef.current((payload.items || []).slice(0, 8));
return;
}
if (eventName === 'notification') {
onNotificationRef.current?.(JSON.parse(data) as StreamNotificationItem);
return;
}
if (eventName === 'notifications_refresh') {
const payload = JSON.parse(data) as { items?: StreamNotificationItem[] };
const items = (payload.items || []).slice(0, 8);
(onRefreshRef.current || onSnapshotRef.current)(items);
}
} catch {
// ignore malformed event
}
};
const connect = async () => {
if (stopped) return;
const token = readAccessToken();
if (!token) return;
abort?.abort();
abort = new AbortController();
try {
const res = await fetch(buildApiUrl('/workflow/notifications/stream'), {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
Accept: 'text/event-stream',
},
signal: abort.signal,
cache: 'no-store',
});
if (!res.ok || !res.body) {
/**
* FE-1:SSE 收到 401 = 认证失效 ⇒ **停止重连**并走统一登出
* (其它错误保持原有 2s→60s 指数退避,不改)。
*/
if (res.status === 401) {
stopped = true;
const { handleUnauthorized } = await import('../lib/localApiClient');
handleUnauthorized();
return;
}
throw new Error(`sse_http_${res.status}`);
}
retryMs = 2000;
const reader = res.body.getReader();
const decoder = new TextDecoder('utf-8');
let buffer = '';
while (!stopped) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parsed = consumeSseChunk(buffer);
buffer = parsed.rest;
for (const ev of parsed.events) {
dispatch(ev.event, ev.data);
}
}
} catch (err) {
if (stopped || (err instanceof DOMException && err.name === 'AbortError')) return;
}
if (stopped) return;
retryTimer = window.setTimeout(() => {
retryMs = Math.min(retryMs * 2, 60_000);
void connect();
}, retryMs);
};
void connect();
return () => {
stopped = true;
if (retryTimer) window.clearTimeout(retryTimer);
abort?.abort();
};
}, [options.enabled]);
}