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

feat(api-client-framework): add blockscout services related helper definitions #1204

Merged

Conversation

rimrakhimov
Copy link
Member

@rimrakhimov rimrakhimov commented Jan 22, 2025

Summary by CodeRabbit

  • New Features

    • Added optional Blockscout API client framework with configurable HTTP request handling
    • Introduced retry mechanism for API requests
    • Implemented health check functionality for API connections
  • Improvements

    • Enhanced API client configuration with flexible middleware support
    • Added support for optional API key and custom timeout settings

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Walkthrough

The pull request introduces a new optional feature for the API client framework, specifically targeting Blockscout services. A new blockscout feature is added to the Cargo.toml, which includes the reqwest-retry dependency. The changes involve creating a new Client struct with methods for making HTTP requests, performing health checks, and managing configuration settings. The implementation provides a flexible and configurable approach to interacting with API endpoints, with support for optional API keys, middleware, and request retry mechanisms. The new module is conditionally compiled and can be opted into by users of the library.

Possibly related PRs

Poem

🐰 A Rabbit's API Tale 🌐

With retry and grace, our client takes flight,
Blockscout endpoints dancing in digital light
Middleware woven, configurations neat
A framework that makes API calls a treat!
Hop, hop, request! 🚀


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
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

🧹 Nitpick comments (7)
libs/api-client-framework/src/blockscout/client.rs (3)

29-29: Correct the error message to refer to the correct client

The error message mentions "contracts-info client", which seems incorrect in this context. It should refer to "Blockscout client" to accurately reflect the service the client is connecting to.

Apply this diff to update the error message:

-                panic!("Cannot establish a connection with contracts-info client: {err}")
+                panic!("Cannot establish a connection with Blockscout client: {err}")

62-63: Rename _status field to status

The field _status in HealthCheckResponse is used and therefore should not have a leading underscore, which is typically reserved for unused fields or variables. Renaming it to status enhances code clarity and eliminates the need for the #[serde(rename = "status")] attribute.

Apply this diff to rename the field:

-    #[serde(rename = "status")]
-    pub _status: i32,
+    pub status: i32,

Ensure any references to _status are updated accordingly.


48-49: Correct indentation in documentation comment

The indentation in the documentation comment is inconsistent, which may affect readability and documentation generation tools.

Apply this diff to correct the indentation:

 /// As we don't have protobuf generated structures here (they are only available inside a service),
-    /// we have to imitate the service health endpoint.
+/// we have to imitate the service health endpoint.
libs/api-client-framework/src/blockscout/config.rs (3)

22-31: Ensure proper error handling in deserialize_api_key

The deserialize_api_key function correctly handles the conversion of the API key from a String to a HeaderValue. However, consider logging or providing more context in the error message to aid troubleshooting if deserialization fails.

Optionally, you can enhance the error handling as follows:

-        string
-            .map(|value| HeaderValue::from_str(&value))
-            .transpose()
-            .map_err(<D::Error as serde::de::Error>::custom)
+        match string {
+            Some(value) => HeaderValue::from_str(&value)
+                .map(Some)
+                .map_err(|e| D::Error::custom(format!("Invalid API key: {}", e))),
+            None => Ok(None),
+        }

33-61: Simplify Debug implementation for Config

Manually implementing Debug to skip the middlewares field is acceptable. Alternatively, the Debug implementation could be automatically derived using the #[derive(Debug)] attribute and annotating the middlewares field with #[debug(skip)] from the derivative crate.

[refactor_suggestion_good_to_HAVE]

If it's acceptable to introduce an additional dependency, consider using the derivative crate for a cleaner implementation.

use derivative::Derivative;

#[derive(Clone, Deserialize, Derivative)]
#[derivative(Debug)]
pub struct Config {
    pub url: url::Url,
    #[serde(default, deserialize_with = "deserialize_api_key")]
    pub api_key: Option<HeaderValue>,
    #[serde(default = "defaults::http_timeout")]
    pub http_timeout: Duration,
    #[serde(default)]
    pub probe_url: bool,
    #[serde(skip_deserializing)]
    #[derivative(Debug = "ignore")]
    pub middlewares: Vec<Arc<dyn Middleware>>,
}

99-102: Consider making http_timeout configurable at runtime

Allowing the http_timeout to be configurable can enhance flexibility, especially under varying network conditions. Ensure that this setting can be adjusted without requiring a recompilation of the application.

libs/api-client-framework/src/lib.rs (1)

6-7: Enhance module documentation.

Consider adding more context about what Blockscout is and when this module should be used.

 /// Blockscout services related structs.
 /// Contains config and client definitions to be used by blockscout-rs services.
+/// 
+/// Blockscout is a blockchain explorer that provides APIs for accessing blockchain data.
+/// This module provides client implementations for interacting with Blockscout services.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0cf48c3 and 1cf3484.

📒 Files selected for processing (5)
  • libs/api-client-framework/Cargo.toml (1 hunks)
  • libs/api-client-framework/src/blockscout/client.rs (1 hunks)
  • libs/api-client-framework/src/blockscout/config.rs (1 hunks)
  • libs/api-client-framework/src/blockscout/mod.rs (1 hunks)
  • libs/api-client-framework/src/lib.rs (1 hunks)
🔇 Additional comments (6)
libs/api-client-framework/src/blockscout/client.rs (1)

27-28: Verify the default HealthCheckRequest initialization

When performing the health check, HealthCheckRequest is initialized with Default::default(). Ensure that the service can handle an empty service parameter or that the default initialization meets the API requirements.

Consider verifying that the health check endpoint functions correctly with the default request.

libs/api-client-framework/src/blockscout/mod.rs (1)

1-5: Module structure looks good

The addition of the client and config modules and their public exports is well-structured, enhancing the modularity and accessibility of the Blockscout client functionality.

libs/api-client-framework/src/blockscout/config.rs (1)

74-78: Ensure retry policy aligns with service requirements

When configuring the retry middleware with an exponential backoff strategy, verify that the maximum number of retries and the backoff parameters are suitable for the Blockscout service's rate limits and expected response times.

Consider reviewing the retry policy settings to ensure they adhere to best practices and do not inadvertently cause excessive load or violate service usage policies.

libs/api-client-framework/Cargo.toml (2)

21-25: LGTM! Well-structured feature definition.

The blockscout feature is well-defined with appropriate dependencies for an API client implementation.


18-18: Verify reqwest-retry version compatibility.

Please verify compatibility with reqwest v0.12.x as reqwest-retry v0.7.0 might have been tested with an older reqwest version.

Run this script to check compatibility:

libs/api-client-framework/src/lib.rs (1)

8-9: LGTM! Well-structured module definition.

The module is correctly feature-gated and exposed as public, which is appropriate for a framework.

Comment on lines +14 to +15
#[serde(default = "defaults::http_timeout")]
pub http_timeout: Duration,
Copy link
Member Author

@rimrakhimov rimrakhimov Jan 24, 2025

Choose a reason for hiding this comment

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

  1. How timeout is deserialized in that case (as seconds)?
  2. Can we make the default value configurable?
  3. Should we add deny_unknown_fields here?

Ref: https://github.com/blockscout/blockscout-rs/pull/1208/files#diff-c1be2081090d95af6dc680cfe111629947a8bb3662810568b433f806f43413deR63

@rimrakhimov rimrakhimov merged commit 77a18e8 into main Jan 30, 2025
3 checks passed
@rimrakhimov rimrakhimov deleted the rimrakhimov/api-framework/add-blockscout-definitions branch January 30, 2025 07:28
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