Repository navigation
✅ [Deploy] v0.5.1 배포 #144
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
✅ [Deploy] v0.5.1 배포 #144
Changes from all commits
4041c38
7650d37
4d6be6f
c7f2999
723cb7e
98efdee
7569673
a63b6d8
8c99c82
0d3e58f
d052a5f
5880e28
edfc10e
670853a
52c7ed2
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,27 +1,107 @@ | ||
| package com.example.scoi.domain.websocket; | ||
|
|
||
| import com.example.scoi.domain.websocket.code.WebsocketErrorCode; | ||
| import com.example.scoi.domain.websocket.event.WebsocketConnectionEvent.ConnectedEvent; | ||
| import com.example.scoi.domain.websocket.event.WebsocketConnectionEvent.DisconnectedEvent; | ||
| import com.example.scoi.domain.websocket.exception.WebsocketException; | ||
| import com.example.scoi.domain.websocket.handler.UpbitTickerHandler; | ||
| import jakarta.annotation.PreDestroy; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.ObjectProvider; | ||
| import org.springframework.boot.context.event.ApplicationReadyEvent; | ||
| import org.springframework.context.event.EventListener; | ||
| import org.springframework.retry.annotation.Backoff; | ||
| import org.springframework.retry.annotation.Recover; | ||
| import org.springframework.retry.annotation.Retryable; | ||
| import org.springframework.scheduling.annotation.Async; | ||
| import org.springframework.stereotype.Service; | ||
| import org.springframework.web.socket.client.WebSocketClient; | ||
|
|
||
| import java.util.concurrent.Executors; | ||
| import java.util.concurrent.ScheduledExecutorService; | ||
| import java.util.concurrent.ScheduledFuture; | ||
| import java.util.concurrent.TimeUnit; | ||
|
|
||
| @Service | ||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| public class WebsocketConnect { | ||
|
|
||
| private final WebSocketClient webSocketClient; | ||
| private final UpbitTickerHandler upbitTickerHandler; | ||
| private final ObjectProvider<WebsocketConnect> selfProvider; // AOP 우회 방지를 위한 프록시 의존성 | ||
|
|
||
| private static final String PUBLIC_URL = "wss://api.upbit.com/websocket/v1"; | ||
|
|
||
| // 실시간 가격 변동 체크 | ||
| // 워치독(Half-Open 헬스체크) 전용 스케줄러 | ||
| private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); | ||
| private ScheduledFuture<?> watchdogTask; | ||
|
|
||
| @EventListener(ApplicationReadyEvent.class) | ||
| public void connect(){ | ||
| log.info("[ Websocket ]: 디페깅 알고리즘 구동 시작..."); | ||
| webSocketClient.execute(upbitTickerHandler, PUBLIC_URL); | ||
| public void init() { | ||
| log.info("[ Websocket ]: 애플리케이션 준비 완료."); | ||
| selfProvider.getObject().connectWithRetry(); | ||
| } | ||
|
|
||
| @Async | ||
| @Retryable( | ||
| retryFor = WebsocketException.class, | ||
| maxAttempts = 10, | ||
| backoff = @Backoff(delay = 1000, multiplier = 2, maxDelay = 60000) | ||
| ) | ||
| public void connectWithRetry() { | ||
| log.info("[ Websocket ]: 업비트 웹소켓 연결 시도 중... URL: {}", PUBLIC_URL); | ||
| try { | ||
| // execute()의 리턴값인 Future를 대기(get)하여 타임아웃이나 연결 거부 시 예외를 발생시키도록 유도 | ||
| webSocketClient.execute(upbitTickerHandler, PUBLIC_URL).get(5, TimeUnit.SECONDS); | ||
| } catch (Exception e) { | ||
| log.error("[ Websocket ]: 웹소켓 연결 실패: {}", e.getMessage()); | ||
| // 예외를 던져서 @Retryable이 AOP 기반 백오프 및 재시도를 수행하도록 트리거 | ||
| throw new WebsocketException(WebsocketErrorCode.UPBIT_WEBSOCKET_ERROR); | ||
| } | ||
| } | ||
|
|
||
| @Recover | ||
| public void recover(Exception e) { | ||
| log.error("[ Websocket ]: 웹소켓 재연결 최대 시도 횟수(10회) 초과"); | ||
|
|
||
| // 2시간뒤 다시 시도 | ||
| scheduler.schedule(() -> { | ||
| log.info("[ Websocket ]: 시스템 복구를 위해 웹소켓 재연결 사이클을 다시 시작합니다."); | ||
| selfProvider.getObject().connectWithRetry(); | ||
| }, 2, TimeUnit.HOURS); | ||
| } | ||
|
|
||
| @EventListener | ||
| public void onConnected(ConnectedEvent event) { | ||
| log.info("[ Websocket ]: 이벤트 수신 - 웹소켓 연결 활성화 완료."); | ||
|
|
||
| if (watchdogTask != null && !watchdogTask.isCancelled()) { | ||
| watchdogTask.cancel(false); | ||
| } | ||
| // 10초마다 마지막 수신 시간 검사 | ||
| watchdogTask = scheduler.scheduleAtFixedRate(() -> { | ||
| long idleTime = System.currentTimeMillis() - upbitTickerHandler.getLastMessageTime(); | ||
| if (idleTime > 30_000) { // 30초 초과 시 | ||
| log.error("[ Websocket ]: 30초간 업비트 응답이 없습니다..."); | ||
| upbitTickerHandler.closeSession(); // DisconnectedEvent 유발 | ||
| } | ||
| }, 10, 10, TimeUnit.SECONDS); | ||
| } | ||
|
|
||
| @EventListener | ||
| public void onDisconnected(DisconnectedEvent event) { | ||
| log.warn("[ Websocket ]: 이벤트 수신 - 웹소켓 연결 해제. 재연결 시도"); | ||
| if (watchdogTask != null) { | ||
| watchdogTask.cancel(false); | ||
| } | ||
| selfProvider.getObject().connectWithRetry(); | ||
| } | ||
|
|
||
| @PreDestroy | ||
| public void shutdown() { | ||
| log.info("[ Websocket ]: 워치독 스케줄러 종료 중..."); | ||
| scheduler.shutdown(); | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,20 @@ | ||
| package com.example.scoi.domain.websocket.code; | ||
|
|
||
| import com.example.scoi.global.apiPayload.code.BaseErrorCode; | ||
| import lombok.Getter; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.HttpStatus; | ||
|
|
||
| @Getter | ||
| @RequiredArgsConstructor | ||
| public enum WebsocketErrorCode implements BaseErrorCode { | ||
|
|
||
| UPBIT_WEBSOCKET_ERROR(HttpStatus.INTERNAL_SERVER_ERROR, | ||
| "WEBSOCKET500_1", | ||
| "웹소켓 연결 도중 에러가 발생했습니다."), | ||
| ; | ||
|
|
||
| private final HttpStatus status; | ||
| private final String code; | ||
| private final String message; | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| package com.example.scoi.domain.websocket.event; | ||
|
|
||
| public interface WebsocketConnectionEvent { | ||
| record ConnectedEvent() implements WebsocketConnectionEvent {} | ||
| record DisconnectedEvent() implements WebsocketConnectionEvent {} | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package com.example.scoi.domain.websocket.exception; | ||
|
|
||
| import com.example.scoi.global.apiPayload.code.BaseErrorCode; | ||
| import com.example.scoi.global.apiPayload.exception.ScoiException; | ||
|
|
||
| public class WebsocketException extends ScoiException { | ||
| public WebsocketException(BaseErrorCode code) { | ||
| super(code); | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -2,14 +2,19 @@ | |||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| import com.example.scoi.domain.websocket.converter.WebSocketConverter; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import com.example.scoi.domain.websocket.dto.UpbitResDTO; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import com.example.scoi.domain.websocket.event.WebsocketConnectionEvent.ConnectedEvent; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import com.example.scoi.domain.websocket.event.WebsocketConnectionEvent.DisconnectedEvent; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import com.example.scoi.domain.websocket.service.WebSocketService; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import com.fasterxml.jackson.databind.ObjectMapper; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import com.fasterxml.jackson.databind.PropertyNamingStrategies; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import lombok.RequiredArgsConstructor; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import lombok.extern.slf4j.Slf4j; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.context.ApplicationEventPublisher; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.messaging.simp.SimpMessageSendingOperations; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.scheduling.annotation.Async; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.stereotype.Component; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.web.socket.BinaryMessage; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.web.socket.CloseStatus; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.web.socket.WebSocketSession; | ||||||||||||||||||||||||||||||||||||||||||||||||
| import org.springframework.web.socket.handler.BinaryWebSocketHandler; | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -19,18 +24,27 @@ | |||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| @Component | ||||||||||||||||||||||||||||||||||||||||||||||||
| @RequiredArgsConstructor | ||||||||||||||||||||||||||||||||||||||||||||||||
| @Slf4j | ||||||||||||||||||||||||||||||||||||||||||||||||
| public class UpbitTickerHandler extends BinaryWebSocketHandler { | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| private final SimpMessageSendingOperations simpMessageSendingOperations; | ||||||||||||||||||||||||||||||||||||||||||||||||
| private final WebSocketService webSocketService; | ||||||||||||||||||||||||||||||||||||||||||||||||
| private final ApplicationEventPublisher eventPublisher; | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| private static final ObjectMapper objectMapper = new ObjectMapper() | ||||||||||||||||||||||||||||||||||||||||||||||||
| .setPropertyNamingStrategy(PropertyNamingStrategies.LOWER_CAMEL_CASE); | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| private volatile long lastMessageTime; | ||||||||||||||||||||||||||||||||||||||||||||||||
| private volatile WebSocketSession currentSession; | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| @Override | ||||||||||||||||||||||||||||||||||||||||||||||||
| public void afterConnectionEstablished( | ||||||||||||||||||||||||||||||||||||||||||||||||
| WebSocketSession session | ||||||||||||||||||||||||||||||||||||||||||||||||
| ) throws IOException { | ||||||||||||||||||||||||||||||||||||||||||||||||
| this.currentSession = session; | ||||||||||||||||||||||||||||||||||||||||||||||||
| this.lastMessageTime = System.currentTimeMillis(); | ||||||||||||||||||||||||||||||||||||||||||||||||
| log.info("[ Websocket ]: 업비트 웹소켓 연결 성공."); | ||||||||||||||||||||||||||||||||||||||||||||||||
| eventPublisher.publishEvent(new ConnectedEvent()); | ||||||||||||||||||||||||||||||||||||||||||||||||
| session.sendMessage(WebSocketConverter.toGetCoinPrice(List.of("KRW-USDT","KRW-USDC"))); | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -39,6 +53,8 @@ public void handleBinaryMessage( | |||||||||||||||||||||||||||||||||||||||||||||||
| WebSocketSession session, | ||||||||||||||||||||||||||||||||||||||||||||||||
| BinaryMessage message | ||||||||||||||||||||||||||||||||||||||||||||||||
| ) throws IOException { | ||||||||||||||||||||||||||||||||||||||||||||||||
| this.lastMessageTime = System.currentTimeMillis(); // Heartbeat 갱신 | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| String converted = new String(message.getPayload().array(), StandardCharsets.UTF_8); | ||||||||||||||||||||||||||||||||||||||||||||||||
| converted = converted.replace("[","").replace("]",""); | ||||||||||||||||||||||||||||||||||||||||||||||||
| publish(converted); | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -50,4 +66,31 @@ public void handleBinaryMessage( | |||||||||||||||||||||||||||||||||||||||||||||||
| protected void publish(String message) { | ||||||||||||||||||||||||||||||||||||||||||||||||
| simpMessageSendingOperations.convertAndSend("/topic/ticker", message); | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| @Override | ||||||||||||||||||||||||||||||||||||||||||||||||
| public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception { | ||||||||||||||||||||||||||||||||||||||||||||||||
| log.warn("[ Websocket ]: 업비트 웹소켓 연결이 종료되었습니다. CloseStatus: {}", status); | ||||||||||||||||||||||||||||||||||||||||||||||||
| eventPublisher.publishEvent(new DisconnectedEvent()); | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| @Override | ||||||||||||||||||||||||||||||||||||||||||||||||
| public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { | ||||||||||||||||||||||||||||||||||||||||||||||||
| log.error("[ Websocket ]: 웹소켓 에러 발생: {}", exception.getMessage()); | ||||||||||||||||||||||||||||||||||||||||||||||||
| eventPublisher.publishEvent(new DisconnectedEvent()); | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+69
to
+80
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Spring 공식 문서에 따르면 현재 두 메서드가 모두 🔧 제안: 중복 이벤트 발행 방지 `@Override`
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
log.error("[ Websocket ]: 웹소켓 에러 발생: {}", exception.getMessage());
- eventPublisher.publishEvent(new DisconnectedEvent());
+ // afterConnectionClosed가 전송 오류 이후에도 항상 호출되므로 여기서는 이벤트를 발행하지 않음
}📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| public long getLastMessageTime() { | ||||||||||||||||||||||||||||||||||||||||||||||||
| return lastMessageTime; | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||
| public void closeSession() { | ||||||||||||||||||||||||||||||||||||||||||||||||
| if (currentSession != null && currentSession.isOpen()) { | ||||||||||||||||||||||||||||||||||||||||||||||||
| try { | ||||||||||||||||||||||||||||||||||||||||||||||||
| log.warn("[ Websocket ]: 하프 오픈(Half-open) 상태 감지."); | ||||||||||||||||||||||||||||||||||||||||||||||||
| currentSession.close(); | ||||||||||||||||||||||||||||||||||||||||||||||||
| } catch (IOException e) { | ||||||||||||||||||||||||||||||||||||||||||||||||
| log.error("[ Websocket ]: 세션 강제 종료 중 에러 발생: {}", e.getMessage()); | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: UMCSCOI/Backend
Length of output: 1442
🏁 Script executed:
Repository: UMCSCOI/Backend
Length of output: 5144
🏁 Script executed:
Repository: UMCSCOI/Backend
Length of output: 3017
🏁 Script executed:
Repository: UMCSCOI/Backend
Length of output: 5144
🌐 Web query:
Spring WebSocketClient execute CompletableFuture cancel handshake timeout behavior duplicate session afterConnectionEstablished💡 Result:
In Spring Framework, the WebSocketClient.execute method returns a CompletableFuture that represents the asynchronous handshake process [1][2]. If you cancel this CompletableFuture, the behavior depends on the underlying implementation (e.g., StandardWebSocketClient, ReactorNettyWebSocketClient). Generally, canceling the future does not automatically guarantee that the underlying network connection or handshake process is aborted synchronously, as this depends on whether the implementation checks for cancellation during the connection setup [3][4]. Regarding "duplicate sessions afterConnectionEstablished": 1. Race Condition: If a timeout or cancellation signal is sent just as the handshake completes, there is a risk that the client-side code triggers the handshake failure logic while the server-side successfully upgrades the connection. This can lead to a state where the client perceives a timeout/cancellation but the connection is actually established, potentially leading to dangling or duplicate sessions if the application layer attempts to retry connection establishment without properly closing the previous, orphaned session [5]. 2. Resource Management: Because WebSocket connections involve an upgrade from HTTP, a timeout might abort the handshake attempt on the client side, but the TCP connection may remain open until the server or a network timeout closes it [6]. If your application logic retries the connection in response to the timeout without explicit resource cleanup, multiple sessions may appear to be active. To mitigate this: - Ensure your WebSocketHandler implementation of afterConnectionEstablished is prepared for edge cases where the session might already be closing [7]. - If using Reactor Netty, be aware that certain timeouts may inadvertently abort even a successfully established connection [6]. - Always explicitly call session.close in your error or cancellation handlers if a session object was partially initialized or returned to ensure no resources are leaked [1][4]. Top Results: [1][4][5][6]
Citations:
🏁 Script executed:
Repository: UMCSCOI/Backend
Length of output: 4756
🏁 Script executed:
Repository: UMCSCOI/Backend
Length of output: 4756
중복 연결을 막는 가드가 필요합니다.
connectWithRetry()가 재시도되는 동안 이전execute(...)가 늦게 성공하면afterConnectionEstablished()가 다시 호출되고, 지금은 기존currentSession을 닫지 않은 채 새 세션으로 덮어씁니다. 그 결과 두 세션이 동시에 살아남아/topic/ticker가 중복 전송될 수 있으니, 연결 성공 시 기존 세션을 정리하거나 handler에서 중복 세션을 거부해야 합니다.🤖 Prompt for AI Agents