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

Refactor exchange rate caching #370

Merged
merged 1 commit into from
Dec 4, 2024
Merged

Conversation

gcomte
Copy link
Owner

@gcomte gcomte commented Dec 4, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new dependency for improved functionality.
  • Bug Fixes

    • Enhanced safety and concurrency in exchange rate management by replacing unsafe mutable state with a thread-safe locking mechanism.

These updates ensure a more reliable and secure experience when accessing exchange rates.

Copy link

coderabbitai bot commented Dec 4, 2024

Walkthrough

The changes in this pull request involve updates to the Cargo.toml and src/currency/fiat.rs files of the bitcoinvert project. A new dependency, lazy_static, has been added to Cargo.toml to facilitate safe concurrent access. In fiat.rs, the management of the EXCHANGE_RATE_PROVIDER variable has been modified from a static mutable variable to a thread-safe Mutex wrapped in a lazy_static! macro. This change enhances safety by preventing potential data races associated with concurrent access.

Changes

File Change Summary
Cargo.toml Added new dependency: lazy_static = "1.5.0"
src/currency/fiat.rs Replaced static mutable variable EXCHANGE_RATE_PROVIDER with lazy_static! and Mutex for safety.

Poem

In the code where rabbits play,
A new friend joins us today!
With lazy_static by our side,
Safe and sound, we now can glide.
No more worries, no more fright,
Our EXCHANGE_RATE shines so bright! 🐇✨


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

🧹 Outside diff range and nitpick comments (1)
src/currency/fiat.rs (1)

11-17: Consider using once_cell instead of lazy_static for lazy initialization

While lazy_static provides lazy initialization, the once_cell crate offers a more modern and flexible approach with OnceCell and Lazy. Since your rust-version is "1.61.0", you can use the external once_cell crate, which provides similar functionality without macros and can improve readability.

To refactor using once_cell, first add it to your dependencies in Cargo.toml:

+ once_cell = "1.18.0"

Then, update your imports and replace the lazy_static! block:

-use lazy_static::lazy_static;
+use once_cell::sync::Lazy;

-lazy_static! {
-    static ref EXCHANGE_RATE_PROVIDER: Mutex<ExchangeRateProvider<blockchain_info_consumer::ApiConsumer>> =
-        Mutex::new(ExchangeRateProvider {
-            data_source: blockchain_info_consumer::ApiConsumer,
-            data: None,
-        });
-}
+static EXCHANGE_RATE_PROVIDER: Lazy<Mutex<ExchangeRateProvider<blockchain_info_consumer::ApiConsumer>>> = Lazy::new(|| {
+    Mutex::new(ExchangeRateProvider {
+        data_source: blockchain_info_consumer::ApiConsumer,
+        data: None,
+    })
+});

This approach eliminates the need for a macro and aligns with modern Rust practices.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between b218f9c and 1894f2c.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • Cargo.toml (1 hunks)
  • src/currency/fiat.rs (3 hunks)
🔇 Additional comments (2)
src/currency/fiat.rs (1)

1-2: Appropriate imports added for thread-safe synchronization

The imports of Mutex and lazy_static are necessary for implementing thread-safe access to shared resources and lazy initialization.

Cargo.toml (1)

30-30: ⚠️ Potential issue

Verify the version of lazy_static dependency

The specified version 1.5.0 for lazy_static may not exist. As of October 2023, the latest version available on crates.io is 1.4.0. Using a non-existent version will cause dependency resolution errors.

Please verify and update the version accordingly. You can check the latest version with the following command:

Alternatively, consider replacing lazy_static with once_cell as suggested earlier.

Comment on lines 55 to 59
EXCHANGE_RATE_PROVIDER
.lock()
.expect("Failed to lock EXCHANGE_RATE_PROVIDER")
.btc_value(self)

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Handle potential mutex poisoning to prevent unexpected panics

Using .expect("Failed to lock EXCHANGE_RATE_PROVIDER") will cause the program to panic if the mutex is poisoned (e.g., if another thread panicked while holding the lock). In a production environment, it's better to handle this case gracefully.

Consider handling the PoisonError by recovering or propagating an appropriate error:

-        EXCHANGE_RATE_PROVIDER
-            .lock()
-            .expect("Failed to lock EXCHANGE_RATE_PROVIDER")
-            .btc_value(self)
+        match EXCHANGE_RATE_PROVIDER.lock() {
+            Ok(provider) => provider.btc_value(self),
+            Err(poisoned) => {
+                // Handle the poisoned mutex, possibly by recovering the data
+                // or logging the error and returning a default value
+                eprintln!("Mutex poisoned: {}", poisoned);
+                // Example: Continue using the poisoned mutex
+                poisoned.into_inner().btc_value(self)
+            }
+        }

Alternatively, you might consider using RwLock if read operations are more frequent than writes, which can improve concurrency performance.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
EXCHANGE_RATE_PROVIDER
.lock()
.expect("Failed to lock EXCHANGE_RATE_PROVIDER")
.btc_value(self)
match EXCHANGE_RATE_PROVIDER.lock() {
Ok(provider) => provider.btc_value(self),
Err(poisoned) => {
// Handle the poisoned mutex, possibly by recovering the data
// or logging the error and returning a default value
eprintln!("Mutex poisoned: {}", poisoned);
// Example: Continue using the poisoned mutex
poisoned.into_inner().btc_value(self)
}
}

@gcomte gcomte force-pushed the refactor/exchange-rate-caching branch from 1894f2c to 7a46877 Compare December 4, 2024 13:18
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/currency/fiat.rs (2)

11-17: Add documentation for thread-safety guarantees

While the implementation using lazy_static! and Mutex is correct, it would be beneficial to document the thread-safety guarantees and usage patterns.

Consider adding documentation like this:

 // Static to have an easy way of caching the exchange rates.
+// Thread-safe singleton implementation using Mutex to ensure
+// safe concurrent access to exchange rates across multiple threads.
+// The lazy_static ensures one-time initialization when first accessed.
 lazy_static! {
     static ref EXCHANGE_RATE_PROVIDER: Mutex<ExchangeRateProvider<blockchain_info_consumer::ApiConsumer>> =

Line range hint 87-102: Add concurrent access tests

The current test only verifies caching behavior but not thread-safety. Given this refactoring focuses on thread-safe access, consider adding concurrent tests.

Example test to add:

#[test]
fn test_concurrent_access() {
    use std::thread;
    
    let handles: Vec<_> = (0..10)
        .map(|_| {
            thread::spawn(|| {
                // Access from multiple threads
                let btc_value = Fiat::USD.btc_value();
                assert!(btc_value > 0.0);
            })
        })
        .collect();

    // Ensure all threads complete successfully
    handles.into_iter().for_each(|h| h.join().unwrap());
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 1894f2c and 7a46877.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • Cargo.toml (1 hunks)
  • src/currency/fiat.rs (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Cargo.toml
🔇 Additional comments (2)
src/currency/fiat.rs (2)

2-2: LGTM! Appropriate imports added for thread-safe implementation

The new imports for lazy_static and Mutex are correctly added and follow Rust's import conventions.

Also applies to: 4-4


54-57: ⚠️ Potential issue

Improve error handling for mutex lock operations

The current implementation using expect() could cause panics in production. This issue was previously raised and remains valid.

As mentioned in the previous review, consider handling potential mutex poisoning:

-        EXCHANGE_RATE_PROVIDER
-            .lock()
-            .expect("Failed to lock EXCHANGE_RATE_PROVIDER")
-            .btc_value(self)
+        match EXCHANGE_RATE_PROVIDER.lock() {
+            Ok(provider) => provider.btc_value(self),
+            Err(poisoned) => {
+                // Log the error and recover the inner value
+                log::error!("Exchange rate provider mutex poisoned: {}", poisoned);
+                poisoned.into_inner().btc_value(self)
+            }
+        }

Additionally, consider adding error propagation to allow callers to handle failures:

fn btc_value(&self) -> Result<f64, Box<dyn std::error::Error>> {
    let provider = EXCHANGE_RATE_PROVIDER.lock()
        .map_err(|e| format!("Failed to acquire exchange rate lock: {}", e))?;
    Ok(provider.btc_value(self))
}

@gcomte gcomte merged commit 155c0b1 into master Dec 4, 2024
7 checks passed
@gcomte gcomte deleted the refactor/exchange-rate-caching branch December 4, 2024 13:25
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.

1 participant