Skip to content

Conversation

@chat26666
Copy link
Collaborator

@chat26666 chat26666 commented Jun 23, 2025


작업 내용

  • scale out 환경에서 MQ 사용해서 메시지가 인스턴스끼리 잘 전달되도록 설정이 변경되었습니다.

코드 리뷰 전 확인 체크리스트

  • 불필요한 콘솔 로그, 주석 제거
  • 커밋 메시지 컨벤션 준수 (type : )
  • 기능 정상 동작 확인

Summary by CodeRabbit

  • 신규 기능

    • 웹소켓 STOMP 클라이언트에 5분 간격의 하트비트(heartbeat) 설정이 추가되었습니다.
    • 구독 시 영수증(receipt) 처리가 도입되어, 채팅방 입장 메시지가 영수증 수신 후 전송됩니다.
  • 버그 수정

    • 알림 구독 경로가 /user/queue/notifications에서 /user/queue/notification으로 수정되었습니다.
    • 중복된 구독이 제거되었습니다.
  • 개선 사항

    • 채팅방 목록 업데이트 및 정렬 로직이 일관성 있게 개선되었습니다.
    • 연결 및 메시지 처리 과정에서 오류 로깅이 추가되었습니다.
    • 사용자 대상 및 사용자 레지스트리 이벤트 브로드캐스트 설정이 추가되어 실시간 이벤트 처리 신뢰성이 향상되었습니다.
    • 연결 종료 시 예외 로그 레벨이 경고에서 정보로 낮아져 로그 관리가 개선되었습니다.

@coderabbitai
Copy link

coderabbitai bot commented Jun 23, 2025

Walkthrough

WebSocket 설정과 채팅 페이지 스크립트가 개선되었습니다. WebSocketConfig에서는 사용자 대상 및 레지스트리 이벤트 브로드캐스트 주제가 추가되었고, chat-page.html에서는 하트비트 설정, 구독 경로 수정, receipt 처리, 에러 핸들링 강화, 코드 구조 개선 등이 이루어졌습니다. 또한, WebSocketEventListener에서는 세션 연결 해제 이벤트 예외 로그 레벨이 경고에서 정보로 변경되었습니다.

Changes

파일/경로 변경 요약
src/main/java/org/ezcode/codetest/infrastructure/event/config/WebSocketConfig.java STOMP 브로커 릴레이에 사용자 대상 및 레지스트리 브로드캐스트 주제(setUserDestinationBroadcast, setUserRegistryBroadcast) 추가
src/main/resources/templates/chat-page.html 하트비트 설정 추가, 구독 경로 수정, receipt 및 에러 핸들링 강화, 코드 구조 개선, 중복 구독 제거 등
src/main/java/org/ezcode/codetest/infrastructure/event/listener/WebSocketEventListener.java SessionDisconnectEvent 예외 로그 레벨을 warn에서 info로 변경

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Browser
    participant WebSocketServer

    User->>Browser: 채팅 페이지 접속
    Browser->>WebSocketServer: STOMP 연결 (하트비트 설정 포함)
    WebSocketServer-->>Browser: 연결 성공/실패 응답
    Browser->>WebSocketServer: /user/queue/notification 등 구독 (receipt 포함)
    WebSocketServer-->>Browser: receipt 응답
    Browser->>WebSocketServer: /chat/enter 메시지 전송
    WebSocketServer-->>Browser: 채팅방 목록/메시지 등 이벤트 전달
    User->>Browser: 메시지 입력 및 전송
    Browser->>WebSocketServer: 메시지 전송
Loading

Suggested reviewers

  • pokerbearkr
  • thezz9
  • minjee2758

Poem

토끼가 톡톡, 하트비트로 똑똑
채팅방 알림도 한 곳에 모아
receipt 받고 방에 쏙!
에러도 척척, 구독도 깔끔
코드가 예뻐진 오늘 밤
채팅의 숲에 평화가 찾아왔네
🐇💬✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 80950d8 and ecbae8b.

📒 Files selected for processing (1)
  • src/main/java/org/ezcode/codetest/infrastructure/event/listener/WebSocketEventListener.java (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • src/main/java/org/ezcode/codetest/infrastructure/event/listener/WebSocketEventListener.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
src/main/java/org/ezcode/codetest/infrastructure/event/config/WebSocketConfig.java (1)

52-54: 사용자 대상과 레지스트리 브로드캐스트 토픽 분리를 고려하세요.

현재 setUserDestinationBroadcastsetUserRegistryBroadcast가 동일한 토픽("/topic/simp-user-registry")을 사용하고 있습니다. 스케일아웃 환경에서의 메시지 분리와 디버깅을 위해 서로 다른 토픽 사용을 고려해보세요.

 .setSystemPasscode(mqPassword)
-.setUserDestinationBroadcast("/topic/simp-user-registry")
-.setUserRegistryBroadcast("/topic/simp-user-registry");
+.setUserDestinationBroadcast("/topic/simp-user-destination")
+.setUserRegistryBroadcast("/topic/simp-user-registry");
src/main/resources/templates/chat-page.html (1)

319-343: 채팅방 전환 시 타이밍 개선을 고려하세요.

여러 setTimeout을 사용한 타이밍 제어보다는 Promise 기반 순차 처리나 상태 관리를 고려해보세요.

-setTimeout(() => {
-    chatSubscription = stompClient.subscribe(`/topic/chat/${nr}`, m => {
-        // ... 메시지 처리 로직
-    });
-    setTimeout(() => {
-        stompClient.send(`/chat/room/${nr}/enter`, {}, nr);
-    }, 100);
-}, 100);
+// Promise 기반 순차 처리 예시
+Promise.resolve()
+    .then(() => new Promise(resolve => {
+        chatSubscription = stompClient.subscribe(`/topic/chat/${nr}`, m => {
+            // ... 메시지 처리 로직
+        });
+        setTimeout(resolve, 100);
+    }))
+    .then(() => {
+        stompClient.send(`/chat/room/${nr}/enter`, {}, nr);
+    });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5132f8b and 80950d8.

📒 Files selected for processing (2)
  • src/main/java/org/ezcode/codetest/infrastructure/event/config/WebSocketConfig.java (1 hunks)
  • src/main/resources/templates/chat-page.html (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (6)
src/main/resources/templates/chat-page.html (6)

192-196: 하트비트 설정이 적절합니다.

5분(300,000ms) 간격의 하트비트 설정은 스케일아웃 환경에서 연결 상태 관리에 적합합니다. 클라이언트와 서버 간 연결 유지에 도움이 됩니다.


198-200: STOMP 연결 개선이 우수합니다.

헤더를 통한 하트비트 설정과 성공/에러 콜백 분리가 연결 안정성을 향상시킵니다.


226-233: 수신 확인 처리 로직이 훌륭합니다.

Receipt 기반 확인 후 입장 메시지를 전송하는 로직이 메시지 순서를 보장합니다. 스케일아웃 환경에서 중요한 개선사항입니다.


250-303: 채팅방 목록 관리 로직이 포괄적입니다.

다양한 이벤트 타입(CREATE, UPDATE, DELETE, GET)을 처리하고 오름차순 정렬을 유지하는 로직이 잘 구현되어 있습니다.


379-382: 에러 핸들링 추가가 좋습니다.

STOMP 연결 실패 시 에러 로깅이 디버깅에 도움이 됩니다.


205-211: 구독 토픽명 일관성 확인이 필요합니다.

/user/queue/notification/user/queue/notifications 두 토픽을 모두 구독하고 있습니다. 서버에서 실제로 두 토픽을 모두 사용하는지 확인이 필요합니다.

#!/bin/bash
# 서버 코드에서 notification 관련 토픽 사용 확인
rg -A 3 -B 3 "notification" --type java

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
src/main/resources/templates/chat-page.html (3)

205-211: 중복된 구독 제거 필요

/user/queue/notification/user/queue/notifications 두 가지 구독이 모두 존재합니다. 실제 사용되는 엔드포인트에 따라 하나는 제거해야 할 것 같습니다.

                stompClient.subscribe('/user/queue/notification', msg => {
                    console.log(msg);
                });

-                stompClient.subscribe('/user/queue/notifications', msg => {
-                    console.log(msg);
-                });

251-303: 채팅방 목록 업데이트 로직 개선

eventType별 처리 로직이 체계적으로 구성되었고, 각 이벤트 후 일관된 정렬을 유지하는 것이 좋습니다. 다만 코드 중복을 줄일 수 있습니다.

정렬 로직을 별도 함수로 분리하여 중복을 제거할 수 있습니다:

+                function sortRoomList() {
+                    const reordered = Array.from(roomListEl.children).sort((a, b) =>
+                        Number(a.dataset.roomId) - Number(b.dataset.roomId)
+                    );
+                    roomListEl.innerHTML = '';
+                    reordered.forEach(li => roomListEl.appendChild(li));
+                }

그리고 각 이벤트 처리 후 sortRoomList()를 호출하도록 변경하면 코드 중복을 줄일 수 있습니다.


378-382: 연결 에러 처리 개선

STOMP 연결 에러에 대한 기본적인 로깅이 추가되었습니다. 사용자에게 더 친화적인 에러 메시지 표시를 고려해볼 수 있습니다.

            error => {
-                console.error('STOMP 연결 에러', error);
+                console.error('STOMP 연결 에러', error);
+                alert('채팅 서버 연결에 실패했습니다. 페이지를 새로고침하여 다시 시도해주세요.');
            }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5132f8b and 80950d8.

📒 Files selected for processing (2)
  • src/main/java/org/ezcode/codetest/infrastructure/event/config/WebSocketConfig.java (1 hunks)
  • src/main/resources/templates/chat-page.html (1 hunks)
🔇 Additional comments (5)
src/main/java/org/ezcode/codetest/infrastructure/event/config/WebSocketConfig.java (1)

53-54: Scale-out 환경을 위한 적절한 설정 추가

사용자 대상 브로드캐스트와 사용자 레지스트리 브로드캐스트 설정이 올바르게 추가되었습니다. 이 설정들은 여러 인스턴스 간에 사용자별 메시지 라우팅을 가능하게 하여 scale-out 환경에서 WebSocket 통신이 정상적으로 작동하도록 합니다.

src/main/resources/templates/chat-page.html (4)

192-196: Heartbeat 설정으로 연결 안정성 향상

5분(300초) 간격의 heartbeat 설정이 클라이언트와 서버 양방향으로 적절히 구성되었습니다. 이는 장시간 연결 유지와 연결 상태 모니터링에 도움이 됩니다.


214-233: Receipt 처리를 통한 초기화 로직 개선

채팅방 목록 구독 후 receipt를 통해 입장 메시지를 전송하는 로직이 잘 구현되었습니다. 구독 완료를 확인한 후 다음 단계를 진행하는 것은 좋은 패턴입니다.


319-343: 비동기 처리를 위한 적절한 setTimeout 사용

구독, 메시지 처리, 방 입장 등에 적절한 지연시간을 두어 비동기 처리 순서를 보장한 것이 좋습니다. 특히 100ms 지연을 통해 메시지 처리 순서를 안정화한 것이 적절합니다.


355-377: 메시지 전송 후 로컬 표시 로직 검토 필요

메시지 전송 API 호출 후 응답 데이터로 메시지를 로컬에 표시하고 있습니다. 이는 WebSocket 브로드캐스트와 중복 표시를 일으킬 수 있습니다.

WebSocket 구독을 통해 자신이 보낸 메시지도 수신되는지 확인이 필요합니다. 만약 WebSocket으로 자신의 메시지도 수신된다면 여기서 로컬 표시는 중복일 수 있습니다.

#!/bin/bash
# 채팅 메시지 전송 API와 WebSocket 브로드캐스트 로직 확인
rg -A 10 -B 5 "room.*chat.*POST\|chat.*room.*enter" --type java

@chat26666 chat26666 merged commit 7a171a4 into dev Jun 24, 2025
2 checks passed
@chat26666 chat26666 deleted the feature/chat branch June 24, 2025 01:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants