|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+import { Injectable, OnDestroy } from '@angular/core';
|
|
|
2
|
+import { BehaviorSubject, Observable, Subject, Subscription } from 'rxjs';
|
|
|
3
|
+import { AuthService } from './auth.service';
|
|
|
4
|
+import { GlobalEvent, EventPayload, EventType, SessionUpdatedEvent, SessionDiffEvent, ServerHeartbeatEvent, MessageUpdatedEvent, MessagePartUpdatedEvent, SessionStatusEvent, ServerConnectedEvent } from '../models/event.model';
|
|
|
5
|
+
|
|
|
6
|
+@Injectable({
|
|
|
7
|
+ providedIn: 'root'
|
|
|
8
|
+})
|
|
|
9
|
+export class EventService implements OnDestroy {
|
|
|
10
|
+ private eventSource: EventSource | null = null;
|
|
|
11
|
+ private isConnected = false;
|
|
|
12
|
+
|
|
|
13
|
+ private subscriptions: Subscription = new Subscription();
|
|
|
14
|
+ private reconnectTimeout: any = null;
|
|
|
15
|
+ private heartbeatTimeout: any = null;
|
|
|
16
|
+ private reconnectAttempts = 0;
|
|
|
17
|
+ private maxReconnectAttempts = 5;
|
|
|
18
|
+ private reconnectDelay = 3000; // 3秒
|
|
|
19
|
+ private heartbeatTimeoutDuration = 5 * 60 * 1000; // 5分钟心跳超时(根据用户要求)
|
|
|
20
|
+
|
|
|
21
|
+ // 事件主题,用于广播所有事件
|
|
|
22
|
+ private allEventsSubject = new Subject<GlobalEvent>();
|
|
|
23
|
+ allEvents$ = this.allEventsSubject.asObservable();
|
|
|
24
|
+
|
|
|
25
|
+ // 特定事件类型主题
|
|
|
26
|
+ private sessionUpdatedSubject = new Subject<SessionUpdatedEvent>();
|
|
|
27
|
+ sessionUpdated$ = this.sessionUpdatedSubject.asObservable();
|
|
|
28
|
+
|
|
|
29
|
+ private sessionDiffSubject = new Subject<SessionDiffEvent>();
|
|
|
30
|
+ sessionDiff$ = this.sessionDiffSubject.asObservable();
|
|
|
31
|
+
|
|
|
32
|
+ private messageUpdatedSubject = new Subject<MessageUpdatedEvent>();
|
|
|
33
|
+ messageUpdated$ = this.messageUpdatedSubject.asObservable();
|
|
|
34
|
+
|
|
|
35
|
+ private messagePartUpdatedSubject = new Subject<MessagePartUpdatedEvent>();
|
|
|
36
|
+ messagePartUpdated$ = this.messagePartUpdatedSubject.asObservable();
|
|
|
37
|
+
|
|
|
38
|
+ // 连接状态主题
|
|
|
39
|
+ private connectionStatusSubject = new BehaviorSubject<boolean>(false);
|
|
|
40
|
+ connectionStatus$ = this.connectionStatusSubject.asObservable();
|
|
|
41
|
+
|
|
|
42
|
+ constructor(private authService: AuthService) {
|
|
|
43
|
+ this.initializeAuthSubscription();
|
|
|
44
|
+ }
|
|
|
45
|
+
|
|
|
46
|
+ // 初始化认证状态订阅
|
|
|
47
|
+ private initializeAuthSubscription() {
|
|
|
48
|
+ this.subscriptions.add(
|
|
|
49
|
+ this.authService.authState$.subscribe(authState => {
|
|
|
50
|
+ console.log('EventService: 认证状态变化', authState.isAuthenticated);
|
|
|
51
|
+
|
|
|
52
|
+ if (authState.isAuthenticated) {
|
|
|
53
|
+ // 用户已登录,连接事件流
|
|
|
54
|
+ this.connectToEventStream();
|
|
|
55
|
+ } else {
|
|
|
56
|
+ // 用户登出,断开事件流
|
|
|
57
|
+ this.disconnect();
|
|
|
58
|
+ }
|
|
|
59
|
+ })
|
|
|
60
|
+ );
|
|
|
61
|
+ }
|
|
|
62
|
+
|
|
|
63
|
+ // 连接到事件流
|
|
|
64
|
+ connectToEventStream(sessionId?: string) {
|
|
|
65
|
+ if (this.eventSource) {
|
|
|
66
|
+ this.eventSource.close();
|
|
|
67
|
+ this.eventSource = null;
|
|
|
68
|
+ }
|
|
|
69
|
+
|
|
|
70
|
+ // 检查是否已登录
|
|
|
71
|
+ if (!this.authService.isAuthenticated()) {
|
|
|
72
|
+ console.warn('未登录状态,不连接事件流');
|
|
|
73
|
+ return;
|
|
|
74
|
+ }
|
|
|
75
|
+
|
|
|
76
|
+ // 获取认证token
|
|
|
77
|
+ const token = this.authService.getToken();
|
|
|
78
|
+ if (!token) {
|
|
|
79
|
+ console.error('无法获取认证token');
|
|
|
80
|
+ return;
|
|
|
81
|
+ }
|
|
|
82
|
+
|
|
|
83
|
+ // 构建带认证参数的URL - 使用日志流端点,因为它发送全局事件
|
|
|
84
|
+ let url = `/api/logs/stream?token=${encodeURIComponent(token)}`;
|
|
|
85
|
+ if (sessionId) {
|
|
|
86
|
+ url += `&sessionId=${sessionId}`;
|
|
|
87
|
+ }
|
|
|
88
|
+
|
|
|
89
|
+ console.log('EventService: 连接事件流URL:', url);
|
|
|
90
|
+ this.eventSource = new EventSource(url);
|
|
|
91
|
+
|
|
|
92
|
+ this.eventSource.onopen = () => {
|
|
|
93
|
+ console.log('EventService: 事件流连接已建立');
|
|
|
94
|
+ this.isConnected = true;
|
|
|
95
|
+ this.connectionStatusSubject.next(true);
|
|
|
96
|
+ this.reconnectAttempts = 0; // 重置重连计数
|
|
|
97
|
+
|
|
|
98
|
+ // 启动心跳超时定时器(5分钟)
|
|
|
99
|
+ this.resetHeartbeatTimeout();
|
|
|
100
|
+
|
|
|
101
|
+ // 发送连接成功事件
|
|
|
102
|
+ this.allEventsSubject.next({
|
|
|
103
|
+ payload: {
|
|
|
104
|
+ type: 'connection.established',
|
|
|
105
|
+ properties: { timestamp: new Date().toISOString() }
|
|
|
106
|
+ }
|
|
|
107
|
+ });
|
|
|
108
|
+ };
|
|
|
109
|
+
|
|
|
110
|
+ this.eventSource.onmessage = (event) => {
|
|
|
111
|
+ const eventData = event.data;
|
|
|
112
|
+ console.log('EventService: 收到原始事件数据:', eventData.substring(0, 200));
|
|
|
113
|
+
|
|
|
114
|
+ // 处理SSE注释格式的心跳(保持向后兼容)
|
|
|
115
|
+ if (eventData === ': heartbeat' || eventData.startsWith(': ')) {
|
|
|
116
|
+ // 重置心跳超时定时器(表示连接活跃)
|
|
|
117
|
+ this.resetHeartbeatTimeout();
|
|
|
118
|
+
|
|
|
119
|
+ // 发送内部心跳事件,供其他服务订阅
|
|
|
120
|
+ this.allEventsSubject.next({
|
|
|
121
|
+ payload: {
|
|
|
122
|
+ type: 'server.heartbeat.comment',
|
|
|
123
|
+ properties: {
|
|
|
124
|
+ timestamp: new Date().toISOString(),
|
|
|
125
|
+ rawData: eventData
|
|
|
126
|
+ }
|
|
|
127
|
+ }
|
|
|
128
|
+ });
|
|
|
129
|
+ return;
|
|
|
130
|
+ }
|
|
|
131
|
+
|
|
|
132
|
+ try {
|
|
|
133
|
+ // 解析JSON事件
|
|
|
134
|
+ const globalEvent: GlobalEvent = JSON.parse(eventData);
|
|
|
135
|
+ this.handleGlobalEvent(globalEvent);
|
|
|
136
|
+ } catch (error) {
|
|
|
137
|
+ // 如果不是JSON,可能是纯文本日志
|
|
|
138
|
+ console.log('EventService: 非JSON事件,可能是纯文本日志:', eventData.substring(0, 100));
|
|
|
139
|
+
|
|
|
140
|
+ // 如果是纯文本日志,可以转发给日志服务或忽略
|
|
|
141
|
+ // 这里只处理JSON事件
|
|
|
142
|
+ }
|
|
|
143
|
+ };
|
|
|
144
|
+
|
|
|
145
|
+ this.eventSource.onerror = (error) => {
|
|
|
146
|
+ console.error('EventService: 事件流连接错误:', error);
|
|
|
147
|
+ this.isConnected = false;
|
|
|
148
|
+ this.connectionStatusSubject.next(false);
|
|
|
149
|
+
|
|
|
150
|
+ // 清除心跳超时定时器
|
|
|
151
|
+ this.clearHeartbeatTimeout();
|
|
|
152
|
+
|
|
|
153
|
+ // 检查是否仍然登录
|
|
|
154
|
+ if (this.authService.isAuthenticated()) {
|
|
|
155
|
+ console.log('EventService: 连接断开,正在重连...');
|
|
|
156
|
+ this.scheduleReconnect(sessionId);
|
|
|
157
|
+ } else {
|
|
|
158
|
+ console.log('EventService: 连接断开(用户未登录)');
|
|
|
159
|
+ }
|
|
|
160
|
+ };
|
|
|
161
|
+ }
|
|
|
162
|
+
|
|
|
163
|
+ // 处理全局事件
|
|
|
164
|
+ private handleGlobalEvent(event: GlobalEvent) {
|
|
|
165
|
+ console.log('EventService: 处理全局事件,类型:', event.payload.type);
|
|
|
166
|
+
|
|
|
167
|
+ // 任何有效事件都重置心跳超时(表明连接活跃)
|
|
|
168
|
+ this.resetHeartbeatTimeout();
|
|
|
169
|
+
|
|
|
170
|
+ // 广播所有事件
|
|
|
171
|
+ this.allEventsSubject.next(event);
|
|
|
172
|
+
|
|
|
173
|
+ // 根据事件类型分发到特定主题
|
|
|
174
|
+ const payload = event.payload;
|
|
|
175
|
+
|
|
|
176
|
+ switch (payload.type) {
|
|
|
177
|
+ case 'session.updated': {
|
|
|
178
|
+ const sessionEvent = payload as SessionUpdatedEvent;
|
|
|
179
|
+ this.sessionUpdatedSubject.next(sessionEvent);
|
|
|
180
|
+ console.log('EventService: 分发 session.updated 事件', sessionEvent.properties.info?.title);
|
|
|
181
|
+ break;
|
|
|
182
|
+ }
|
|
|
183
|
+
|
|
|
184
|
+ case 'session.diff':
|
|
|
185
|
+ this.sessionDiffSubject.next(payload as SessionDiffEvent);
|
|
|
186
|
+ console.log('EventService: 分发 session.diff 事件');
|
|
|
187
|
+ break;
|
|
|
188
|
+
|
|
|
189
|
+ case 'server.heartbeat':
|
|
|
190
|
+ this.allEventsSubject.next(event); // 已经广播过
|
|
|
191
|
+ this.resetHeartbeatTimeout();
|
|
|
192
|
+ break;
|
|
|
193
|
+
|
|
|
194
|
+ case 'message.updated':
|
|
|
195
|
+ this.messageUpdatedSubject.next(payload as MessageUpdatedEvent);
|
|
|
196
|
+ console.log('EventService: 分发 message.updated 事件');
|
|
|
197
|
+ break;
|
|
|
198
|
+
|
|
|
199
|
+ case 'message.part.updated':
|
|
|
200
|
+ this.messagePartUpdatedSubject.next(payload as MessagePartUpdatedEvent);
|
|
|
201
|
+ console.log('EventService: 分发 message.part.updated 事件');
|
|
|
202
|
+ break;
|
|
|
203
|
+
|
|
|
204
|
+ case 'session.status':
|
|
|
205
|
+ this.allEventsSubject.next(event);
|
|
|
206
|
+ console.log('EventService: 分发 session.status 事件');
|
|
|
207
|
+ break;
|
|
|
208
|
+
|
|
|
209
|
+ case 'server.connected':
|
|
|
210
|
+ this.allEventsSubject.next(event);
|
|
|
211
|
+ console.log('EventService: 分发 server.connected 事件');
|
|
|
212
|
+ break;
|
|
|
213
|
+
|
|
|
214
|
+ default:
|
|
|
215
|
+ console.log('EventService: 未知事件类型:', payload.type);
|
|
|
216
|
+ // 未知事件类型仍然通过 allEvents$ 广播
|
|
|
217
|
+ }
|
|
|
218
|
+ }
|
|
|
219
|
+
|
|
|
220
|
+ // 重置心跳超时定时器
|
|
|
221
|
+ private resetHeartbeatTimeout() {
|
|
|
222
|
+ // 清除现有超时
|
|
|
223
|
+ if (this.heartbeatTimeout) {
|
|
|
224
|
+ clearTimeout(this.heartbeatTimeout);
|
|
|
225
|
+ }
|
|
|
226
|
+
|
|
|
227
|
+ // 设置新的超时定时器(5分钟)
|
|
|
228
|
+ this.heartbeatTimeout = setTimeout(() => {
|
|
|
229
|
+ console.warn('EventService: 心跳超时(5分钟未收到心跳),尝试重连');
|
|
|
230
|
+ this.isConnected = false;
|
|
|
231
|
+ this.connectionStatusSubject.next(false);
|
|
|
232
|
+
|
|
|
233
|
+ // 清除现有的重连定时器(如果有)
|
|
|
234
|
+ if (this.reconnectTimeout) {
|
|
|
235
|
+ clearTimeout(this.reconnectTimeout);
|
|
|
236
|
+ }
|
|
|
237
|
+
|
|
|
238
|
+ // 立即尝试重连
|
|
|
239
|
+ if (this.authService.isAuthenticated()) {
|
|
|
240
|
+ const activeSession = this.getCurrentSessionId(); // 需要获取当前会话ID
|
|
|
241
|
+ this.connectToEventStream(activeSession);
|
|
|
242
|
+ }
|
|
|
243
|
+ }, this.heartbeatTimeoutDuration);
|
|
|
244
|
+
|
|
|
245
|
+ console.log('EventService: 心跳超时定时器已重置(5分钟)');
|
|
|
246
|
+ }
|
|
|
247
|
+
|
|
|
248
|
+ // 清除心跳超时定时器
|
|
|
249
|
+ private clearHeartbeatTimeout() {
|
|
|
250
|
+ if (this.heartbeatTimeout) {
|
|
|
251
|
+ clearTimeout(this.heartbeatTimeout);
|
|
|
252
|
+ this.heartbeatTimeout = null;
|
|
|
253
|
+ }
|
|
|
254
|
+ }
|
|
|
255
|
+
|
|
|
256
|
+ // 获取当前会话ID(用于重连时保持会话过滤)
|
|
|
257
|
+ private getCurrentSessionId(): string | undefined {
|
|
|
258
|
+ // 这里可以从URL或状态管理获取当前会话ID
|
|
|
259
|
+ // 暂时返回undefined,表示不进行会话过滤
|
|
|
260
|
+ return undefined;
|
|
|
261
|
+ }
|
|
|
262
|
+
|
|
|
263
|
+ // 安排重连
|
|
|
264
|
+ private scheduleReconnect(sessionId?: string) {
|
|
|
265
|
+ if (this.reconnectTimeout) {
|
|
|
266
|
+ clearTimeout(this.reconnectTimeout);
|
|
|
267
|
+ }
|
|
|
268
|
+
|
|
|
269
|
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
|
|
|
270
|
+ console.error('EventService: 达到最大重连次数,停止重连');
|
|
|
271
|
+ return;
|
|
|
272
|
+ }
|
|
|
273
|
+
|
|
|
274
|
+ this.reconnectAttempts++;
|
|
|
275
|
+ const delay = this.reconnectDelay * Math.pow(1.5, this.reconnectAttempts - 1); // 指数退避
|
|
|
276
|
+
|
|
|
277
|
+ console.log(`EventService: ${this.reconnectAttempts}/${this.maxReconnectAttempts} 重连,等待 ${delay}ms`);
|
|
|
278
|
+
|
|
|
279
|
+ this.reconnectTimeout = setTimeout(() => {
|
|
|
280
|
+ if (this.authService.isAuthenticated()) {
|
|
|
281
|
+ this.connectToEventStream(sessionId);
|
|
|
282
|
+ }
|
|
|
283
|
+ }, delay);
|
|
|
284
|
+ }
|
|
|
285
|
+
|
|
|
286
|
+ // 断开事件流连接
|
|
|
287
|
+ disconnect() {
|
|
|
288
|
+ if (this.eventSource) {
|
|
|
289
|
+ this.eventSource.close();
|
|
|
290
|
+ this.eventSource = null;
|
|
|
291
|
+ this.isConnected = false;
|
|
|
292
|
+ this.connectionStatusSubject.next(false);
|
|
|
293
|
+
|
|
|
294
|
+ console.log('EventService: 已断开事件流连接');
|
|
|
295
|
+ }
|
|
|
296
|
+
|
|
|
297
|
+ if (this.reconnectTimeout) {
|
|
|
298
|
+ clearTimeout(this.reconnectTimeout);
|
|
|
299
|
+ this.reconnectTimeout = null;
|
|
|
300
|
+ }
|
|
|
301
|
+
|
|
|
302
|
+ // 清除心跳超时定时器
|
|
|
303
|
+ this.clearHeartbeatTimeout();
|
|
|
304
|
+
|
|
|
305
|
+ this.reconnectAttempts = 0;
|
|
|
306
|
+ }
|
|
|
307
|
+
|
|
|
308
|
+ // 订阅特定事件类型
|
|
|
309
|
+ subscribeToEvent<T = any>(eventType: EventType): Observable<T> {
|
|
|
310
|
+ return new Observable<T>(observer => {
|
|
|
311
|
+ const subscription = this.allEvents$.subscribe(event => {
|
|
|
312
|
+ if (event.payload.type === eventType) {
|
|
|
313
|
+ observer.next(event.payload as T);
|
|
|
314
|
+ }
|
|
|
315
|
+ });
|
|
|
316
|
+
|
|
|
317
|
+ return () => subscription.unsubscribe();
|
|
|
318
|
+ });
|
|
|
319
|
+ }
|
|
|
320
|
+
|
|
|
321
|
+ // 手动发送事件(用于测试)
|
|
|
322
|
+ emitTestEvent(event: GlobalEvent) {
|
|
|
323
|
+ this.handleGlobalEvent(event);
|
|
|
324
|
+ }
|
|
|
325
|
+
|
|
|
326
|
+ // 检查连接状态
|
|
|
327
|
+ isStreamConnected(): boolean {
|
|
|
328
|
+ return this.isConnected;
|
|
|
329
|
+ }
|
|
|
330
|
+
|
|
|
331
|
+ // 切换会话过滤
|
|
|
332
|
+ switchSession(sessionId?: string) {
|
|
|
333
|
+ if (this.authService.isAuthenticated()) {
|
|
|
334
|
+ this.connectToEventStream(sessionId);
|
|
|
335
|
+ } else {
|
|
|
336
|
+ console.warn('未登录状态,无法切换会话过滤');
|
|
|
337
|
+ }
|
|
|
338
|
+ }
|
|
|
339
|
+
|
|
|
340
|
+ ngOnDestroy() {
|
|
|
341
|
+ this.subscriptions.unsubscribe();
|
|
|
342
|
+ this.disconnect();
|
|
|
343
|
+ }
|
|
|
344
|
+}
|