Skip to content

fix: network chooser screen statuses#89

Merged
QuantumExplorer merged 10 commits into
v0.4-devfrom
fix/show-offline-core-when-disconnected
Nov 25, 2024
Merged

fix: network chooser screen statuses#89
QuantumExplorer merged 10 commits into
v0.4-devfrom
fix/show-offline-core-when-disconnected

Conversation

@pauldelucia
Copy link
Copy Markdown
Member

@pauldelucia pauldelucia commented Nov 24, 2024

  • Fixed: network statuses would never switch from Online to Offline unless the app restarts
  • Fixed: only the currently active network status would update automatically

Now we check both networks every 3 seconds while the screen is active.

Summary by CodeRabbit

  • New Features

    • Enhanced network status handling with simultaneous retrieval of chain locks from both mainnet and testnet.
    • Introduced a new mechanism for rechecking network status every three seconds.
  • Bug Fixes

    • Improved error handling and configuration loading for network tasks.
  • Refactor

    • Simplified state management in the network chooser screen by removing unnecessary fields and methods.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Nov 24, 2024

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The pull request introduces significant updates to the CoreTask and CoreItem enums in src/backend_task/core/mod.rs, including renaming and restructuring to handle multiple chain locks. The run_core_task method has been enhanced with improved error handling and logic for fetching chain locks from both mainnet and testnet. Additionally, the NetworkChooserScreen in src/ui/network_chooser_screen.rs has been refactored to simplify network status checks and improve the handling of task results related to chain locks.

Changes

File Path Change Summary
src/backend_task/core/mod.rs - Renamed CoreTask::GetBestChainLock to CoreTask::GetBestChainLocks.
- Updated CoreItem::ChainLock to CoreItem::ChainLocks(Option<ChainLock>, Option<ChainLock>).
- Enhanced run_core_task for error handling and fetching chain locks from mainnet and testnet.
src/ui/network_chooser_screen.rs - Removed status_checked field from NetworkChooserScreen.
- Removed check_core_status method.
- Updated display_task_result to handle BackendTaskSuccessResult::CoreItem(CoreItem::ChainLocks(...)).
- Modified network status checking logic for efficiency and clarity.
- Added display_message method.

Possibly related PRs

Suggested reviewers

  • QuantumExplorer

Poem

🐰 In the burrow, changes bloom,
Tasks now fetch with less gloom.
Chain locks dance from net to net,
Simplified checks, no more fret.
Hopping through code, we celebrate,
A smoother path, oh, isn’t it great! 🌟


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.

@pauldelucia pauldelucia changed the title fix: show offline status when core disconnects on network chooser screen fix: network chooser screen statuses Nov 25, 2024
@pauldelucia pauldelucia marked this pull request as ready for review November 25, 2024 04:10
@pauldelucia
Copy link
Copy Markdown
Member Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Nov 25, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown
Contributor

@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 (7)
src/backend_task/core/mod.rs (3)

53-74: Refactor duplicated code for fetching chain locks into a helper function

The code for fetching the best chain lock for mainnet and testnet is nearly identical. To improve maintainability and reduce code duplication, consider creating a helper function that encapsulates this logic.

Here’s how you might refactor the code:

Create a helper function:

fn get_best_chain_lock_for_network(
    network_config: &Option<NetworkConfig>,
    network: Network,
) -> Result<ChainLock, String> {
    if let Some(config) = network_config {
        let addr = format!("http://{}:{}", config.core_host, config.core_rpc_port);
        let client = Client::new(
            &addr,
            Auth::UserPass(
                config.core_rpc_user.to_string(),
                config.core_rpc_password.to_string(),
            ),
        )
        .map_err(|e| format!("Failed to create {:?} client: {}", network, e))?;
        client.get_best_chain_lock().map_err(|e| {
            format!(
                "Failed to get best chain lock for {:?}: {}",
                network,
                e.to_string()
            )
        })
    } else {
        Err(format!("{:?} config not found", network))
    }
}

Update the run_core_task method:

 CoreTask::GetBestChainLocks => {
     tracing::info!("Getting best chain locks for testnet and mainnet");

     // Load configs
     let config = match Config::load() {
         Ok(config) => config,
         Err(e) => {
             return Err(format!("Failed to load config: {}", e));
         }
     };

-    let maybe_mainnet_config = config.config_for_network(Network::Dash);
-    let maybe_testnet_config = config.config_for_network(Network::Testnet);
-
-    // Get mainnet best chainlock
-    let mainnet_result = if let Some(mainnet_config) = maybe_mainnet_config {
-        // [Mainnet fetching logic...]
-    } else {
-        Err("Mainnet config not found".to_string())
-    };
-
-    // Get testnet best chainlock
-    let testnet_result = if let Some(testnet_config) = maybe_testnet_config {
-        // [Testnet fetching logic...]
-    } else {
-        Err("Testnet config not found".to_string())
-    };
+    let mainnet_result = get_best_chain_lock_for_network(
+        &config.config_for_network(Network::Dash),
+        Network::Dash,
+    );
+    let testnet_result = get_best_chain_lock_for_network(
+        &config.config_for_network(Network::Testnet),
+        Network::Testnet,
+    );

     // Handle results
     match (mainnet_result, testnet_result) {
         (Ok(mainnet_chainlock), Ok(testnet_chainlock)) => {
             Ok(BackendTaskSuccessResult::CoreItem(CoreItem::ChainLocks(
                 Some(mainnet_chainlock),
                 Some(testnet_chainlock),
             )))
         }
         (Ok(mainnet_chainlock), Err(_)) => Ok(BackendTaskSuccessResult::CoreItem(
             CoreItem::ChainLocks(Some(mainnet_chainlock), None),
         )),
         (Err(_), Ok(testnet_chainlock)) => Ok(BackendTaskSuccessResult::CoreItem(
             CoreItem::ChainLocks(None, Some(testnet_chainlock)),
         )),
         (Err(_), Err(_)) => Err(
             "Failed to get best chain lock for both mainnet and testnet".to_string(),
         ),
     }
 }

This refactoring reduces code duplication and makes the codebase cleaner and easier to maintain.

Also applies to: 77-98


65-65: Include error details when failing to create mainnet client

Currently, the error message when failing to create the mainnet client does not include the specific error, which can make debugging more difficult. Including the error details will aid in troubleshooting.

Apply this diff to include the error details:

 let mainnet_client = Client::new(
     &mainnet_addr,
     Auth::UserPass(
         mainnet_config.core_rpc_user.to_string(),
         mainnet_config.core_rpc_password.to_string(),
     ),
 )
- .map_err(|_| "Failed to create mainnet client".to_string())?;
+ .map_err(|e| format!("Failed to create mainnet client: {}", e))?;

89-89: Include error details when failing to create testnet client

The error message when failing to create the testnet client omits the specific error, hindering effective debugging. Including the error details will facilitate troubleshooting.

Apply this diff to include the error details:

 let testnet_client = Client::new(
     &testnet_addr,
     Auth::UserPass(
         testnet_config.core_rpc_user.to_string(),
         testnet_config.core_rpc_password.to_string(),
     ),
 )
- .map_err(|_| "Failed to create testnet client".to_string())?;
+ .map_err(|e| format!("Failed to create testnet client: {}", e))?;
src/ui/network_chooser_screen.rs (4)

164-167: Consider defining status colors as constants for maintainability

Defining ONLINE_COLOR and OFFLINE_COLOR as constants improves readability and makes future changes easier.

Apply this diff to define the colors as constants:

+const ONLINE_COLOR: Color32 = Color32::from_rgb(0, 255, 0); // Green
+const OFFLINE_COLOR: Color32 = Color32::from_rgb(255, 0, 0); // Red

 fn render_network_row(&mut self, ui: &mut Ui, network: Network, name: &str) -> AppAction {
     // Check network status
     let is_working = self.check_network_status(network);
     let status_color = if is_working {
-        Color32::from_rgb(0, 255, 0) // Green if working
+        ONLINE_COLOR
     } else {
-        Color32::from_rgb(255, 0, 0) // Red if not working
+        OFFLINE_COLOR
     };

Line range hint 207-211: Refactor repeated time calculations into a helper method

The time calculation for self.recheck_time is repeated. Creating a helper method enhances code maintainability.

Suggested refactor:

fn schedule_recheck_in(&mut self, secs: u64) {
    self.recheck_time = Some(
        (SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards")
            + Duration::from_secs(secs))
        .as_millis() as u64,
    );
}

Replace the code with:

// Recheck in 1 second
self.schedule_recheck_in(1);

249-261: Simplify option matching by using is_some()

You can simplify the assignment of mainnet_core_status_online and testnet_core_status_online using Option::is_some().

Apply this diff to simplify the code:

             )) => {
-                match mainnet_chainlock {
-                    Some(_) => self.mainnet_core_status_online = true,
-                    None => self.mainnet_core_status_online = false,
-                }
+                self.mainnet_core_status_online = mainnet_chainlock.is_some();

-                match testnet_chainlock {
-                    Some(_) => self.testnet_core_status_online = true,
-                    None => self.testnet_core_status_online = false,
-                }
+                self.testnet_core_status_online = testnet_chainlock.is_some();
             }

285-300: Encapsulate recheck logic to improve readability

The recheck logic in the ui method can be encapsulated into a separate function to enhance readability and reduce complexity.

Suggested refactor:

fn handle_recheck(&mut self, action: &mut AppAction) {
    let recheck_interval = Duration::from_secs(3);
    if *action == AppAction::None {
        let current_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Time went backwards");
        if let Some(time) = self.recheck_time {
            if current_time.as_millis() as u64 >= time {
                *action = AppAction::BackendTask(BackendTask::CoreTask(CoreTask::GetBestChainLocks));
                self.recheck_time = Some((current_time + recheck_interval).as_millis() as u64);
            }
        } else {
            self.recheck_time = Some((current_time + recheck_interval).as_millis() as u64);
        }
    }
}

Then, in the ui method, replace the recheck logic with:

self.handle_recheck(&mut action);
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between f6ad81f and 84302bf.

📒 Files selected for processing (2)
  • src/backend_task/core/mod.rs (2 hunks)
  • src/ui/network_chooser_screen.rs (7 hunks)

Comment on lines +241 to +245
fn display_message(&mut self, message: &str, _message_type: super::MessageType) {
if message.contains("Failed to get best chain lock for both mainnet and testnet") {
self.mainnet_core_status_online = false;
self.testnet_core_status_online = false;
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid string matching for error handling

Relying on string matching in display_message is fragile. Consider using error types or codes for more robust error handling.

Propose defining a custom error type or variant and updating the method accordingly:

// Define a custom message type or error enum
enum Message {
    FailedToGetBestChainLock,
    // other variants...
}

fn display_message(&mut self, message: &Message, _message_type: super::MessageType) {
    match message {
        Message::FailedToGetBestChainLock => {
            self.mainnet_core_status_online = false;
            self.testnet_core_status_online = false;
        }
        // handle other messages...
    }
}

Copy link
Copy Markdown
Member

@QuantumExplorer QuantumExplorer left a comment

Choose a reason for hiding this comment

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

No, this is wrong, we don't want to get chain locks for both networks with that call, because if one network is offline you can't get the chain lock for the other network.

@pauldelucia
Copy link
Copy Markdown
Member Author

No, this is wrong, we don't want to get chain locks for both networks with that call, because if one network is offline you can't get the chain lock for the other network.

Yes you can

@QuantumExplorer QuantumExplorer merged commit 77759be into v0.4-dev Nov 25, 2024
@QuantumExplorer QuantumExplorer deleted the fix/show-offline-core-when-disconnected branch November 25, 2024 12:26
@coderabbitai coderabbitai Bot mentioned this pull request Nov 26, 2024
@coderabbitai coderabbitai Bot mentioned this pull request Feb 17, 2025
@coderabbitai coderabbitai Bot mentioned this pull request Apr 24, 2025
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