Skip to content

Conversation

@sunohkim
Copy link
Collaborator

@sunohkim sunohkim commented Feb 20, 2025

[BE] 질문 체크 기능 개선

#️⃣ 연관된 이슈

#182

📝 작업 내용

질문 체크 과정에서 발생한 트랜잭션 이슈 해결

  • 질문 체크 시 DB를 조회하고 저장하는 과정을 하나의 트랜잭션으로 처리하도록 수정
    기타 실시간 수업 중 SSE 통신을 포함하는 API에 대한 트랜잭션 이슈 해결
  • DB 조회 및 업데이트를 하나의 트랜잭션으로 처리

💬 리뷰 요구사항(선택)

Summary by CodeRabbit

  • New Features

    • Introduced enhanced question management endpoints that allow students to submit new queries and check their status.
    • Added a dedicated request handling service to increment course-related request counts reliably.
  • Refactor

    • Streamlined the logic for processing questions and requests, reducing redundant validations.
    • Improved error handling and transactional integrity to boost overall system responsiveness.

@sunohkim sunohkim added 🐞 Fix 버그 수정 (기능 오류 및 예외 처리 등) 🌱 BE 백엔드 관련 labels Feb 20, 2025
@sunohkim sunohkim self-assigned this Feb 20, 2025
@coderabbitai
Copy link

coderabbitai bot commented Feb 20, 2025

Walkthrough

This pull request refactors the question and request handling logic. In the question domain, service methods have been modified to delegate validations and state updates to dedicated methods, with redundant private methods removed. In the request domain, a new service class has been introduced and transaction management added to repository operations. Controller methods have been updated to simplify parameter handling, and dependencies have been refactored to shift responsibilities across services.

Changes

File(s) Change Summary
.../domain/question/ProfessorQuestionService.java
.../domain/question/QuestionRepository.java
.../domain/question/QuestionService.java
.../domain/question/StudentQuestionController.java
.../domain/question/StudentQuestionService.java
Question Domain: In ProfessorQuestionService, the sendQuestionCheck method now delegates fetching and validation of questions to questionService.checkQuestion, and removed private methods getQuestion and checkIfOpen. In QuestionRepository, the updateQuestion method was removed. In QuestionService, the save method was replaced by checkQuestion and saveQuestion along with new private helpers. In StudentQuestionController and StudentQuestionService, method signatures were updated by removing studentId and delegating logic to QuestionService.
.../domain/request/RequestRepository.java
.../domain/request/RequestService.java
.../domain/request/StudentRequestService.java
Request Domain: The incrementCount method in RequestRepository now has the @Transactional annotation. A new RequestService class has been added to handle request count increments with proper course validations. In StudentRequestService, dependencies on CourseRepository and RequestRepository were removed and replaced with RequestService, streamlining the request handling process.

Sequence Diagram(s)

sequenceDiagram
    participant SC as StudentQuestionController
    participant SS as StudentQuestionService
    participant QS as QuestionService
    participant DB as Database (QuestionRepository)
    
    SC->>SS: sendQuestionCheck(courseId, questionId)
    SS->>QS: checkQuestion(questionId)
    QS->>DB: Retrieve question & validate course status
    DB-->>QS: Return Question
    QS-->>SS: Return updated Question
    SS-->>SC: Complete operation
Loading
sequenceDiagram
    participant SR as StudentRequestService
    participant RS as RequestService
    participant CR as CourseRepository
    participant DB as RequestRepository
    
    SR->>RS: sendRequest(requestPayload)
    RS->>CR: getCourse(courseId)
    CR-->>RS: Return Course
    RS->>RS: checkIfOpen(Course)
    RS->>DB: incrementCount(Course, type)
    DB-->>RS: Return updated count
    RS-->>SR: Acknowledge success
Loading

Possibly related PRs

  • [BE] 질문 체크 기능 구현 #188: Directly related to the modifications in the sendQuestionCheck method in both ProfessorQuestionService and StudentQuestionService, as both address question status checking and completion updates.

Suggested reviewers

  • uri010

Poem

I'm a code rabbit, hopping with delight,
Refactoring lines under the moonlight.
Out with old methods, in with new flair,
Bugs bounce away like carrots in the air!
With clean commits, I twirl and cheer 🐇!

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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. (Beta)
  • @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: 3

🧹 Nitpick comments (5)
back-end/reacton/src/main/java/com/softeer/reacton/domain/request/RequestRepository.java (1)

13-20: Good addition of transaction management!

The @transactional annotation ensures that the increment operation is executed atomically, preventing potential race conditions during concurrent updates. This aligns well with the PR's objective of improving transaction handling.

Note: Since this is a modifying query, the @transactional annotation is particularly important as it ensures:

  1. Atomic updates to prevent partial modifications
  2. Proper transaction boundaries for database consistency
  3. Automatic rollback on exceptions
back-end/reacton/src/main/java/com/softeer/reacton/domain/request/RequestService.java (2)

8-10: Consider aligning with Spring's standard transactional usage.

You currently use the jakarta.transaction.Transactional annotation. If your project relies primarily on Spring's transaction management, adopting org.springframework.transaction.annotation.Transactional throughout can enhance consistency and avoid confusion.

Also applies to: 13-13, 15-15


21-32: Review concurrency handling and fallback behavior.

Since this method increments a counter, concurrent invocations might cause race conditions if the underlying DB logic doesn’t handle locking. Also, if no existing request is found, the current implementation throws an exception rather than inserting a new record, which could be intentional or may warrant a reconsideration of the fallback behavior.

back-end/reacton/src/main/java/com/softeer/reacton/domain/question/QuestionService.java (1)

22-30: Potential concurrency consideration in checkQuestion method.

checkQuestion sets isComplete on the question within a transaction. If multiple calls attempt to check the same question concurrently, ensure consistency. A simple approach is optimistic locking or verifying isComplete is not already set.

back-end/reacton/src/main/java/com/softeer/reacton/domain/question/StudentQuestionController.java (1)

81-92: Update API documentation to reflect transaction behavior.

Since this PR focuses on improving transaction handling during question checking, consider adding a note about transaction behavior in the API documentation.

Add transaction-related details to the API documentation:

 @Operation(
         summary = "학생 질문 체크 전송",
         description = "학생이 교수에게 질문 체크를 전송합니다.",
+        description = "학생이 교수에게 질문 체크를 전송합니다. 모든 데이터베이스 작업은 단일 트랜잭션으로 처리됩니다.",
         responses = {
                 @ApiResponse(responseCode = "200", description = "성공적으로 전송했습니다."),
                 @ApiResponse(responseCode = "404", description = "수업을 찾을 수 없습니다."),
                 @ApiResponse(responseCode = "404", description = "질문을 찾을 수 없습니다."),
                 @ApiResponse(responseCode = "409", description = "아직 수업이 시작되지 않았습니다."),
                 @ApiResponse(responseCode = "500", description = "서버와의 연결에 실패했습니다.")
         }
 )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 23bef6c and 61e3ed8.

📒 Files selected for processing (8)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/question/ProfessorQuestionService.java (1 hunks)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/question/QuestionRepository.java (0 hunks)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/question/QuestionService.java (1 hunks)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/question/StudentQuestionController.java (1 hunks)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/question/StudentQuestionService.java (3 hunks)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/request/RequestRepository.java (1 hunks)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/request/RequestService.java (1 hunks)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/request/StudentRequestService.java (1 hunks)
💤 Files with no reviewable changes (1)
  • back-end/reacton/src/main/java/com/softeer/reacton/domain/question/QuestionRepository.java
🧰 Additional context used
🧠 Learnings (1)
back-end/reacton/src/main/java/com/softeer/reacton/domain/question/StudentQuestionService.java (1)
Learnt from: sunohkim
PR: softeer5th/Team3-PowerPenguin#174
File: back-end/reacton/src/main/java/com/softeer/reacton/domain/question/dto/QuestionSendRequest.java:0-0
Timestamp: 2025-02-19T08:11:33.101Z
Learning: QuestionSendRequest DTO requires validation: content must not be empty (@NotBlank) and must not exceed 1000 characters (@Size).
🔇 Additional comments (18)
back-end/reacton/src/main/java/com/softeer/reacton/domain/request/RequestRepository.java (1)

8-8: LGTM!

Clean addition of the required import for @transactional annotation.

back-end/reacton/src/main/java/com/softeer/reacton/domain/request/RequestService.java (4)

3-7: Looks good.

These imports appropriately reflect the new domain models and custom error codes, and no issues are apparent here.


18-19: Dependency injection approach is appropriate.

Using Lombok's @AllArgsConstructor with final fields is clean and ensures proper dependency injection without requiring boilerplate constructors.


34-37: No issues found in getCourse.

Implementing a straightforward lookup with a custom exception on absence follows best practices.


39-43: No issues found in checkIfOpen.

This concise method cleanly enforces the active-course requirement.

back-end/reacton/src/main/java/com/softeer/reacton/domain/request/StudentRequestService.java (1)

17-17: Looks good, but ensure proper testing of the new service dependency.

Replacing direct repository references with RequestService improves maintainability, but please confirm you have adequate unit tests covering this new dependency injection.

back-end/reacton/src/main/java/com/softeer/reacton/domain/question/ProfessorQuestionService.java (1)

21-21: Consider explicit error handling for exceptions.

checkQuestion may throw an exception if the question does not exist or the course is inactive. Ensure higher-level code gracefully handles these exceptions, returning meaningful error responses or logs for debugging.

back-end/reacton/src/main/java/com/softeer/reacton/domain/question/QuestionService.java (6)

3-7: Imports aligned with new functionalities.

These imports accurately reflect the new exception and domain references needed for Course and CourseErrorCode.


10-13: Good practice: logging enabled with @slf4j.

Enabling detailed debug logs is beneficial for monitoring question workflows, especially for debugging transaction issues.


18-18: Additional dependency injection recognized.

The injection of CourseRepository ensures that QuestionService can manage both question and course data.


47-50: Clear handling of non-existent questions.

Throwing a BaseException with a specific error code is a good practice to standardize error handling.


52-55: Consistent approach for missing course.

Similar to getQuestion, throwing a BaseException ensures consistent error messages if the course is not found.


57-60: Blocking inactive course usage.

Raising a BaseException for inactive courses enforces the rule that only active courses can be used.

back-end/reacton/src/main/java/com/softeer/reacton/domain/question/StudentQuestionService.java (4)

29-29: Integration with QuestionService recognized.

Delegating question handling to QuestionService enhances maintainability and consolidates logic for retrieving and saving questions.


48-50: Well-structured response building.

Constructing CourseQuestionResponse directly from the saved question is clear and concise, avoiding duplication of fields.


61-61: Method signature clarified.

The removal of studentId from method parameters simplifies the check flow, relying on internal lookups in QuestionService.


64-64: Reusing checkQuestion logic in StudentQuestionService.

This centralizes question validation and completion logic, reducing code duplication and risk of inconsistent behavior.

back-end/reacton/src/main/java/com/softeer/reacton/domain/question/StudentQuestionController.java (1)

100-100:

Details

❓ Verification inconclusive

LGTM! Architectural improvement in student identification.

The removal of studentId parameter from sendQuestionCheck call suggests a good architectural decision to handle student identification within the service layer, promoting better separation of concerns.

Let's verify that the service layer properly handles student identification:


🏁 Script executed:

#!/bin/bash
# Search for student identification handling in the service layer
ast-grep --pattern $'class StudentQuestionService {
  $$$
  sendQuestionCheck($$$) {
    $$$
  }
  $$$
}'

Length of output: 106


Let's try a broader search for the implementation of sendQuestionCheck in the service layer. This will help us verify if the service method now handles student identification internally. Please run the following script, which uses rg to search across Java files for references to sendQuestionCheck:

#!/bin/bash
# Search for occurrences of "sendQuestionCheck" in Java files to locate its implementation and review context.
rg "sendQuestionCheck" --type java

After getting the output from this command, we can assess whether the service layer properly integrates student identification internally or if further adjustments are needed. Please provide feedback on the output so we can finalize the review comment.

@softeer5th softeer5th deleted a comment from coderabbitai bot Feb 21, 2025
@softeer5th softeer5th deleted a comment from coderabbitai bot Feb 21, 2025
@softeer5th softeer5th deleted a comment from coderabbitai bot Feb 21, 2025
@sunohkim sunohkim requested a review from uri010 February 21, 2025 01:15
Copy link
Collaborator

@uri010 uri010 left a comment

Choose a reason for hiding this comment

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

리뷰한 내용이 잘 반영된 것 같습니다👍

@sunohkim sunohkim merged commit f95981c into dev Feb 23, 2025
2 checks passed
@sunohkim sunohkim deleted the fix/be/transaction branch February 23, 2025 12:37
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🌱 BE 백엔드 관련 🐞 Fix 버그 수정 (기능 오류 및 예외 처리 등)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants