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: use source http error instead of application libarary error #5

Open
wants to merge 5 commits into
base: main
Choose a base branch
from

Conversation

xoac
Copy link

@xoac xoac commented Apr 24, 2023

According to eyre documentation:

Use eyre if you don’t think you’ll do anything with an error other than report it. This is common in application code. Use thiserror if you think you need an error type that can be handled via match or reported. This is common in library crates where you don’t know how your users will handle your errors.

It shouldn't be used in libraries. This PR remove it and instead returns Http Error from request to be handled by application.

Summary by CodeRabbit

  • New Features

    • Updated dependencies to improve HTTP request handling.
    • Introduced new features related to the reqwest crate for enhanced functionality.
  • Bug Fixes

    • Improved error handling in asynchronous calls to prevent panics.
  • Documentation

    • Updated the configuration for test files to simplify feature checks.
  • Chores

    • Modified .gitignore to exclude unnecessary files and directories.

@xoac xoac force-pushed the feat/use-source-errors branch from 419af83 to 3910c10 Compare April 24, 2023 07:37
@xoac xoac force-pushed the feat/use-source-errors branch from d2fc6f9 to a2b098f Compare June 7, 2023 15:46
@xoac xoac force-pushed the feat/use-source-errors branch from a2b098f to 7ecc7b5 Compare June 7, 2023 15:51
xoac added 2 commits August 28, 2023 15:01
* reqwest, http dependecies update

* chore: remove Cargo.lock from lib repo
Copy link

coderabbitai bot commented Dec 16, 2024

Walkthrough

This pull request introduces significant updates to the chain-registry package, focusing on dependency management and error handling. The changes primarily involve updating the HTTP-related dependencies, transitioning from eyre to reqwest for error handling, and modifying function signatures to use more type-specific return types. The modifications streamline the codebase by improving type safety, simplifying JSON deserialization, and providing more granular feature configurations for HTTP requests.

Changes

File Changes
.gitignore - Added Cargo.lock to ignored files
- Maintained /target directory exclusion
Cargo.toml - Updated http dependency to version 1
- Removed eyre and serde_json dependencies
- Added reqwest dependency with optional features
- Updated and added new features for reqwest
src/cache.rs - Replaced eyre::Result with HttpResult
- Modified return types for get_path, get_paths_filtered, and try_new methods
src/get.rs - Renamed get to get_typed with generic deserialization
- Updated function signatures to use HttpResult
- Renamed get_file_content to get_file_typed_content
- Improved error handling and JSON processing
tests/registry_cache.rs - Simplified feature configuration attribute
- Refined asynchronous method call handling

Sequence Diagram

sequenceDiagram
    participant Client
    participant RegistryCache
    participant HTTPClient
    participant RemoteRepository

    Client->>RegistryCache: get_paths_filtered(tag)
    RegistryCache->>HTTPClient: Send request
    HTTPClient->>RemoteRepository: Fetch data
    RemoteRepository-->>HTTPClient: Return JSON response
    HTTPClient-->>RegistryCache: Deserialize response
    RegistryCache-->>Client: Return filtered paths
Loading

Poem

🐰 Hop, hop, through the code's new terrain,
Reqwest's magic, no more error pain!
Dependencies dance, types align just right,
Cargo.toml sparkles with features so bright!
A rabbit's delight in this refactored scene 🚀


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

@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: 4

🔭 Outside diff range comments (1)
src/cache.rs (1)

Line range hint 74-86: Avoid using expect to prevent panics in library code

Using expect("path returned None") can cause a panic if the condition is not met. In library code, it's better to handle errors gracefully without panicking.

Apply this diff to handle the None case appropriately:

 paths.insert(
     pn.clone(),
-    get_path(cn[0], cn[1]).await?.expect("path returned None"),
+    match get_path(cn[0], cn[1]).await? {
+        Some(path) => path,
+        None => continue, // or handle the error as needed
+    },
 );
🧹 Nitpick comments (4)
src/get.rs (1)

16-22: Use &str instead of String for the url parameter

The get_typed function accepts url: String, but it can accept a &str, which avoids unnecessary cloning and can improve performance.

Apply this diff to adjust the parameter type:

-async fn get_typed<T: DeserializeOwned>(url: String) -> HttpResult<T> {
+async fn get_typed<T: DeserializeOwned>(url: &str) -> HttpResult<T> {
     let client = reqwest::Client::new();
     let req = client
-        .request(Method::GET, url)
+        .request(Method::GET, url.to_string())
         .header("User-Agent", format!("ocular/{}", VERSION))
         .build()?;
     client.execute(req).await?.error_for_status()?.json().await
 }
Cargo.toml (1)

29-31: Ensure feature flags include all necessary dependencies

The reqwest-blocking feature depends on reqwest-crate/blocking but doesn't include the base reqwest-crate dependency in its feature list, which could lead to missing features or compilation errors.

Apply this diff to include reqwest-crate in the reqwest-blocking feature:

 reqwest = ["reqwest-crate", "reqwest-crate/default-tls"]
 reqwest-rustls = ["reqwest-crate", "reqwest-crate/rustls-tls"]
-reqwest-blocking = ["reqwest-crate/blocking"]
+reqwest-blocking = ["reqwest-crate", "reqwest-crate/blocking"]
src/cache.rs (2)

Line range hint 32-38: Remove unnecessary async keyword from get_path function

The get_path function does not perform any asynchronous operations but is declared as async. This adds unnecessary overhead.

Apply this diff to remove async:

-pub async fn get_path(&self, chain_a: &str, chain_b: &str) -> HttpResult<Option<IBCPath>> {
+pub fn get_path(&self, chain_a: &str, chain_b: &str) -> HttpResult<Option<IBCPath>> {

Line range hint 60-70: Remove unnecessary async keyword from get_paths_filtered function

Since get_paths_filtered doesn't perform any asynchronous operations, removing async can improve performance.

Apply this diff to remove async:

-pub async fn get_paths_filtered(&self, tag: Tag) -> Vec<IBCPath> {
+pub fn get_paths_filtered(&self, tag: Tag) -> Vec<IBCPath> {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c5144d9 and a3b0d2a.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (5)
  • .gitignore (1 hunks)
  • Cargo.toml (1 hunks)
  • src/cache.rs (4 hunks)
  • src/get.rs (8 hunks)
  • tests/registry_cache.rs (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • .gitignore
🔇 Additional comments (4)
tests/registry_cache.rs (4)

1-1: Simplify conditional compilation attribute

The change from #![cfg(all(feature = "cache"))] to #![cfg(feature = "cache")] is acceptable and simplifies the condition.


24-26: Remove unnecessary error handling

Since get_paths_filtered now returns Vec<IBCPath> instead of a Result, the error handling can be simplified. The updated code reflects this change appropriately.


31-33: Consistent error handling after signature change

The changes align with the updated return type of get_paths_filtered, removing unnecessary unwrapping of results.


38-40: Maintain consistency in test assertions

The test correctly asserts that the result is not empty and checks the status values.

Comment on lines +6 to +7
use reqwest::Result as HttpResult;
use reqwest_crate as reqwest;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider encapsulating reqwest errors to avoid exposing dependency details

The use of reqwest::Result (aliased as HttpResult) in public API functions exposes the reqwest crate in your library's public interface. This can cause issues if you switch HTTP clients in the future or if users have version conflicts. It's better to define a custom error type and convert reqwest::Error into your own error before returning it to maintain abstraction.

Comment on lines +91 to +104
async fn get_file_typed_content<T: DeserializeOwned>(
r#ref: &str,
path: &str,
) -> HttpResult<Option<T>> {
let url = format!("{}/{}/{}", RAW_FILE_REPO_URL, r#ref, path);
let response = reqwest::get(url).await?; //.text().await?

if response.status() == StatusCode::NOT_FOUND {
return Err(eyre!("path {} not found", path));
match reqwest::get(url).await?.error_for_status() {
Ok(res) => res.json().await,
Err(e) => {
if e.status() == Some(StatusCode::NOT_FOUND) {
Ok(None)
} else {
Err(e)
}
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle network errors separately to ensure robust error handling

In the current implementation of get_file_typed_content, if reqwest::get(url).await? fails due to a network error, the error is propagated immediately, bypassing your error handling logic for HTTP status codes. Refactor the code to separately handle network errors and HTTP errors.

Apply this diff to improve error handling:

-    match reqwest::get(url).await?.error_for_status() {
-        Ok(res) => res.json().await,
-        Err(e) => {
-            if e.status() == Some(StatusCode::NOT_FOUND) {
-                Ok(None)
-            } else {
-                Err(e)
-            }
-        }
-    }
+    let response = reqwest::get(url).await;
+    match response {
+        Ok(res) => match res.error_for_status() {
+            Ok(success_res) => success_res.json().await.map(Some),
+            Err(e) => {
+                if e.status() == Some(StatusCode::NOT_FOUND) {
+                    Ok(None)
+                } else {
+                    Err(e)
+                }
+            }
+        },
+        Err(e) => Err(e),
+    }
📝 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
async fn get_file_typed_content<T: DeserializeOwned>(
r#ref: &str,
path: &str,
) -> HttpResult<Option<T>> {
let url = format!("{}/{}/{}", RAW_FILE_REPO_URL, r#ref, path);
let response = reqwest::get(url).await?; //.text().await?
if response.status() == StatusCode::NOT_FOUND {
return Err(eyre!("path {} not found", path));
match reqwest::get(url).await?.error_for_status() {
Ok(res) => res.json().await,
Err(e) => {
if e.status() == Some(StatusCode::NOT_FOUND) {
Ok(None)
} else {
Err(e)
}
}
async fn get_file_typed_content<T: DeserializeOwned>(
r#ref: &str,
path: &str,
) -> HttpResult<Option<T>> {
let url = format!("{}/{}/{}", RAW_FILE_REPO_URL, r#ref, path);
let response = reqwest::get(url).await;
match response {
Ok(res) => match res.error_for_status() {
Ok(success_res) => success_res.json().await.map(Some),
Err(e) => {
if e.status() == Some(StatusCode::NOT_FOUND) {
Ok(None)
} else {
Err(e)
}
}
},
Err(e) => Err(e),
}

eyre = "0.6"
http = "0.2"
reqwest = "0.11"
http = "1"
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Incorrect version specified for the http crate

The http crate does not have a stable release at version "1". The latest version at the time of writing is "0.2". Specifying an invalid version will lead to dependency resolution errors.

Apply this diff to correct the version:

-http = "1"
+http = "0.2"
📝 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
http = "1"
http = "0.2"

Comment on lines +10 to +11
use reqwest::Result as HttpResult;
use reqwest_crate as reqwest;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider encapsulating reqwest errors in a custom error type

Exposing reqwest::Result publicly ties your library to the reqwest crate. To maintain abstraction, define a custom error type and convert reqwest::Error into it before returning.

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