Skip to content
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

Communication: Fix an issue when creating post in a private channel #9896

Conversation

PaRangger
Copy link
Contributor

@PaRangger PaRangger commented Nov 28, 2024

Checklist

General

Server

Motivation and Context

Currently, there is a rare exception being thrown when creating the first post in a one to one chat that looks like this:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: de.tum.cit.aet.artemis.communication.domain.conversation.Conversation.conversationParticipants: could not initialize proxy - no Session
...
at de.tum.cit.aet.artemis.communication.service.conversation.ConversationDTOService.getConversationParticipants(ConversationDTOService.java:261)
...

This happens due to the conversations persistence context being closed under certain circumstances. This causes a LazyInitializationException being thrown when trying to load conversation.getConversationParticipants(). More information about this issue can be found here.

Description

I surrounded the code with a try-catch-block that handles the exception being thrown. In this rare case the repository then re-queries the database to retrieve the conversation participant list.

Steps for Testing

Prerequisites:

  • 2 Students
  • 1 Course with communication enabled
  1. Log in to Artemis
  2. Navigate to course
  3. Navigate to the communication tab
  4. Create a private channel by clicking the + icon in the channel sidebar
  5. Write the first message in the private channel
  6. Observe if any errors occur
  7. If you have access, check the server logs and view if any LazyInitializationException is thrown

Testserver States

Note

These badges show the state of the test servers.
Green = Currently available, Red = Currently locked
Click on the badges to get to the test servers.







Review Progress

Performance Review

Code Review

  • Code Review 1
  • Code Review 2

Manual Tests

  • Test 1
  • Test 2

Test Coverage

TBD

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error handling for loading conversation participants, preventing errors when the persistence context is closed.
    • Improved robustness of data retrieval for conversation participants.
  • Refactor

    • Updated variable declaration for clarity regarding the initialization state of participants.

@PaRangger PaRangger added server Pull requests that update Java code. (Added Automatically!) small bugfix communication Pull requests that affect the corresponding module labels Nov 28, 2024
@PaRangger PaRangger self-assigned this Nov 28, 2024
@PaRangger PaRangger temporarily deployed to artemis-test2.artemis.cit.tum.de November 28, 2024 15:34 — with GitHub Actions Inactive
@PaRangger PaRangger temporarily deployed to artemis-test6.artemis.cit.tum.de November 28, 2024 15:42 — with GitHub Actions Inactive
@PaRangger PaRangger marked this pull request as ready for review November 28, 2024 15:47
@PaRangger PaRangger requested a review from a team as a code owner November 28, 2024 15:47
Copy link

coderabbitai bot commented Nov 28, 2024

Walkthrough

The ConversationDTOService class has been updated to improve error handling for lazy loading of conversation participants. A try-catch block was added to the getConversationParticipants method to manage LazyInitializationException, allowing the method to set participantsInitialized to false when the persistence context is closed. This change allows for re-fetching participants from the repository if they are not loaded. Additionally, the participantsInitialized variable's type was changed from var to boolean for clarity.

Changes

File Change Summary
src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/ConversationDTOService.java Modified getConversationParticipants method to include error handling for lazy loading and changed participantsInitialized from var to boolean.

Possibly related PRs

Suggested labels

ready to merge, component:Communication

Suggested reviewers

  • sachmii
  • HawKhiem
  • FelberMartin
  • edkaya
  • JohannesStoehr

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 pmd (7.7.0)
src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/ConversationDTOService.java

The following rules are missing or misspelled in your ruleset file category/vm/bestpractices.xml: BooleanInstantiation, DontImportJavaLang, DuplicateImports, EmptyFinallyBlock, EmptyIfStmt, EmptyInitializer, EmptyStatementBlock, EmptyStatementNotInLoop, EmptySwitchStatements, EmptySynchronizedBlock, EmptyTryBlock, EmptyWhileStmt, ExcessiveClassLength, ExcessiveMethodLength, ImportFromSamePackage, MissingBreakInSwitch, SimplifyBooleanAssertion. Please check your ruleset configuration.


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 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 or @coderabbitai title anywhere in the PR title to generate the title automatically.

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

🧹 Outside diff range and nitpick comments (1)
src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/ConversationDTOService.java (1)

262-269: Consider adding logging and metrics for better observability

The error handling logic correctly addresses the LazyInitializationException by falling back to repository query. However, for better monitoring and debugging:

  1. Consider logging the exception at DEBUG level
  2. Consider adding metrics to track fallback frequency
 try {
     participantsInitialized = Persistence.getPersistenceUtil().isLoaded(conversation, "conversationParticipants") && conversation.getConversationParticipants() != null
             && !conversation.getConversationParticipants().isEmpty();
 }
 catch (LazyInitializationException e) {
+    log.debug("Persistence context closed while checking conversation participants. Falling back to repository query.", e);
+    metricsRegistry.counter("conversation.participants.lazy_init_fallback").increment();
     // In case the conversation's persistence context was closed already, we need to re-fetch to avoid errors down the line
     participantsInitialized = false;
 }
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 4eaba4e and a691219.

📒 Files selected for processing (1)
  • src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/ConversationDTOService.java (2 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/ConversationDTOService.java (1)

Pattern src/main/java/**/*.java: naming:CamelCase; principles:{single_responsibility,small_methods,no_duplication}; db:{perf_queries,datetime_not_timestamp}; rest:{stateless,singleton,delegate_logic,http_only,minimal_dtos}; dtos:{java_records,no_entities,min_data,single_resp}; di:constructor_injection; kiss:simple_code; file_handling:os_indep_paths; practices:{least_access,avoid_transactions,code_reuse,static_member_ref,prefer_primitives}; sql:{param_annotation,uppercase,avoid_subqueries};java:avoid_star_imports

🔇 Additional comments (2)
src/main/java/de/tum/cit/aet/artemis/communication/service/conversation/ConversationDTOService.java (2)

12-12: LGTM: Required import for exception handling

The addition of LazyInitializationException import is necessary for the new error handling logic.


261-261: LGTM: Explicit type declaration improves clarity

Changed from var to boolean for better code readability and type safety.

Comment on lines +261 to +269
boolean participantsInitialized;
try {
participantsInitialized = Persistence.getPersistenceUtil().isLoaded(conversation, "conversationParticipants") && conversation.getConversationParticipants() != null
&& !conversation.getConversationParticipants().isEmpty();
}
catch (LazyInitializationException e) {
// In case the conversation's persistence context was closed already, we need to re-fetch to avoid errors down the line
participantsInitialized = false;
}
Copy link
Contributor

Choose a reason for hiding this comment

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

After some digging I get why this is necessary, but I still find it a bit weird to need to have try/catch if before there is an explicit check to prevent exactly that exception.
Under which circumstances does this trigger? Maybe it might make sense to fix the issue there?

Copy link
Member

Choose a reason for hiding this comment

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

I agree, both, the old and the new code do not look very good!

Copy link
Member

Choose a reason for hiding this comment

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

We use Hibernate.isInitialized(...) in some places. Would that help to improve the code?

Hibernate.isInitialized(conversation.getConversationParticipants())

@krusche krusche changed the title Communication: Fix exception being thrown when creating post in a private channel Communication: Fix an issue when creating post in a private channel Nov 28, 2024
Copy link

github-actions bot commented Dec 6, 2024

There hasn't been any activity on this pull request recently. Therefore, this pull request has been automatically marked as stale and will be closed if no further activity occurs within seven days. Thank you for your contributions.

@github-actions github-actions bot added the stale label Dec 6, 2024
@github-actions github-actions bot removed the stale label Dec 10, 2024
@PaRangger PaRangger closed this Dec 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bugfix communication Pull requests that affect the corresponding module server Pull requests that update Java code. (Added Automatically!) small
Projects
Status: Ready For Review
Status: Done
Development

Successfully merging this pull request may close these issues.

3 participants