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

Fix async connection leak and co #72

Merged
merged 3 commits into from
Dec 4, 2024
Merged

Fix async connection leak and co #72

merged 3 commits into from
Dec 4, 2024

Conversation

barakb
Copy link
Contributor

@barakb barakb commented Dec 1, 2024

  • Fix connection leak on async connection when there is connection down
  • Fix compilation warnings "warning: elided lifetime has a name"
  • Update version in readme

Summary by CodeRabbit

  • New Features

    • Updated version of the FalkorDB Rust client from 0.1.8 to 0.1.9, reflecting changes in installation instructions and feature specifications.
    • Improved readability of code examples in the documentation.
  • Bug Fixes

    • Enhanced connection management in asynchronous command execution to ensure connections are returned to the pool upon errors.
  • Documentation

    • Clarified API return types with explicit lifetime parameters for better type safety and clarity.

- Fix compilation warnings "warning: elided lifetime has a name"
- Update version in readme
Copy link

coderabbitai bot commented Dec 1, 2024

Walkthrough

The pull request introduces several changes to the FalkorDB Rust client, primarily focusing on updates to the README.md file to reflect a version increment from 0.1.8 to 0.1.9 across various sections. Additionally, it enhances the formatting of Rust code examples for better readability. In the source code, modifications are made to the BorrowedAsyncConnection struct to improve connection management during command execution, and several methods in the SyncGraph and AsyncGraph structs are updated to include lifetime parameters in their return types, enhancing type safety.

Changes

File Path Change Summary
README.md Version updated from 0.1.8 to 0.1.9 in multiple sections, including installation instructions and feature specifications. Formatting improvements made to Rust code examples for better readability.
src/connection/asynchronous.rs Updated execute_command method in BorrowedAsyncConnection to spawn an asynchronous task for returning the connection to the pool on command execution errors and after obtaining results.
src/graph/blocking.rs Method signatures in SyncGraph updated to include lifetime parameters for profile, explain, ro_query, call_procedure, and call_procedure_ro, enhancing clarity and type safety.
src/graph/asynchronous.rs Method signatures in AsyncGraph updated to include lifetime parameters for profile, explain, ro_query, call_procedure, and call_procedure_ro, improving type safety and clarity in asynchronous contexts.

Possibly related PRs

Suggested reviewers

  • gkorland
  • AviAvni

🐰 In the garden of code, we hop with glee,
Version numbers rise, as bright as can be!
With formatting neat, and lifetimes in sight,
FalkorDB shines, a true delight!
So let’s code away, with joy in our hearts,
For every change made, a new journey starts! 🌟


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7dfe370 and 7385bb4.

📒 Files selected for processing (1)
  • README.md (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • README.md

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 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

🧹 Outside diff range and nitpick comments (1)
src/connection/asynchronous.rs (1)

119-119: Consider handling potential errors in the spawned task.

While spawning a task to return the connection to the pool is a good fix for the connection leak, the error from return_to_pool() is silently ignored. Consider logging the error if the return fails.

-tokio::spawn(async { self.return_to_pool().await });
+tokio::spawn(async {
+    if let Err(e) = self.return_to_pool().await {
+        tracing::error!("Failed to return connection to pool: {}", e);
+    }
+});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 96d57d7 and b4746ad.

📒 Files selected for processing (3)
  • README.md (6 hunks)
  • src/connection/asynchronous.rs (1 hunks)
  • src/graph/blocking.rs (5 hunks)
🔇 Additional comments (2)
README.md (1)

24-24: LGTM! Version updates are consistent.

The version has been correctly updated from 0.1.8 to 0.1.9 across all feature combinations in the installation instructions.

Also applies to: 72-72, 126-126, 130-130, 136-136, 140-140, 149-149

src/graph/blocking.rs (1)

113-113: LGTM! Lifetime parameters correctly added.

The addition of explicit lifetime parameters to the return types improves type safety and addresses the compilation warnings about elided lifetimes.

Let's verify that all similar methods have been updated:

Also applies to: 128-128, 159-159, 175-175, 191-191

✅ Verification successful

LGTM! All lifetime parameters are correctly added and consistent

After reviewing the file content, I can confirm that all QueryBuilder return types have been properly updated with lifetime parameters where needed. The changes are consistent across all methods including:

  • profile (line 113)
  • explain (line 128)
  • ro_query (line 159)
  • call_procedure (line 175)
  • call_procedure_ro (line 191)

The lifetime parameters are correctly propagated through the return types and match the input parameters, ensuring proper lifetime tracking.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining methods that might need lifetime parameters

# Search for methods that might still have elided lifetimes
ast-grep --pattern 'fn $name<$_>($_: &$_) -> QueryBuilder<$ret, $_, $_>'

Length of output: 74


Script:

#!/bin/bash
# Let's try a more specific pattern to find QueryBuilder return types
ast-grep --pattern 'fn $_($_) -> QueryBuilder<$_, $_, $_>'

# Also search for the specific file content to verify the changes
cat src/graph/blocking.rs

Length of output: 21311

Copy link

codecov bot commented Dec 1, 2024

Codecov Report

Attention: Patch coverage is 36.36364% with 7 lines in your changes missing coverage. Please review.

Project coverage is 85.11%. Comparing base (96d57d7) to head (7385bb4).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/graph/asynchronous.rs 40.00% 3 Missing ⚠️
src/graph/blocking.rs 40.00% 3 Missing ⚠️
src/connection/asynchronous.rs 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #72      +/-   ##
==========================================
+ Coverage   84.93%   85.11%   +0.18%     
==========================================
  Files          28       28              
  Lines        3909     3910       +1     
  Branches     3909     3910       +1     
==========================================
+ Hits         3320     3328       +8     
+ Misses        399      390       -9     
- Partials      190      192       +2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@barakb barakb requested a review from AviAvni December 1, 2024 13:31
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 (2)
src/graph/asynchronous.rs (2)

Line range hint 38-47: Consider enhancing error handling for connection failures

While the connection borrowing logic is sound, consider adding specific error handling for connection failures to improve reliability. This could help prevent connection leaks when errors occur.

Example enhancement:

 async fn execute_command(
     &self,
     command: &str,
     subcommand: Option<&str>,
     params: Option<&[&str]>,
 ) -> FalkorResult<redis::Value> {
-    self.client
-        .borrow_connection(self.client.clone())
-        .await?
-        .execute_command(Some(self.graph_name.as_str()), command, subcommand, params)
-        .await
+    let connection = match self.client.borrow_connection(self.client.clone()).await {
+        Ok(conn) => conn,
+        Err(e) => {
+            tracing::error!("Failed to borrow connection: {}", e);
+            return Err(e);
+        }
+    };
+    connection
+        .execute_command(Some(self.graph_name.as_str()), command, subcommand, params)
+        .await
}

Line range hint 347-485: Add test coverage for connection failure scenarios

The test suite is comprehensive for successful operations, but consider adding tests for connection failure scenarios to ensure proper handling of connection leaks mentioned in the PR objectives.

Example test case:

#[tokio::test(flavor = "multi_thread")]
async fn test_connection_failure_handling() {
    let mut graph = create_async_test_client().await.select_graph("test_connection_failure");
    
    // Simulate connection failure (implementation depends on your test utilities)
    // For example, by stopping the database or using a mock client
    
    let result = graph.query("RETURN 1").execute().await;
    assert!(result.is_err());
    // Verify that resources are properly cleaned up
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b4746ad and 7dfe370.

📒 Files selected for processing (1)
  • src/graph/asynchronous.rs (5 hunks)
🔇 Additional comments (1)
src/graph/asynchronous.rs (1)

119-119: LGTM! Improved lifetime management in method signatures

The explicit lifetime parameters in the QueryBuilder return types enhance type safety and help prevent potential memory issues by ensuring proper lifetime tracking of borrowed references.

Also applies to: 134-134, 165-165, 181-181, 197-197

@barakb barakb merged commit c79d7a7 into main Dec 4, 2024
8 of 9 checks passed
@barakb barakb deleted the async_connection_leak branch December 4, 2024 12:39
@github-actions github-actions bot mentioned this pull request Dec 4, 2024
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.

2 participants