Skip to content

Conversation

@kwon204
Copy link
Contributor

@kwon204 kwon204 commented Apr 7, 2025

#️⃣ 연관된 이슈>

📝 작업 내용> 이번 PR에서 작업한 내용을 간략히 설명해주세요(이미지 첨부 가능)

  • 논의 탈퇴 기능을 구현했습니다.
  • DiscussionParticipant DB에서 삭제 + 비트맵 데이터를 false로 설정
  • 새로 들어온 사용자에게 Offset 부여 방식을 수정하였습니다.
    • Max(Offset) + 1 => List 에서 아직 할당 받지 않은 Offset
  • 논의 참여, 삭제에서 발생하는 동시성 이슈
    • 비관적 락 + 행 잠금 방식을 사용해서 특정 Discussion에 대해서 잠금을 걸었습니다.
    • 논의 참여, 탈퇴 로직의 트랜잭션이 겹치지 않게 하였습니다.

🙏 여기는 꼭 봐주세요! > 리뷰어가 특별히 봐주었으면 하는 부분이 있다면 작성해주세요

Summary by CodeRabbit

  • New Features

    • Users can now exit discussions seamlessly, with their participation updated accurately.
    • The process for joining discussions has been enhanced with more robust participant allocation and improved conflict prevention.
    • Overall discussion state management has been optimized to reliably reflect the current conversation participants.
    • New methods allow for the deletion of discussion participants and improved retrieval of discussion offsets.
  • Bug Fixes

    • Enhanced error handling for discussion retrieval to prevent issues when discussions are not found.
  • Tests

    • Added tests to verify the functionality of deleting user bits from discussions and updated existing tests to reflect changes in discussion retrieval methods.

@kwon204 kwon204 added the 🛠️ BE Backend label Apr 7, 2025
@kwon204 kwon204 added this to the 😉 9차 스프린트 milestone Apr 7, 2025
@kwon204 kwon204 self-assigned this Apr 7, 2025
@kwon204 kwon204 requested a review from efdao as a code owner April 7, 2025 01:59
@coderabbitai
Copy link

coderabbitai bot commented Apr 7, 2025

Walkthrough

This pull request introduces several new methods and modifications across repository, service, and test classes to improve discussion participant management. The changes add deletion and offset-retrieval methods in the participant repository, update participant addition logic in the service layer, and implement a new exit discussion flow that leverages pessimistic locking. Furthermore, a new Redis method is introduced for bitmap manipulation, along with corresponding tests to validate the changes.

Changes

File(s) Change Summary
backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantRepository.java Added deleteByDiscussionIdAndUserId (deletes participant by discussion and user IDs) and findOffsetsByDiscussionId (retrieves user offsets for a discussion).
backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantService.java Modified addDiscussionParticipant to use a list of offsets and added deleteDiscussionParticipant for participant removal.
backend/src/main/java/endolphin/backend/domain/discussion/DiscussionRepository.java Added findByIdForUpdate method to fetch a discussion with a pessimistic write lock.
backend/src/main/java/endolphin/backend/domain/discussion/DiscussionService.java Updated joinDiscussion to use the new locking retrieval and added exitDiscussion to handle a user exiting a discussion.
backend/src/main/java/endolphin/backend/global/redis/DiscussionBitmapService.java Introduced deleteUsersFromDiscussion to clear specific bit settings in Redis using pipelined operations.
Test Files (DiscussionParticipantServiceTest, DiscussionServiceTest, DiscussionBitmapServiceTest) Adjusted and added tests to accommodate changes in offset handling, discussion locking, participant deletion, and Redis bitmap updates.

Sequence Diagram(s)

Join Discussion Flow

sequenceDiagram
    participant C as Client
    participant DS as DiscussionService
    participant DR as DiscussionRepository
    participant DPS as DiscussionParticipantService
    C->>DS: joinDiscussion(discussionId, request)
    DS->>DR: findByIdForUpdate(discussionId)
    DR-->>DS: Discussion entity
    DS->>DPS: addDiscussionParticipant(discussion, user)
    DPS-->>DS: Assigned offset
    DS-->>C: JoinDiscussionResponse
Loading

Exit Discussion Flow

sequenceDiagram
    participant C as Client
    participant DS as DiscussionService
    participant DR as DiscussionRepository
    participant DPS as DiscussionParticipantService
    participant DBS as DiscussionBitmapService
    C->>DS: exitDiscussion(discussionId, userId)
    DS->>DR: findByIdForUpdate(discussionId)
    DR-->>DS: Discussion entity
    DS->>DPS: getDiscussionParticipantOffset(discussionId, userId)
    DPS-->>DS: Participant offset
    DS->>DBS: deleteUsersFromDiscussion(discussionId, offset)
    DBS-->>DS: Acknowledgement
    DS->>DPS: deleteDiscussionParticipant(discussionId, userId)
    DPS-->>DS: Deletion acknowledgement
    DS-->>C: Exit confirmation
Loading

Possibly related PRs

Suggested reviewers

  • efdao

Poem

Oh, I’m a rabbit with a hop in my code,
Celebrating new methods that smoothly unload,
Bits and locks dancing in a rhythmic delight,
Discussions updated while I nibble through the night,
A little hop, a joyful skip, in code we trust—
Carrot-fueled changes, a bunny must adjust!
(_/) (•‿•) (> <) Enjoy the ride!

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

.isHost(false)
.userOffset(offset)
.build();
long offset = 0L;
Copy link
Collaborator

Choose a reason for hiding this comment

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

p3; offsets가 오름차순으로 정렬되어있는데 contains를 여러번 수행하지 않고 offsets에 대해 반복을 수행하며 찾는건 어떤가요?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

좋은 아이디어 감사합니다

Copy link
Contributor Author

Choose a reason for hiding this comment

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

수정하였습니다!

offsets에 대해서만 반복을 수행하도록 수정
@kwon204 kwon204 requested a review from efdao April 12, 2025 15:56
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 (1)
backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantService.java (1)

322-324: Consider adding validation before deletion

The new deleteDiscussionParticipant method directly calls the repository's delete method without first verifying if the participant exists. Consider adding validation to provide better feedback when attempting to delete a non-existent participant.

public void deleteDiscussionParticipant(Long discussionId, Long userId) {
+    // Validate if the participant exists before deletion
+    discussionParticipantRepository.findOffsetByDiscussionIdAndUserId(discussionId, userId)
+            .orElseThrow(() -> new ApiException(ErrorCode.DISCUSSION_PARTICIPANT_NOT_FOUND));
     discussionParticipantRepository.deleteByDiscussionIdAndUserId(discussionId, userId);
}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9ac256f and fbeb10d.

📒 Files selected for processing (1)
  • backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantService.java (3 hunks)
🔇 Additional comments (5)
backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantService.java (5)

45-48: Good optimization in participant verification

Changed from using a maximum offset to retrieving a complete list of offsets, which allows for better reuse of previously assigned offsets. This approach efficiently handles cases where participants have left the discussion.


52-56: Efficient implementation of finding the first available offset

The algorithm correctly identifies the first available offset by iterating through the sorted list of existing offsets. This aligns with the previous review feedback about avoiding redundant contains checks.


58-65: Clean, simplified participant creation logic

The host determination is now more straightforward (checking if offset is 0), and the builder pattern for participant creation is clear and well-structured.


18-18:

Details

❓ Verification inconclusive

Verify the new import's usage in this class

Added import for DiscussionBitmapService, but I don't see any direct usage of this service in the current file. Is this needed for future functionality, or is it being used in one of the methods?


🏁 Script executed:

#!/bin/bash
# Check if DiscussionBitmapService is used elsewhere in this class
rg "discussionBitmapService" backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantService.java

Length of output: 120


Unused Import in DiscussionParticipantService Detected—Please Confirm Its Intent

After running a case-sensitive search, I found no references to the DiscussionBitmapService (or any variant in casing) in the file backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantService.java. This suggests that the newly added import is currently unused. Please verify whether it is reserved for future functionality or if it can be removed to keep the code clean.

  • File: backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantService.java
  • Concern: The import for DiscussionBitmapService does not appear to be utilized anywhere in this class.
  • Action: Confirm if this is an intentional placeholder for upcoming features. If not, consider removing the import to reduce unused dependencies.

322-324:

Details

❓ Verification inconclusive

Verify transaction handling for discussion withdrawal

The PR objectives mention implementing pessimistic locking for concurrency issues. I don't see any explicit locking mechanism in this method. Ensure that proper locking is implemented either at the repository level or in a higher-level service that calls this method.


🏁 Script executed:

#!/bin/bash
# Check if there's pessimistic locking implemented in the repository or related service
echo "Checking for pessimistic locking in repository methods:"
rg -A 3 "Lock|lock" backend/src/main/java/endolphin/backend/domain/discussion/DiscussionParticipantRepository.java

echo -e "\nChecking for transaction management with pessimistic locking in service layers:"
rg -A 3 "Pessimistic|PESSIMISTIC" backend/src/main/java/endolphin/backend/domain/discussion/

Length of output: 1400


Ensure Transactional Consistency for Discussion Withdrawal

The deletion method in DiscussionParticipantService (lines 322–324) currently does not introduce explicit locking. However, our investigation shows that pessimistic locking is applied in the discussion flow via the DiscussionRepository (specifically, the findByIdForUpdate method is annotated with @Lock(LockModeType.PESSIMISTIC_WRITE)). This indicates that the broader discussion withdrawal process is expected to enforce concurrency control at a higher level.

  • Confirm that any workflow invoking deleteDiscussionParticipant is executed within a transactional context that acquires the pessimistic lock (e.g., via a call to findByIdForUpdate).
  • If the deletion can occur independently (outside that transactional boundary), consider either:
    • Annotating the method (or its calling service) with @Transactional, or
    • Integrating explicit locking at the repository level for participant deletion.

Copy link
Collaborator

@efdao efdao left a comment

Choose a reason for hiding this comment

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

고생하셨습니다.

@kwon204 kwon204 merged commit deb89f7 into dev Apr 13, 2025
4 checks passed
@kwon204 kwon204 deleted the feature/be/exit-discussion branch April 13, 2025 02:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🛠️ BE Backend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants