-
Notifications
You must be signed in to change notification settings - Fork 209
Categorize crates.io API errors #2852
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
base: master
Are you sure you want to change the base?
Changes from all commits
34a21b1
aee103c
32aaf46
5b75617
5f81817
3669b65
bec60b6
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -33,6 +33,21 @@ use url::form_urlencoded; | |
|
||
use super::cache::CachePolicy; | ||
|
||
// Introduce SearchError as new error type | ||
#[derive(Debug, thiserror::Error)] | ||
pub enum SearchError { | ||
#[error("crates.io error: {0}")] | ||
CratesIo(String), | ||
#[error(transparent)] | ||
Other(#[from] anyhow::Error), | ||
} | ||
|
||
impl From<sqlx::Error> for SearchError { | ||
fn from(err: sqlx::Error) -> Self { | ||
SearchError::Other(anyhow::Error::from(err)) | ||
} | ||
} | ||
|
||
/// Number of release in home page | ||
const RELEASES_IN_HOME: i64 = 15; | ||
/// Releases in /releases page | ||
|
@@ -149,8 +164,13 @@ async fn get_search_results( | |
conn: &mut sqlx::PgConnection, | ||
registry: &RegistryApi, | ||
query_params: &str, | ||
) -> Result<SearchResult, anyhow::Error> { | ||
let crate::registry_api::Search { crates, meta } = registry.search(query_params).await?; | ||
) -> Result<SearchResult, SearchError> { | ||
// Capture responses returned by registry | ||
let result = registry.search(query_params).await; | ||
let crate::registry_api::Search { crates, meta } = match result { | ||
Ok(results_from_search_request) => results_from_search_request, | ||
Err(err) => return handle_registry_error(err), | ||
}; | ||
|
||
let names = Arc::new( | ||
crates | ||
|
@@ -233,6 +253,35 @@ async fn get_search_results( | |
}) | ||
} | ||
|
||
// Categorize errors from registry | ||
fn handle_registry_error(err: anyhow::Error) -> Result<SearchResult, SearchError> { | ||
// Capture crates.io API error | ||
if let Some(registry_request_error) = err.downcast_ref::<reqwest::Error>() | ||
&& let Some(status) = registry_request_error.status() | ||
&& (status.is_client_error() || status.is_server_error()) | ||
{ | ||
return Err(SearchError::CratesIo(format!( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. looking at what do you think? should we change There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Great suggestion. However, I have great reserve about this because RegistryApi might introduce new problems such as limited reusability, and how we might want to handle errors in different part of the codebase. |
||
"crates.io returned {status}: {registry_request_error}" | ||
))); | ||
} | ||
// Move all other error types to this wrapper | ||
Err(SearchError::Other(err)) | ||
} | ||
|
||
//Error message to gracefully display | ||
fn create_search_error_response(query: String, sort_by: String, error_message: String) -> Search { | ||
Search { | ||
title: format!("Search service is not currently available: {error_message}"), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. please add a test that tests this new behaviour. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good point! I went back to add test for this. |
||
releases: vec![], | ||
search_query: Some(query), | ||
search_sort_by: Some(sort_by), | ||
previous_page_link: None, | ||
next_page_link: None, | ||
release_type: ReleaseType::Search, | ||
status: http::StatusCode::SERVICE_UNAVAILABLE, | ||
} | ||
} | ||
|
||
#[derive(Template)] | ||
#[template(path = "core/home.html")] | ||
#[derive(Debug, Clone, PartialEq, Eq)] | ||
|
@@ -589,19 +638,32 @@ pub(crate) async fn search_handler( | |
} | ||
} | ||
|
||
get_search_results(&mut conn, ®istry, query_params).await? | ||
get_search_results(&mut conn, ®istry, query_params).await | ||
} else if !query.is_empty() { | ||
let query_params: String = form_urlencoded::Serializer::new(String::new()) | ||
.append_pair("q", &query) | ||
.append_pair("sort", &sort_by) | ||
.append_pair("per_page", &RELEASES_IN_RELEASES.to_string()) | ||
.finish(); | ||
|
||
get_search_results(&mut conn, ®istry, &query_params).await? | ||
get_search_results(&mut conn, ®istry, &query_params).await | ||
} else { | ||
return Err(AxumNope::NoResults); | ||
}; | ||
|
||
let search_result = match search_result { | ||
Ok(result) => result, | ||
Err(SearchError::CratesIo(error_message)) => { | ||
// Return a user-friendly error response | ||
return Ok(create_search_error_response(query, sort_by, error_message).into_response()); | ||
} | ||
Err(SearchError::Other(err)) => { | ||
// For other errors, propagate them normally | ||
// NOTE - Errrors that are not 400x or 500x will be logged to Sentry | ||
return Err(err.into()); | ||
} | ||
}; | ||
|
||
let title = if search_result.results.is_empty() { | ||
format!("No results found for '{query}'") | ||
} else { | ||
|
@@ -1251,7 +1313,7 @@ mod tests { | |
.await | ||
.get("/releases/search?query=doesnt_matter_here") | ||
.await?; | ||
assert_eq!(response.status(), 500); | ||
assert_eq!(response.status(), 503); | ||
|
||
assert!(response.text().await?.contains(&format!("{status}"))); | ||
Ok(()) | ||
|
@@ -2231,4 +2293,43 @@ mod tests { | |
Ok(()) | ||
}); | ||
} | ||
|
||
#[test] | ||
fn test_create_search_error_response() { | ||
let response = create_search_error_response( | ||
"test_query".to_string(), | ||
"relevance".to_string(), | ||
"Service temporarily unavailable".to_string(), | ||
); | ||
assert_eq!( | ||
response.title, | ||
"Search service is not currently available: Service temporarily unavailable" | ||
); | ||
assert_eq!(response.status, http::StatusCode::SERVICE_UNAVAILABLE); | ||
assert_eq!(response.release_type, ReleaseType::Search); | ||
} | ||
|
||
#[test] | ||
fn crates_io_search_returns_status_code_5xx() { | ||
async_wrapper(|env| async move { | ||
let mut crates_io = mockito::Server::new_async().await; | ||
env.override_config(|config| { | ||
config.registry_api_host = crates_io.url().parse().unwrap(); | ||
}); | ||
|
||
crates_io | ||
.mock("GET", "/api/v1/crates") | ||
.with_status(500) | ||
.create_async() | ||
.await; | ||
|
||
let response = env | ||
.web_app() | ||
.await | ||
.get("/releases/search?query=anything_goes_here") | ||
.await?; | ||
assert_eq!(response.status(), 503); | ||
Ok(()) | ||
}) | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the
Ok
variant will never be returned, right?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
also, we could put this into from
impl From<anyhow::Error> for SearchError
above?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note: The OK variant will never return.
Also, I don't feel comfortable with returning
SearchError
directly. While the suggestion makes it simpler, it could lead to issues down the line when the function would fail silently. I'd prefer this to stay explicit.