huang
2025-11-20 366ba040d2447bacd3455299425e3166f1f992bb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
package com.mes.task.service.impl;
 
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mes.task.entity.MultiDeviceTask;
import com.mes.task.entity.TaskStepDetail;
import com.mes.task.service.TaskStatusNotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
 
/**
 * 任务状态通知服务实现
 * 
 * @author mes
 * @since 2025-01-XX
 */
@Slf4j
@Service
public class TaskStatusNotificationServiceImpl implements TaskStatusNotificationService {
 
    private final ObjectMapper objectMapper = new ObjectMapper();
    
    // 存储所有SSE连接:taskId -> List<SseEmitter>
    private final Map<String, List<SseEmitter>> connections = new ConcurrentHashMap<>();
    
    // 存储所有任务的连接(taskId为null时使用)
    private final List<SseEmitter> allTaskConnections = new CopyOnWriteArrayList<>();
    
    // 连接超时时间(毫秒)
    private static final long TIMEOUT = 30 * 60 * 1000L; // 30分钟
 
    @Override
    public SseEmitter createConnection(String taskId) {
        SseEmitter emitter = new SseEmitter(TIMEOUT);
        
        // 设置完成和超时回调
        emitter.onCompletion(() -> {
            log.info("SSE连接完成: taskId={}", taskId);
            removeConnection(taskId, emitter);
        });
        
        emitter.onTimeout(() -> {
            log.info("SSE连接超时: taskId={}", taskId);
            removeConnection(taskId, emitter);
        });
        
        emitter.onError((ex) -> {
            log.error("SSE连接错误: taskId={}", taskId, ex);
            removeConnection(taskId, emitter);
        });
        
        // 添加到连接列表
        if (taskId != null && !taskId.isEmpty()) {
            connections.computeIfAbsent(taskId, k -> new CopyOnWriteArrayList<>()).add(emitter);
        } else {
            allTaskConnections.add(emitter);
        }
        
        try {
            // 发送初始连接成功消息
            Map<String, Object> initData = new HashMap<>();
            if (taskId != null) {
                initData.put("taskId", taskId);
            }
            emitter.send(SseEmitter.event()
                .name("connected")
                .data(createMessage("连接成功", initData)));
        } catch (IOException e) {
            log.error("发送初始消息失败: taskId={}", taskId, e);
            removeConnection(taskId, emitter);
            return null;
        }
        
        log.info("创建SSE连接: taskId={}, 当前连接数={}", taskId, getConnectionCount(taskId));
        return emitter;
    }
 
    @Override
    public void notifyTaskStatus(MultiDeviceTask task) {
        if (task == null || task.getTaskId() == null) {
            return;
        }
        
        String taskId = task.getTaskId();
        Map<String, Object> data = createTaskStatusData(task);
        
        // 发送给指定任务的连接
        sendToConnections(taskId, "taskStatus", data);
        
        // 发送给所有任务的连接
        sendToAllTaskConnections("taskStatus", data);
        
        log.debug("推送任务状态: taskId={}, status={}", taskId, task.getStatus());
    }
 
    @Override
    public void notifyStepUpdate(String taskId, TaskStepDetail step) {
        if (taskId == null || step == null) {
            return;
        }
        
        Map<String, Object> data = createStepData(step);
        
        // 发送给指定任务的连接
        sendToConnections(taskId, "stepUpdate", data);
        
        // 发送给所有任务的连接
        Map<String, Object> allTaskData = new HashMap<>();
        allTaskData.put("taskId", taskId);
        allTaskData.put("step", data);
        sendToAllTaskConnections("stepUpdate", allTaskData);
        
        log.debug("推送步骤更新: taskId={}, stepOrder={}, status={}", 
            taskId, step.getStepOrder(), step.getStatus());
    }
 
    @Override
    public void notifyStepsUpdate(String taskId, List<TaskStepDetail> steps) {
        if (taskId == null || steps == null) {
            return;
        }
        
        Map<String, Object> data = new HashMap<>();
        data.put("taskId", taskId);
        data.put("steps", steps);
        data.put("stepCount", steps.size());
        
        // 发送给指定任务的连接
        sendToConnections(taskId, "stepsUpdate", data);
        
        // 发送给所有任务的连接
        sendToAllTaskConnections("stepsUpdate", data);
        
        log.debug("推送步骤列表更新: taskId={}, stepCount={}", taskId, steps.size());
    }
 
    @Override
    public void closeConnections(String taskId) {
        if (taskId == null) {
            return;
        }
        
        List<SseEmitter> emitters = connections.remove(taskId);
        if (emitters != null) {
            for (SseEmitter emitter : emitters) {
                try {
                    emitter.complete();
                } catch (Exception e) {
                    log.warn("关闭SSE连接失败: taskId={}", taskId, e);
                }
            }
            log.info("关闭任务连接: taskId={}, 连接数={}", taskId, emitters.size());
        }
    }
 
    @Override
    public void closeAllConnections() {
        // 关闭所有任务连接
        for (Map.Entry<String, List<SseEmitter>> entry : connections.entrySet()) {
            for (SseEmitter emitter : entry.getValue()) {
                try {
                    emitter.complete();
                } catch (Exception e) {
                    log.warn("关闭SSE连接失败: taskId={}", entry.getKey(), e);
                }
            }
        }
        connections.clear();
        
        // 关闭所有任务监听连接
        for (SseEmitter emitter : allTaskConnections) {
            try {
                emitter.complete();
            } catch (Exception e) {
                log.warn("关闭SSE连接失败", e);
            }
        }
        allTaskConnections.clear();
        
        log.info("关闭所有SSE连接");
    }
 
    /**
     * 发送消息到指定任务的连接
     */
    private void sendToConnections(String taskId, String eventName, Map<String, Object> data) {
        List<SseEmitter> emitters = connections.get(taskId);
        if (emitters == null || emitters.isEmpty()) {
            return;
        }
        
        List<SseEmitter> toRemove = new CopyOnWriteArrayList<>();
        for (SseEmitter emitter : emitters) {
            try {
                emitter.send(SseEmitter.event()
                    .name(eventName)
                    .data(createMessage("", data)));
            } catch (IOException e) {
                log.warn("发送SSE消息失败: taskId={}, event={}", taskId, eventName, e);
                toRemove.add(emitter);
            }
        }
        
        // 移除失败的连接
        emitters.removeAll(toRemove);
    }
 
    /**
     * 发送消息到所有任务监听连接
     */
    private void sendToAllTaskConnections(String eventName, Map<String, Object> data) {
        if (allTaskConnections.isEmpty()) {
            return;
        }
        
        List<SseEmitter> toRemove = new CopyOnWriteArrayList<>();
        for (SseEmitter emitter : allTaskConnections) {
            try {
                emitter.send(SseEmitter.event()
                    .name(eventName)
                    .data(createMessage("", data)));
            } catch (IOException e) {
                log.warn("发送SSE消息失败: event={}", eventName, e);
                toRemove.add(emitter);
            }
        }
        
        // 移除失败的连接
        allTaskConnections.removeAll(toRemove);
    }
 
    /**
     * 移除连接
     */
    private void removeConnection(String taskId, SseEmitter emitter) {
        if (taskId != null && !taskId.isEmpty()) {
            List<SseEmitter> emitters = connections.get(taskId);
            if (emitters != null) {
                emitters.remove(emitter);
                if (emitters.isEmpty()) {
                    connections.remove(taskId);
                }
            }
        } else {
            allTaskConnections.remove(emitter);
        }
    }
 
    /**
     * 获取连接数
     */
    private int getConnectionCount(String taskId) {
        if (taskId != null && !taskId.isEmpty()) {
            List<SseEmitter> emitters = connections.get(taskId);
            return emitters != null ? emitters.size() : 0;
        }
        return allTaskConnections.size();
    }
 
    /**
     * 创建任务状态数据
     */
    private Map<String, Object> createTaskStatusData(MultiDeviceTask task) {
        Map<String, Object> data = new HashMap<>();
        data.put("taskId", task.getTaskId() != null ? task.getTaskId() : "");
        data.put("groupId", task.getGroupId() != null ? task.getGroupId() : "");
        data.put("status", task.getStatus() != null ? task.getStatus() : "");
        data.put("currentStep", task.getCurrentStep() != null ? task.getCurrentStep() : 0);
        data.put("totalSteps", task.getTotalSteps() != null ? task.getTotalSteps() : 0);
        data.put("startTime", task.getStartTime() != null ? task.getStartTime().getTime() : 0);
        data.put("endTime", task.getEndTime() != null ? task.getEndTime().getTime() : 0);
        data.put("errorMessage", task.getErrorMessage() != null ? task.getErrorMessage() : "");
        return data;
    }
 
    /**
     * 创建步骤数据
     */
    private Map<String, Object> createStepData(TaskStepDetail step) {
        Map<String, Object> data = new HashMap<>();
        data.put("id", step.getId() != null ? step.getId() : 0);
        data.put("stepOrder", step.getStepOrder() != null ? step.getStepOrder() : 0);
        data.put("deviceId", step.getDeviceId() != null ? step.getDeviceId() : "");
        data.put("stepName", step.getStepName() != null ? step.getStepName() : "");
        data.put("status", step.getStatus() != null ? step.getStatus() : "");
        data.put("startTime", step.getStartTime() != null ? step.getStartTime().getTime() : 0);
        data.put("endTime", step.getEndTime() != null ? step.getEndTime().getTime() : 0);
        data.put("durationMs", step.getDurationMs() != null ? step.getDurationMs() : 0);
        data.put("retryCount", step.getRetryCount() != null ? step.getRetryCount() : 0);
        data.put("errorMessage", step.getErrorMessage() != null ? step.getErrorMessage() : "");
        return data;
    }
 
    /**
     * 创建消息对象
     */
    private String createMessage(String message, Map<String, Object> data) {
        try {
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("timestamp", System.currentTimeMillis());
            if (message != null && !message.isEmpty()) {
                result.put("message", message);
            }
            if (data != null && !data.isEmpty()) {
                result.putAll(data);
            }
            return objectMapper.writeValueAsString(result);
        } catch (Exception e) {
            log.error("序列化消息失败", e);
            return "{}";
        }
    }
}