use std::{fmt, time::Duration};
pub(crate) const BAD_MESSAGE_BAN_TIME: Duration = Duration::from_secs(60 * 60 * 24);
#[repr(u16)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StatusCode {
OK = 200,
TooManyRequests = 110,
InvalidMaxTTL = 410,
InvalidFromPeerId = 411,
InvalidToPeerId = 412,
InvalidRoute = 413,
InvalidListenAddrLen = 414,
Ignore = 501,
BroadcastError = 502,
ForwardError = 503,
ReachedMaxHops = 504,
}
#[derive(Clone, Debug, Eq)]
pub struct Status {
code: StatusCode,
context: Option<String>,
}
impl PartialEq for Status {
fn eq(&self, other: &Self) -> bool {
self.code == other.code
}
}
impl fmt::Display for Status {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.context {
Some(ref context) => write!(f, "{:?}({}): {}", self.code, self.code as u16, context),
None => write!(f, "{:?}({})", self.code, self.code as u16),
}
}
}
impl From<StatusCode> for Status {
fn from(code: StatusCode) -> Self {
Self::new::<&str>(code, None)
}
}
impl StatusCode {
pub fn with_context<S: ToString>(self, context: S) -> Status {
Status::new(self, Some(context))
}
}
impl Status {
pub fn new<T: ToString>(code: StatusCode, context: Option<T>) -> Self {
Self {
code,
context: context.map(|c| c.to_string()),
}
}
pub fn ok() -> Self {
Self::new::<&str>(StatusCode::OK, None)
}
pub fn is_ok(&self) -> bool {
self.code == StatusCode::OK
}
pub fn should_ban(&self) -> Option<Duration> {
let code = self.code() as u16;
if (400..500).contains(&code) {
Some(BAD_MESSAGE_BAN_TIME)
} else {
None
}
}
pub fn should_warn(&self) -> bool {
let code = self.code() as u16;
(500..600).contains(&code)
}
pub fn code(&self) -> StatusCode {
self.code
}
}