use crate::utils::clock::Instant;
use tokio::task::JoinHandle;
use super::client::ClientId;
use super::server::ServerId;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct EasyId(u32);
impl EasyId {
pub fn new(id: u32) -> Self {
Self(id)
}
pub fn as_u32(&self) -> u32 {
self.0
}
pub fn from_string(s: &str) -> Option<Self> {
let s = s.trim();
let id_str = s.strip_prefix("easy-").unwrap_or(s);
id_str.parse::<u32>().ok().map(Self)
}
}
impl std::fmt::Display for EasyId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "easy-{}", self.0)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EasyStatus {
Starting,
Running,
Stopped,
Error(String),
}
impl EasyStatus {
pub fn as_str(&self) -> &str {
match self {
Self::Starting => "Starting",
Self::Running => "Running",
Self::Stopped => "Stopped",
Self::Error(_) => "Error",
}
}
}
impl std::fmt::Display for EasyStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Starting => write!(f, "Starting"),
Self::Running => write!(f, "Running"),
Self::Stopped => write!(f, "Stopped"),
Self::Error(msg) => write!(f, "Error: {}", msg),
}
}
}
#[derive(Debug)]
pub struct EasyInstance {
pub id: EasyId,
pub protocol_name: String,
pub underlying_protocol: String,
pub user_instruction: Option<String>,
pub underlying_server_id: Option<ServerId>,
pub underlying_client_id: Option<ClientId>,
pub status: EasyStatus,
pub created_at: Instant,
pub status_changed_at: Instant,
pub handle: Option<JoinHandle<()>>,
}
impl EasyInstance {
pub fn new(
id: EasyId,
protocol_name: String,
underlying_protocol: String,
user_instruction: Option<String>,
) -> Self {
let now = Instant::now();
Self {
id,
protocol_name,
underlying_protocol,
user_instruction,
underlying_server_id: None,
underlying_client_id: None,
status: EasyStatus::Starting,
created_at: now,
status_changed_at: now,
handle: None,
}
}
pub fn set_underlying_server(&mut self, server_id: ServerId) {
self.underlying_server_id = Some(server_id);
}
pub fn set_underlying_client(&mut self, client_id: ClientId) {
self.underlying_client_id = Some(client_id);
}
pub fn set_status(&mut self, status: EasyStatus) {
self.status = status;
self.status_changed_at = Instant::now();
}
}