Unverified Commit 3ebd8803 authored by gaoyan's avatar gaoyan Committed by GitHub

Add sse heart 3 (#3391)

parent 72cfc1f2
...@@ -55,10 +55,9 @@ public class UdfClassLoaderAspect { ...@@ -55,10 +55,9 @@ public class UdfClassLoaderAspect {
proceed = proceedingJoinPoint.proceed(); proceed = proceedingJoinPoint.proceed();
} catch (Throwable e) { } catch (Throwable e) {
if (!(e instanceof DinkyException)) { if (!(e instanceof DinkyException)) {
throw new DinkyException(e); throw new RuntimeException(e);
} }
e.printStackTrace(); throw (RuntimeException) e;
throw (DinkyException) e;
} finally { } finally {
if (contextClassLoader != Thread.currentThread().getContextClassLoader()) { if (contextClassLoader != Thread.currentThread().getContextClassLoader()) {
Thread.currentThread().setContextClassLoader(contextClassLoader); Thread.currentThread().setContextClassLoader(contextClassLoader);
......
...@@ -19,6 +19,7 @@ ...@@ -19,6 +19,7 @@
package org.dinky.context; package org.dinky.context;
import org.dinky.daemon.pool.ScheduleThreadPool;
import org.dinky.data.constant.SseConstant; import org.dinky.data.constant.SseConstant;
import org.dinky.data.exception.BusException; import org.dinky.data.exception.BusException;
import org.dinky.data.vo.SseDataVo; import org.dinky.data.vo.SseDataVo;
...@@ -30,15 +31,39 @@ import java.util.Map; ...@@ -30,15 +31,39 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.springframework.scheduling.support.PeriodicTrigger;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import lombok.Data; import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
@Slf4j @Slf4j
@Data
public class SseSessionContextHolder { public class SseSessionContextHolder {
@Getter
private static final Map<String, TopicSubscriber> sessionMap = new ConcurrentHashMap<>(); private static final Map<String, TopicSubscriber> sessionMap = new ConcurrentHashMap<>();
public static void init(ScheduleThreadPool schedulePool) {
log.info("start init sse heart schedule task");
PeriodicTrigger trigger = new PeriodicTrigger(9 * 1000L);
schedulePool.addSchedule(
SseSessionContextHolder.class.toString(), SseSessionContextHolder::checkHeart, trigger);
}
public static void checkHeart() {
sessionMap.forEach((sessionKey, topicSubscriber) -> {
try {
SseDataVo data = new SseDataVo(sessionKey, SseConstant.HEART_TOPIC, "heart");
sendSse(sessionKey, data);
} catch (Exception e) {
log.error("Error sending sse data:{}", e.getMessage());
onError(topicSubscriber.getEmitter(), sessionKey, e);
}
});
}
/** /**
* Subscribes a session to the topics. * Subscribes a session to the topics.
* A session can subscribe to multiple topics * A session can subscribe to multiple topics
...@@ -65,21 +90,20 @@ public class SseSessionContextHolder { ...@@ -65,21 +90,20 @@ public class SseSessionContextHolder {
* @param sessionKey The session key of the new session. * @param sessionKey The session key of the new session.
* @return The SseEmitter for the session. * @return The SseEmitter for the session.
*/ */
public static SseEmitter connectSession(String sessionKey) { public static synchronized SseEmitter connectSession(String sessionKey) {
log.debug("New session wants to connect: {}", sessionKey); log.debug("New session wants to connect: {}", sessionKey);
log.warn("Session key already exists: {},replace it", sessionKey);
SseEmitter sseEmitter = new SseEmitter(60 * 1000L * 10); SseEmitter sseEmitter = new SseEmitter(30 * 60 * 1000L);
sseEmitter.onError(err -> onError(sessionKey, err)); sseEmitter.onError(err -> onError(sseEmitter, sessionKey, err));
sseEmitter.onTimeout(() -> onTimeout(sessionKey)); sseEmitter.onTimeout(() -> onTimeout(sseEmitter));
sseEmitter.onCompletion(() -> onCompletion(sessionKey)); sseEmitter.onCompletion(() -> onCompletion(sseEmitter, sessionKey));
sessionMap.put(sessionKey, TopicSubscriber.of(sseEmitter));
try { try {
// Set the client reconnection interval, 0 to reconnect immediately // Set the client reconnection interval, 0 to reconnect immediately
sseEmitter.send(SseEmitter.event().reconnectTime(1000)); sseEmitter.send(SseEmitter.event().reconnectTime(1000));
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException(e); throw new RuntimeException(e);
} }
sessionMap.put(sessionKey, TopicSubscriber.of(sseEmitter));
return sseEmitter; return sseEmitter;
} }
...@@ -95,28 +119,12 @@ public class SseSessionContextHolder { ...@@ -95,28 +119,12 @@ public class SseSessionContextHolder {
/** /**
* Handles the timeout event for a session. * Handles the timeout event for a session.
*
* @param sessionKey The session key of the timed-out session.
*/ */
public static void onTimeout(String sessionKey) { public static void onTimeout(SseEmitter sseEmitter) {
log.debug("Type: SseSession Timeout, Session ID: {}", sessionKey);
closeSse(sessionKey);
}
/**
* Closes the SseEmitter for a session.
*
* @param sessionKey The session key of the session to close.
*/
public static void closeSse(String sessionKey) {
if (exists(sessionKey)) {
try { try {
sessionMap.get(sessionKey).getEmitter().complete(); sseEmitter.complete();
} catch (Exception e) { } catch (Exception e) {
log.warn("Failed to complete sseEmitter, Session Key: {}, Error: {}", sessionKey, e.getMessage()); log.warn("Failed to complete sseEmitter, Error: {}", e.getMessage());
} finally {
sessionMap.remove(sessionKey);
}
} }
} }
...@@ -126,16 +134,14 @@ public class SseSessionContextHolder { ...@@ -126,16 +134,14 @@ public class SseSessionContextHolder {
* @param sessionKey The session key of the session with the error. * @param sessionKey The session key of the session with the error.
* @param throwable The throwable representing the error. * @param throwable The throwable representing the error.
*/ */
public static void onError(String sessionKey, Throwable throwable) { private static void onError(SseEmitter sseEmitter, String sessionKey, Throwable throwable) {
log.error("Type: SseSession [{}] Error, Message: {}", sessionKey, throwable.getMessage()); log.debug("Type: SseSession [{}] Error, Message: {}", sessionKey, throwable.getMessage());
if (exists(sessionKey)) {
try { try {
sessionMap.get(sessionKey).getEmitter().completeWithError(throwable); sseEmitter.completeWithError(throwable);
} catch (Exception e) { } catch (Exception e) {
log.error("Failed to complete Sse With Error: {}", e.getMessage()); log.debug("Failed to complete Sse With Error: {}", e.getMessage());
}
} }
sessionMap.remove(sessionKey); onCompletion(sseEmitter, sessionKey);
} }
/** /**
...@@ -143,9 +149,14 @@ public class SseSessionContextHolder { ...@@ -143,9 +149,14 @@ public class SseSessionContextHolder {
* *
* @param sessionKey The session key of the completed session. * @param sessionKey The session key of the completed session.
*/ */
public static void onCompletion(String sessionKey) { private static synchronized void onCompletion(SseEmitter sseEmitter, String sessionKey) {
log.debug("Type: SseSession Completion, Session ID: {}", sessionKey); log.debug("Type: SseSession Completion, Session ID: {}", sessionKey);
closeSse(sessionKey); if (exists(sessionKey)) {
SseEmitter emitter = sessionMap.get(sessionKey).getEmitter();
if (emitter == sseEmitter) {
sessionMap.remove(sessionKey);
}
}
} }
/** /**
...@@ -162,7 +173,7 @@ public class SseSessionContextHolder { ...@@ -162,7 +173,7 @@ public class SseSessionContextHolder {
sendSse(sessionKey, data); sendSse(sessionKey, data);
} catch (Exception e) { } catch (Exception e) {
log.error("Error sending sse data:{}", e.getMessage()); log.error("Error sending sse data:{}", e.getMessage());
onError(sessionKey, e); onError(topicSubscriber.getEmitter(), sessionKey, e);
} }
} }
}); });
......
...@@ -34,6 +34,7 @@ import org.springframework.web.bind.annotation.RequestMapping; ...@@ -34,6 +34,7 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import cn.dev33.satoken.annotation.SaCheckLogin;
import io.swagger.annotations.Api; import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiOperation;
...@@ -43,6 +44,7 @@ import lombok.RequiredArgsConstructor; ...@@ -43,6 +44,7 @@ import lombok.RequiredArgsConstructor;
@Api(tags = "SSE Controller") @Api(tags = "SSE Controller")
@RequestMapping("/api/sse") @RequestMapping("/api/sse")
@RequiredArgsConstructor @RequiredArgsConstructor
@SaCheckLogin
public class SseController { public class SseController {
@PostMapping(value = "/subscribeTopic") @PostMapping(value = "/subscribeTopic")
......
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
package org.dinky.init; package org.dinky.init;
import org.dinky.assertion.Asserts; import org.dinky.assertion.Asserts;
import org.dinky.context.SseSessionContextHolder;
import org.dinky.context.TenantContextHolder; import org.dinky.context.TenantContextHolder;
import org.dinky.daemon.pool.FlinkJobThreadPool; import org.dinky.daemon.pool.FlinkJobThreadPool;
import org.dinky.daemon.pool.ScheduleThreadPool; import org.dinky.daemon.pool.ScheduleThreadPool;
...@@ -154,7 +155,7 @@ public class SystemInit implements ApplicationRunner { ...@@ -154,7 +155,7 @@ public class SystemInit implements ApplicationRunner {
Configuration<Integer> sysGatherTiming = sysConfig.getMetricsSysGatherTiming(); Configuration<Integer> sysGatherTiming = sysConfig.getMetricsSysGatherTiming();
Consumer<Configuration<?>> metricsListener = c -> { Consumer<Configuration<?>> metricsListener = c -> {
c.addChangeEvent(x -> { c.addChangeEvent(x -> {
schedule.removeSchedule(sysMetricsTask); schedule.removeSchedule(sysMetricsTask.getType());
PeriodicTrigger trigger = new PeriodicTrigger(sysGatherTiming.getValue()); PeriodicTrigger trigger = new PeriodicTrigger(sysGatherTiming.getValue());
if (metricsSysEnable.getValue()) schedule.addSchedule(sysMetricsTask, trigger); if (metricsSysEnable.getValue()) schedule.addSchedule(sysMetricsTask, trigger);
}); });
...@@ -175,6 +176,7 @@ public class SystemInit implements ApplicationRunner { ...@@ -175,6 +176,7 @@ public class SystemInit implements ApplicationRunner {
DaemonTask daemonTask = DaemonTask.build(config); DaemonTask daemonTask = DaemonTask.build(config);
flinkJobThreadPool.execute(daemonTask); flinkJobThreadPool.execute(daemonTask);
} }
SseSessionContextHolder.init(schedule);
} }
/** /**
......
...@@ -24,4 +24,6 @@ public class SseConstant { ...@@ -24,4 +24,6 @@ public class SseConstant {
* Sse label for front to reconnect session * Sse label for front to reconnect session
*/ */
public static final String SSE_SESSION_INVALID = "SESSION_INVALID"; public static final String SSE_SESSION_INVALID = "SESSION_INVALID";
public static final String HEART_TOPIC = "HEART_BEAT";
} }
...@@ -41,8 +41,13 @@ public class ScheduleThreadPool { ...@@ -41,8 +41,13 @@ public class ScheduleThreadPool {
getScheduleMap().put(task.getType(), schedule); getScheduleMap().put(task.getType(), schedule);
} }
public void removeSchedule(DaemonTask task) { public void addSchedule(String type, Runnable task, Trigger trigger) {
ScheduledFuture<?> scheduledFuture = getScheduleMap().get(task.getType()); ScheduledFuture<?> schedule = threadPoolTaskScheduler.schedule(task, trigger);
getScheduleMap().put(type, schedule);
}
public void removeSchedule(String type) {
ScheduledFuture<?> scheduledFuture = getScheduleMap().get(type);
if (scheduledFuture != null) { if (scheduledFuture != null) {
scheduledFuture.cancel(true); scheduledFuture.cancel(true);
} }
......
...@@ -35,9 +35,18 @@ export type SubscriberData = { ...@@ -35,9 +35,18 @@ export type SubscriberData = {
export default () => { export default () => {
const uuidRef = useRef<string>(uuidv4()); const uuidRef = useRef<string>(uuidv4());
const lastHeartTime = useRef<number>(0);
const subscriberRef = useRef<SubscriberData[]>([]); const subscriberRef = useRef<SubscriberData[]>([]);
const [eventSource, setEventSource] = useState<EventSource>(); const [eventSource, setEventSource] = useState<EventSource>();
const reconnectSse = () => {
lastHeartTime.current = Date.now();
uuidRef.current = uuidv4();
const sseUrl = 'api/sse/connect?sessionKey=' + uuidRef.current;
eventSource?.close();
setEventSource(new EventSource(sseUrl));
};
const subscribe = async () => { const subscribe = async () => {
const topics: string[] = []; const topics: string[] = [];
subscriberRef.current.forEach((sub) => topics.push(...sub.topic)); subscriberRef.current.forEach((sub) => topics.push(...sub.topic));
...@@ -50,15 +59,13 @@ export default () => { ...@@ -50,15 +59,13 @@ export default () => {
}) })
.catch((e) => ErrorMessage(e)); .catch((e) => ErrorMessage(e));
}; };
const reconnectSse = () => {
uuidRef.current = uuidv4();
const sseUrl = 'api/sse/connect?sessionKey=' + uuidRef.current;
eventSource?.close();
setEventSource(new EventSource(sseUrl));
};
useEffect(() => { useEffect(() => {
setInterval(() => {
if (Date.now() - lastHeartTime.current > 20 * 1000) {
reconnectSse(); reconnectSse();
}
}, 5000);
}, []); }, []);
useEffect(() => { useEffect(() => {
...@@ -67,9 +74,13 @@ export default () => { ...@@ -67,9 +74,13 @@ export default () => {
eventSource.onmessage = (e) => { eventSource.onmessage = (e) => {
try { try {
const data: SseData = JSON.parse(e.data); const data: SseData = JSON.parse(e.data);
if (data.topic === 'HEART_BEAT') {
lastHeartTime.current = Date.now();
} else {
subscriberRef.current subscriberRef.current
.filter((sub) => sub.topic.includes(data.topic)) .filter((sub) => sub.topic.includes(data.topic))
.forEach((sub) => sub.call(data)); .forEach((sub) => sub.call(data));
}
} catch (e: any) { } catch (e: any) {
ErrorMessage(e); ErrorMessage(e);
} }
......
...@@ -43,8 +43,6 @@ const Login: React.FC = () => { ...@@ -43,8 +43,6 @@ const Login: React.FC = () => {
const [localStorageOfToken, setLocalStorageOfToken] = useLocalStorage('token', ''); const [localStorageOfToken, setLocalStorageOfToken] = useLocalStorage('token', '');
const { reconnectSse } = useModel('Sse', (model: any) => ({ reconnectSse: model.reconnectSse }));
const containerClassName = useEmotionCss(() => { const containerClassName = useEmotionCss(() => {
return { return {
display: 'flex', display: 'flex',
...@@ -99,7 +97,6 @@ const Login: React.FC = () => { ...@@ -99,7 +97,6 @@ const Login: React.FC = () => {
/** /**
* Redirect to home page && reconnect Global Sse * Redirect to home page && reconnect Global Sse
*/ */
reconnectSse();
gotoRedirectUrl(); gotoRedirectUrl();
} else { } else {
ErrorMessage(l('login.chooseTenantFailed')); ErrorMessage(l('login.chooseTenantFailed'));
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment