use core::fmt;
use std::time::Duration;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LinkState {
Connected,
Reconnecting,
Refused {
daemon_version: Option<String>,
message: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use = "which of the two it was decides whether a dog exits unreachable or refused"]
#[non_exhaustive]
pub enum LinkLost {
Budget {
waited: Duration,
},
Refused {
daemon_version: Option<String>,
message: String,
},
}
impl LinkLost {
#[must_use]
pub const fn exit_code(&self) -> u8 {
use shep_core::exit;
match self {
Self::Refused { .. } => exit::PROTOCOL_MISMATCH,
Self::Budget { .. } => exit::DAEMON_UNREACHABLE,
}
}
}
impl fmt::Display for LinkLost {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Budget { waited } => write!(f, "no shepherd answered within {waited:?}"),
Self::Refused { message, .. } => {
write!(f, "the shepherd refused this connection: {message}")
}
}
}
}
impl core::error::Error for LinkLost {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use = "the verdict says whether ids held from before the reconnect still mean anything"]
pub enum Reconnected {
SameDaemon,
NewDaemon,
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::*;
#[test]
fn a_lost_link_says_which_of_the_two_it_was() {
let budget = LinkLost::Budget {
waited: Duration::from_secs(5),
};
assert_eq!(budget.to_string(), "no shepherd answered within 5s");
let refused = LinkLost::Refused {
daemon_version: Some("0.9.9".into()),
message: "daemon speaks protocol 3, client speaks 2".into(),
};
assert_eq!(
refused.to_string(),
"the shepherd refused this connection: daemon speaks protocol 3, client speaks 2"
);
}
#[test]
fn reconnected_debug_is_the_verdict_and_nothing_else() {
assert_eq!(format!("{:?}", Reconnected::SameDaemon), "SameDaemon");
assert_eq!(format!("{:?}", Reconnected::NewDaemon), "NewDaemon");
}
#[test]
fn a_refused_link_exits_protocol_mismatch_and_a_spent_budget_unreachable() {
let refused = LinkLost::Refused {
daemon_version: None,
message: "too old".to_owned(),
};
let spent = LinkLost::Budget {
waited: Duration::from_secs(5),
};
assert_eq!(refused.exit_code(), shep_core::exit::PROTOCOL_MISMATCH);
assert_eq!(spent.exit_code(), shep_core::exit::DAEMON_UNREACHABLE);
}
}