use super::resolver::ResolveGuardError;
use crate::error::{DepsError, RateLimitEvidence};
use crate::redact::RedactedUrl;
use reqwest::{StatusCode, header};
#[inline]
pub(super) fn confirmed_rate_limit_exhaustion(
status: StatusCode,
headers: &header::HeaderMap,
) -> bool {
if !matches!(
status,
StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS
) {
return false;
}
let remaining_exhausted = headers
.get("x-ratelimit-remaining")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<u64>().ok())
== Some(0);
remaining_exhausted || headers.contains_key("retry-after")
}
const CONFIRMED_RATE_LIMIT_MESSAGE: &str =
"registry rate limit exceeded (confirmed by the response)";
#[inline]
pub(super) fn http_status_error(
url: &str,
status: StatusCode,
headers: &header::HeaderMap,
) -> DepsError {
if confirmed_rate_limit_exhaustion(status, headers) {
return DepsError::RateLimited {
message: CONFIRMED_RATE_LIMIT_MESSAGE.to_string(),
verified: RateLimitEvidence::Confirmed,
source_status: Some(status.as_u16()),
};
}
DepsError::HttpStatus {
url: RedactedUrl::new(url),
status: status.as_u16(),
}
}
pub(super) fn send_error(url: &str, error: reqwest::Error) -> DepsError {
let blocked =
std::iter::successors(std::error::Error::source(&error), |source| source.source())
.find_map(|source| match source.downcast_ref::<ResolveGuardError>() {
Some(ResolveGuardError::Blocked { block, .. }) => Some(*block),
Some(ResolveGuardError::NoAddresses { .. }) | None => None,
});
match blocked {
Some(block) => DepsError::HostBlockedByPolicy {
url: RedactedUrl::new(url),
block,
},
None => DepsError::RegistryError {
package: RedactedUrl::new(url),
source: error.into(),
},
}
}
pub(super) fn preflight_error(
url: &str,
error: Box<dyn std::error::Error + Send + Sync>,
) -> DepsError {
match error.downcast_ref::<ResolveGuardError>() {
Some(ResolveGuardError::Blocked { block, .. }) => DepsError::HostBlockedByPolicy {
url: RedactedUrl::new(url),
block: *block,
},
Some(ResolveGuardError::NoAddresses { .. }) => {
resolution_error(url, crate::error::ResolutionFailure::NoAddresses)
}
None => resolution_error(url, crate::error::ResolutionFailure::LookupFailed),
}
}
fn resolution_error(url: &str, failure: crate::error::ResolutionFailure) -> DepsError {
DepsError::RegistryError {
package: RedactedUrl::new(url),
source: failure.into(),
}
}