Skip to content

Conversation

@pauldelucia
Copy link
Member

@pauldelucia pauldelucia commented Nov 18, 2024

Retry querying contested resources and contenders up to 3 times when error message contains "try another server" or "contract not found when querying from value with contract info".

Now, all contested names and contenders are fetched by just clicking "refresh" once, and there are no error messages at the top.

Summary by CodeRabbit

  • New Features

    • Introduced retry mechanisms for fetching contested resources and vote contenders, enhancing error handling for transient issues.
  • Bug Fixes

    • Improved error message handling in the UI to prevent unnecessary alerts for specific errors.
  • Documentation

    • Updated method signatures to reflect changes in error handling logic.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Nov 18, 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 changes in this pull request enhance error handling in the query_dpns_contested_resources and query_dpns_vote_contenders methods by introducing a retry mechanism for transient errors. A maximum of three retries is allowed for specific error messages, improving robustness during resource fetching. Additionally, the display_message method in the UI is modified to filter out certain error messages to streamline user notifications. The overall control flow remains similar, but these adjustments increase the resilience and clarity of error handling across the application.

Changes

File Path Change Summary
src/backend_task/contested_names/query_dpns_contested_resources.rs Introduced a retry mechanism for fetching contested resources with a maximum of 3 retries for specific transient errors. Standardized error logging. Updated handling of start_at_value.
src/backend_task/contested_names/query_dpns_vote_contenders.rs Added a retry mechanism for fetching vote contenders, allowing up to 3 retries for specific errors. Restructured control flow with a loop for attempts. Method signature updated.
src/ui/dpns_contested_names_screen.rs Modified display_message to prevent displaying certain error messages, specifically those containing "try another server." Logic updated without changing method signature.

Possibly related PRs

  • feat: refresh identities #14: The changes in this PR introduce a retry mechanism in the query_dpns_vote_contenders method, which is similar to the retry logic added in the query_dpns_contested_resources method of the main PR.
  • feat: dpns subscreens #18: This PR modifies the DPNSContestedNamesScreen to handle different subscreens, which may relate to the overall error handling and resource querying logic in the main PR's context of contested resources.
  • feat: highlight button for active dpns subscreen #51: The modifications to the add_dpns_subscreen_chooser_panel function in this PR enhance the interaction with the application context, which is relevant to the changes made in the main PR regarding error handling and resource fetching.

Suggested reviewers

  • QuantumExplorer
  • ogabrielides

🐰 In the meadow, where bunnies play,
A retry mechanism brightens the day.
With each little hop, we fetch with cheer,
Filtering messages, we hold dear.
So let’s dance and twirl, with joy we’ll sing,
For error handling's a wonderful thing! 🌼


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 marked this pull request as ready for review November 18, 2024 09:00
@pauldelucia pauldelucia changed the base branch from master to v0.4-dev November 18, 2024 09:00
Copy link
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: 2

🧹 Outside diff range and nitpick comments (5)
src/ui/dpns_contested_names_screen.rs (1)

789-791: LGTM! Consider extracting the error message filter to a constant.

The implementation correctly filters out transient error messages containing "try another server", which aligns with the PR objectives. This prevents unnecessary error notifications while the system attempts to retry the operation.

Consider extracting the error message filter to a constant for better maintainability:

 impl DPNSContestedNamesScreen {
+    const FILTERED_ERROR_MESSAGES: [&'static str; 1] = ["try another server"];
+
     // ... other methods ...
 
     fn display_message(&mut self, message: &str, message_type: MessageType) {
-        if !message.contains("try another server") {
+        if !Self::FILTERED_ERROR_MESSAGES.iter().any(|&filter| message.contains(filter)) {
             self.error_message = Some((message.to_string(), message_type, Utc::now()));
         }
     }
src/backend_task/contested_names/query_dpns_vote_contenders.rs (3)

80-80: Consider adding a delay between retries

Currently, the loop retries immediately upon failure, which could lead to rapid successive retries and potential server overload. Adding a small delay between retries can help mitigate this issue and provide time for transient errors to resolve.

Insert the following line before continue; at line 80:

tokio::time::sleep(std::time::Duration::from_secs(1)).await;

47-86: Refactor retry logic into a reusable function

Since similar retry mechanisms are implemented in multiple methods, consider abstracting the retry logic into a reusable helper function. This will reduce code duplication and enhance maintainability.


62-63: Avoid logging errors multiple times

Errors are logged when fetching fails (tracing::error!("Error fetching contested resources: {}", e);) and again when maximum retries are reached. This may result in redundant log messages. Consider adjusting the logging to avoid duplicate entries.

src/backend_task/contested_names/query_dpns_contested_resources.rs (1)

Line range hint 41-115: Fix the retries counter to prevent an infinite loop

The retries counter is initialized inside the loop, causing it to reset to zero on each iteration. This means the condition retries > MAX_RETRIES will never be satisfied, potentially leading to an infinite loop if the error persists.

Apply this diff to move the retries counter initialization outside the loop:

         const MAX_RETRIES: usize = 3;
+        // Initialize retry counter
+        let mut retries = 0;
         let mut start_at_value = None;
-        // Initialize retry counter
-        let mut retries = 0;
         loop {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 95b676f and 42693b0.

📒 Files selected for processing (3)
  • src/backend_task/contested_names/query_dpns_contested_resources.rs (6 hunks)
  • src/backend_task/contested_names/query_dpns_vote_contenders.rs (1 hunks)
  • src/ui/dpns_contested_names_screen.rs (1 hunks)

)
{
retries += 1;
if retries > MAX_RETRIES {
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix off-by-one error in retries condition

The condition if retries > MAX_RETRIES may allow for one additional retry beyond the intended MAX_RETRIES. Since retries is incremented before the check and starts at 0, the condition should be if retries >= MAX_RETRIES to ensure the method retries exactly MAX_RETRIES times.

Apply this change:

- if retries > MAX_RETRIES {
+ if retries >= MAX_RETRIES {
📝 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
if retries > MAX_RETRIES {
if retries >= MAX_RETRIES {

Comment on lines 95 to 114
return Err(e);
}
}
format!("error fetching contested resources: {}", e)
})?;

if e.to_string().contains("try another server")
|| e.to_string().contains(
"contract not found when querying from value with contract info",
)
{
retries += 1;
if retries > MAX_RETRIES {
tracing::error!("Max retries reached for query: {}", e);
return Err(format!(
"Error fetching contested resources after retries: {}",
e
));
} else {
// Retry
continue;
}
} else {
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use specific error types instead of string matching for robust error handling

Matching errors using string comparisons like e.to_string().contains(...) is fragile and may break if error messages change. Consider matching on specific error types or creating custom error variants to make the error handling more robust.

Apply this diff to match on specific error variants:

-        if e.to_string().contains("try another server")
-            || e.to_string().contains(
-                "contract not found when querying from value with contract info",
-            )
+        if matches!(e,
+            dash_sdk::Error::NetworkError(_) | 
+            dash_sdk::Error::ContractNotFound(_)
+        )

This change assumes that dash_sdk::Error has specific variants for these error conditions.

Committable suggestion skipped: line range outside the PR's diff.

Copy link
Contributor

@ogabrielides ogabrielides left a comment

Choose a reason for hiding this comment

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

LGTM

Copy link
Contributor

@ogabrielides ogabrielides left a comment

Choose a reason for hiding this comment

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

rebase and fix conflicts. besides that LGTM

@pauldelucia pauldelucia force-pushed the fix/error-messages-in-dpns-screen branch from 42693b0 to 6c8f34c Compare November 19, 2024 12:57
@QuantumExplorer QuantumExplorer merged commit 68cdd20 into v0.4-dev Nov 19, 2024
1 check passed
@pauldelucia pauldelucia deleted the fix/error-messages-in-dpns-screen branch November 20, 2024 03:48
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.

4 participants