use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ProxyError {
ConnFailed,
Timeout,
Reset,
EmptyRecv,
BadStatus,
BadResponse,
ErrorOnStream,
DisallowedStatus(u16),
Resolve,
}
impl ProxyError {
pub const fn as_str(self) -> &'static str {
match self {
ProxyError::ConnFailed => "connection_failed",
ProxyError::Timeout => "connection_timeout",
ProxyError::Reset => "connection_is_reset",
ProxyError::EmptyRecv => "empty_response",
ProxyError::BadStatus => "bad_status",
ProxyError::BadResponse => "bad_response",
ProxyError::ErrorOnStream => "error_on_stream",
ProxyError::DisallowedStatus(_) => "disallowed_status",
ProxyError::Resolve => "resolve_failed",
}
}
}
impl fmt::Display for ProxyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl std::error::Error for ProxyError {}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("no working judges were found")]
NoJudges,
#[error("at least one proxy type is required")]
NoTypes,
#[error("no providers configured")]
NoProviders,
#[error("could not determine this machine's external IP address")]
ExtIpUnknown,
#[error("invalid provider configuration: {0}")]
Config(String),
#[error(transparent)]
Io(#[from] std::io::Error),
#[error("persistence error: {0}")]
Persist(String),
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
#[test]
fn errmsg_strings_match_python_byte_for_byte() {
assert_eq!(ProxyError::ConnFailed.as_str(), "connection_failed");
assert_eq!(ProxyError::Timeout.as_str(), "connection_timeout");
assert_eq!(ProxyError::Reset.as_str(), "connection_is_reset");
assert_eq!(ProxyError::EmptyRecv.as_str(), "empty_response");
assert_eq!(ProxyError::BadStatus.as_str(), "bad_status");
assert_eq!(ProxyError::BadResponse.as_str(), "bad_response");
assert_eq!(ProxyError::ErrorOnStream.as_str(), "error_on_stream");
}
#[test]
fn reset_is_a_single_bucket() {
let mut counter: HashMap<ProxyError, u32> = HashMap::new();
*counter.entry(ProxyError::Reset).or_default() += 1;
*counter.entry(ProxyError::Reset).or_default() += 1;
assert_eq!(counter.len(), 1);
assert_eq!(counter[&ProxyError::Reset], 2);
assert_eq!(
counter.keys().next().unwrap().as_str(),
"connection_is_reset"
);
}
#[test]
fn proxy_error_is_a_cheap_hashmap_key() {
let mut stats: HashMap<ProxyError, u32> = HashMap::new();
for e in [
ProxyError::ConnFailed,
ProxyError::Timeout,
ProxyError::Timeout,
ProxyError::BadStatus,
] {
*stats.entry(e).or_default() += 1;
}
assert_eq!(stats[&ProxyError::Timeout], 2);
assert_eq!(stats[&ProxyError::ConnFailed], 1);
assert_eq!(stats.get(&ProxyError::Reset), None);
}
#[test]
fn display_delegates_to_as_str() {
assert_eq!(ProxyError::Timeout.to_string(), "connection_timeout");
}
}