feat: with agent db

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
2023-08-27 19:42:33 +02:00
parent 75d99c2461
commit 43ed89d0d8
10 changed files with 286 additions and 68 deletions

View File

@@ -1,17 +1,21 @@
use std::collections::HashMap;
use std::sync::Arc;
use axum::async_trait;
use churn_domain::ServerEnrollReq;
use tokio::sync::Mutex;
use churn_capnp::CapnpPackExt;
use churn_domain::{Agent, ServerEnrollReq};
use crate::Agent;
use crate::db::Db;
#[derive(Clone)]
pub struct AgentService(Arc<dyn AgentServiceTrait + Send + Sync + 'static>);
impl AgentService {
pub fn new(db: Db) -> Self {
Self(Arc::new(DefaultAgentService::new(db)))
}
}
impl std::ops::Deref for AgentService {
type Target = Arc<dyn AgentServiceTrait + Send + Sync + 'static>;
@@ -28,7 +32,13 @@ impl Default for AgentService {
#[derive(Default)]
struct DefaultAgentService {
agents: Arc<Mutex<HashMap<String, Agent>>>,
agents: Db,
}
impl DefaultAgentService {
pub fn new(db: Db) -> Self {
Self { agents: db }
}
}
#[async_trait]
@@ -41,24 +51,17 @@ impl AgentServiceTrait for DefaultAgentService {
async fn enroll(&self, req: ServerEnrollReq) -> anyhow::Result<String> {
let agent_name = req.agent_name;
let mut agents = self.agents.lock().await;
self.agents
.insert(
"agents",
&agent_name,
&Agent {
name: agent_name.clone(),
}
.serialize_capnp(),
)
.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)
}
}
Ok(agent_name)
}
}