Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,10 @@ jobs:
echo "DOCKER_USERNAME=${{ secrets.DOCKER_USERNAME }}" >> .env

# Docker Hub에서 방금 만든 최신 이미지 가져오기
sudo docker-compose pull
sudo docker compose pull

# 컨테이너 재실행
sudo docker-compose up -d
sudo docker compose up -d

# 불필요한 이미지 삭제
sudo docker image prune -f
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class AuthResDTO {
// SMS 발송 응답
@JsonInclude(JsonInclude.Include.NON_NULL)
public record SmsSendResponse(
LocalDateTime expiredAt, // 인증번호 만료 시간 (발송 시간 + 3분)
LocalDateTime expiredAt, // 인증번호 만료 시간 (발송 시간 + 5분)
String verificationCode // 개발/QA 환경에서만 포함 (프로덕션에서는 null)
) {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ public enum AuthErrorCode implements BaseErrorCode {
SMS_COOLDOWN(HttpStatus.TOO_MANY_REQUESTS,
"AUTH429_1",
"잠시 후 다시 시도해주세요. (1분 후 재요청 가능)"),
VERIFICATION_ATTEMPTS_EXCEEDED(HttpStatus.TOO_MANY_REQUESTS,
"AUTH429_2",
"인증 시도 횟수를 초과했습니다. 인증번호를 다시 요청해주세요."),

// 회원가입/로그인 관련
ALREADY_REGISTERED_PHONE(HttpStatus.CONFLICT,
Expand Down
55 changes: 33 additions & 22 deletions src/main/java/com/example/scoi/domain/auth/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,11 @@ public class AuthService {
private static final String BLACKLIST_PREFIX = "blacklist:";
private static final String SMS_COOLDOWN_PREFIX = "sms:cooldown:";
private static final String SMS_REQUIRED_PREFIX = "sms_required:";
private static final String SMS_VERIFY_FAIL_PREFIX = "sms:verify:fail:";

// 상수
private static final int SMS_CODE_LENGTH = 6;
private static final int MAX_VERIFY_ATTEMPTS = 5;
private static final long SMS_EXPIRATION_MINUTES = 5;
private static final long VERIFICATION_EXPIRATION_MINUTES = 10;
private static final long REFRESH_TOKEN_SLIDING_DAYS = 14; // 비활성 기준 만료
Expand All @@ -85,9 +87,10 @@ public AuthResDTO.SmsSendResponse sendSms(AuthReqDTO.SmsSendRequest request) {
// 1. 인증번호 생성 (6자리)
String verificationCode = String.format("%06d", ThreadLocalRandom.current().nextInt(1000000));

// 2. Redis 저장
// 2. Redis 저장 (새 코드에는 새 시도 예산을 부여)
String redisKey = SMS_PREFIX + request.phoneNumber();
redisUtil.set(redisKey, verificationCode, SMS_EXPIRATION_MINUTES, TimeUnit.MINUTES);
redisUtil.delete(SMS_VERIFY_FAIL_PREFIX + request.phoneNumber());

// 3. CoolSMS 발송
if (smsEnabled) {
Expand All @@ -99,7 +102,7 @@ public AuthResDTO.SmsSendResponse sendSms(AuthReqDTO.SmsSendRequest request) {
);
CoolSmsDTO.SendRequest smsRequest = new CoolSmsDTO.SendRequest(message);
coolSmsClient.sendMessage(smsRequest);
log.info("SMS 발송 성공: phoneNumber={}, code={}", request.phoneNumber(), verificationCode);
log.info("SMS 발송 성공: phoneNumber={}", request.phoneNumber());
} catch (Exception e) {
log.error("SMS 발송 실패: {}", e.getMessage());
throw new AuthException(AuthErrorCode.SMS_SEND_FAILED);
Expand All @@ -120,19 +123,37 @@ public AuthResDTO.SmsSendResponse sendSms(AuthReqDTO.SmsSendRequest request) {
public AuthResDTO.SmsVerifyResponse verifySms(AuthReqDTO.SmsVerifyRequest request) {
// 1. Redis 조회
String redisKey = SMS_PREFIX + request.phoneNumber();
String failKey = SMS_VERIFY_FAIL_PREFIX + request.phoneNumber();
String storedCode = redisUtil.get(redisKey);

if (storedCode == null) {
throw new AuthException(AuthErrorCode.VERIFICATION_CODE_EXPIRED);
}

// 2. 검증
// 2. 검증 (불일치 시 실패 카운터 증가 → 한도 초과 시 코드 무효화)
if (!storedCode.equals(request.verificationCode())) {
throw new AuthException(AuthErrorCode.INVALID_VERIFICATION_CODE);
long failCount = redisUtil.increment(failKey, SMS_EXPIRATION_MINUTES, TimeUnit.MINUTES);

if (failCount >= MAX_VERIFY_ATTEMPTS) {
// 한도 초과: 코드와 카운터 삭제 → 새 코드 재요청 유도
redisUtil.delete(redisKey);
redisUtil.delete(failKey);
log.warn("SMS 인증 시도 횟수 초과: phoneNumber={}, failCount={}", request.phoneNumber(), failCount);
throw new AuthException(AuthErrorCode.VERIFICATION_ATTEMPTS_EXCEEDED);
}

long remainingAttempts = MAX_VERIFY_ATTEMPTS - failCount;
log.warn("SMS 인증번호 불일치: phoneNumber={}, failCount={}, remainingAttempts={}",
request.phoneNumber(), failCount, remainingAttempts);
throw new AuthException(
AuthErrorCode.INVALID_VERIFICATION_CODE,
Map.of("remainingAttempts", String.valueOf(remainingAttempts))
);
}

// 3. SMS 코드 삭제
// 3. SMS 코드 및 실패 카운터 삭제 (성공 시 초기화)
redisUtil.delete(redisKey);
redisUtil.delete(failKey);

// 4. Verification Token 발급
String verificationToken = jwtUtil.createVerificationToken(request.phoneNumber());
Expand All @@ -151,7 +172,8 @@ public AuthResDTO.SmsVerifyResponse verifySms(AuthReqDTO.SmsVerifyRequest reques
/**
* Verification Token 검증 (범용)
* SMS 인증 완료 후 발급된 토큰이 유효한지 검증합니다.
* 다른 도메인(회원가입, 비밀번호 찾기, 휴대폰 번호 변경 등)에서 재사용 가능합니다.
* 토큰은 소멸되지 않으며, TTL(10분) 동안 회원가입·로그인·비밀번호 재설정 등
* 여러 동작에서 반복 재사용 가능합니다. (매번 SMS 재인증을 요구하지 않기 위한 의도된 설계)
*
* @param verificationToken SMS 인증 완료 후 발급받은 토큰
* @param phoneNumber 검증할 휴대폰 번호
Expand All @@ -175,11 +197,11 @@ public String validateVerificationToken(String verificationToken, String phoneNu
}

// 간편 비밀번호 재설정
@jakarta.transaction.Transactional
@Transactional
public Void resetPassword(
AuthReqDTO.ResetPassword dto
) {
// Verification Token 검증 및 소멸 (SMS 인증 완료 확인)
// Verification Token 검증 (SMS 인증 완료 확인 / 토큰은 TTL 동안 재사용 가능)
String phoneNumber = validateVerificationToken(dto.verificationToken(), dto.phoneNumber());

// 사용자 가져오기
Expand Down Expand Up @@ -210,6 +232,9 @@ public Void resetPassword(

// 로그인 횟수 -> 0
member.resetLoginFailCount();

// RT 만료로 걸린 SMS 재인증 플래그 해제 (이미 SMS 인증을 통과했으므로 잠금 완전 해제)
redisUtil.delete(SMS_REQUIRED_PREFIX + phoneNumber);
return null;
}

Expand Down Expand Up @@ -460,18 +485,4 @@ public void logout(String phoneNumber, String accessToken) {

log.info("로그아웃 성공: phoneNumber={}", phoneNumber);
}

// 임시
public String generateSmsToken(
String phoneNumber
) {
// 4. Verification Token 발급
String verificationToken = jwtUtil.createVerificationToken(phoneNumber);

// 5. Redis 저장 (10분 TTL)
String tokenKey = VERIFICATION_PREFIX + verificationToken;
redisUtil.set(tokenKey, phoneNumber, VERIFICATION_EXPIRATION_MINUTES, TimeUnit.MINUTES);

return verificationToken;
}
}
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);
}
}
Comment on lines +47 to +63

Copy link
Copy Markdown

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:

#!/bin/bash
set -euo pipefail

# Map the relevant files and their surrounding context.
git ls-files | rg 'src/main/java/com/example/scoi/domain/websocket/(WebsocketConnect|UpbitTickerHandler)\.java$|src/main/java/.*/websocket/.*\.java$'

for f in \
  src/main/java/com/example/scoi/domain/websocket/WebsocketConnect.java \
  src/main/java/com/example/scoi/domain/websocket/UpbitTickerHandler.java
do
  if [ -f "$f" ]; then
    echo "===== $f ====="
    wc -l "$f"
    ast-grep outline "$f" --view expanded || true
  fi
done

Repository: UMCSCOI/Backend

Length of output: 1442


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Inspect the full relevant source slices with line numbers.
for f in \
  src/main/java/com/example/scoi/domain/websocket/WebsocketConnect.java \
  src/main/java/com/example/scoi/domain/websocket/UpbitTickerHandler.java
do
  if [ -f "$f" ]; then
    echo "===== $f ====="
    cat -n "$f" | sed -n '1,260p'
  fi
done

Repository: UMCSCOI/Backend

Length of output: 5144


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Search for any session lifecycle or duplicate-connection handling.
rg -n --hidden --glob '!**/target/**' \
  'currentSession|afterConnectionEstablished|WebSocketSession|execute\(upbitTickerHandler|`@Retryable`|WebsocketException|UPBIT_WEBSOCKET_ERROR' \
  src/main/java

Repository: UMCSCOI/Backend

Length of output: 3017


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read only the relevant files if they exist.
for f in \
  src/main/java/com/example/scoi/domain/websocket/WebsocketConnect.java \
  src/main/java/com/example/scoi/domain/websocket/UpbitTickerHandler.java
do
  if [ -f "$f" ]; then
    echo "===== $f ====="
    cat -n "$f" | sed -n '1,220p'
  fi
done

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:

#!/bin/bash
set -euo pipefail

# Inspect the handler lifecycle and session management in detail.
f=src/main/java/com/example/scoi/domain/websocket/handler/UpbitTickerHandler.java
wc -l "$f"
cat -n "$f" | sed -n '1,220p'

Repository: UMCSCOI/Backend

Length of output: 4756


🏁 Script executed:

#!/bin/bash
set -euo pipefail

f=src/main/java/com/example/scoi/domain/websocket/handler/UpbitTickerHandler.java
wc -l "$f"
cat -n "$f" | sed -n '1,220p'

Repository: UMCSCOI/Backend

Length of output: 4756


중복 연결을 막는 가드가 필요합니다.

connectWithRetry()가 재시도되는 동안 이전 execute(...)가 늦게 성공하면 afterConnectionEstablished()가 다시 호출되고, 지금은 기존 currentSession을 닫지 않은 채 새 세션으로 덮어씁니다. 그 결과 두 세션이 동시에 살아남아 /topic/ticker가 중복 전송될 수 있으니, 연결 성공 시 기존 세션을 정리하거나 handler에서 중복 세션을 거부해야 합니다.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/main/java/com/example/scoi/domain/websocket/WebsocketConnect.java` around
lines 47 - 63, Update the connection-success handling associated with
connectWithRetry and upbitTickerHandler so a newly established websocket cannot
coexist with the existing currentSession. When afterConnectionEstablished()
receives a new session, close and clear the previous currentSession before
replacing it, or reject the new session when one is already active; preserve a
single active session for /topic/ticker delivery.


@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
Expand Up @@ -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;

Expand All @@ -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")));
}

Expand All @@ -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);
Expand All @@ -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

Copy link
Copy Markdown

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

handleTransportError와 afterConnectionClosed가 DisconnectedEvent를 중복 발행합니다.

Spring 공식 문서에 따르면 afterConnectionClosed는 Invoked after the WebSocket connection has been closed by either side, or after a transport error has occurred. 즉 전송 오류 발생 시 handleTransportError 호출 이후에도 afterConnectionClosed가 항상 뒤따라 호출됩니다.

현재 두 메서드가 모두 DisconnectedEvent를 발행하므로, 오류로 인한 연결 종료 시 WebsocketConnect.onDisconnected()가 두 번 트리거되어 connectWithRetry()가 중복(비동기) 호출됩니다. currentSession은 마지막으로 성립된 연결로만 덮어써지므로, 먼저 열린 연결이 정리되지 않고 누수될 위험이 있습니다.

🔧 제안: 중복 이벤트 발행 방지
     `@Override`
     public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
         log.error("[ Websocket ]: 웹소켓 에러 발생: {}", exception.getMessage());
-        eventPublisher.publishEvent(new DisconnectedEvent());
+        // afterConnectionClosed가 전송 오류 이후에도 항상 호출되므로 여기서는 이벤트를 발행하지 않음
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@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());
}
`@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());
// afterConnectionClosed가 전송 오류 이후에도 항상 호출되므로 여기서는 이벤트를 발행하지 않음
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@src/main/java/com/example/scoi/domain/websocket/handler/UpbitTickerHandler.java`
around lines 69 - 80, Prevent duplicate DisconnectedEvent publication in
UpbitTickerHandler by making handleTransportError only log the transport failure
and leaving event publication to afterConnectionClosed. Preserve the existing
disconnection event behavior for normal closures and ensure each connection
termination triggers one event.


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());
}
}
}
}
Loading
Loading