use std::collections::HashMap; use std::sync::Arc; use axum::async_trait; use churn_domain::ServerEnrollReq; use tokio::sync::Mutex; use crate::Agent; #[derive(Clone)] pub struct AgentService(Arc); impl std::ops::Deref for AgentService { type Target = Arc; fn deref(&self) -> &Self::Target { &self.0 } } impl Default for AgentService { fn default() -> Self { Self(Arc::new(DefaultAgentService::default())) } } #[derive(Default)] struct DefaultAgentService { agents: Arc>>, } #[async_trait] pub trait AgentServiceTrait { async fn enroll(&self, req: ServerEnrollReq) -> anyhow::Result; } #[async_trait] impl AgentServiceTrait for DefaultAgentService { async fn enroll(&self, req: ServerEnrollReq) -> anyhow::Result { let agent_name = req.agent_name; let mut agents = self.agents.lock().await; match agents.insert( agent_name.clone(), Agent { name: agent_name.clone(), }, ) { Some(_) => { tracing::debug!("agents store already contained agent, replaced existing"); Ok(agent_name) } None => { tracing::debug!("agents store didn't contain agent, inserted"); Ok(agent_name) } } } }