@@ -4,13 +4,23 @@ use std::sync::Arc;
|
||||
|
||||
use axum::async_trait;
|
||||
|
||||
use churn_domain::ServerEnrollReq;
|
||||
use churn_domain::{LogEvent, ServerEnrollReq};
|
||||
use serde::{ser::SerializeStruct, Deserialize, Serialize};
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
|
||||
use churn_capnp::CapnpPackExt;
|
||||
|
||||
use crate::db::Db;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct EventService(Arc<dyn EventServiceTrait + Send + Sync + 'static>);
|
||||
|
||||
impl EventService {
|
||||
pub fn new(db: Db) -> Self {
|
||||
Self(Arc::new(DefaultEventService::new(db)))
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for EventService {
|
||||
type Target = Arc<dyn EventServiceTrait + Send + Sync + 'static>;
|
||||
|
||||
@@ -27,23 +37,12 @@ impl Default for EventService {
|
||||
|
||||
#[derive(Default)]
|
||||
struct DefaultEventService {
|
||||
agents: Arc<RwLock<Vec<LogEvent>>>,
|
||||
db: Db,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct LogEvent {
|
||||
pub id: uuid::Uuid,
|
||||
pub author: String,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
impl LogEvent {
|
||||
pub fn new(author: impl Into<String>, content: impl Into<String>) -> Self {
|
||||
Self {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
author: author.into(),
|
||||
content: content.into(),
|
||||
}
|
||||
impl DefaultEventService {
|
||||
pub fn new(db: Db) -> Self {
|
||||
Self { db }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,22 +56,34 @@ pub trait EventServiceTrait {
|
||||
#[async_trait]
|
||||
impl EventServiceTrait for DefaultEventService {
|
||||
async fn append(&self, req: LogEvent) -> anyhow::Result<()> {
|
||||
let mut events = self.agents.write().await;
|
||||
events.push(req);
|
||||
self.db
|
||||
.insert("events_log", &req.id.to_string(), &req.serialize_capnp())
|
||||
.await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
async fn get_from_cursor(&self, cursor: uuid::Uuid) -> anyhow::Result<Vec<LogEvent>> {
|
||||
let events = self.agents.read().await;
|
||||
let items = events
|
||||
let events = self.db.get_all("events_log").await?;
|
||||
|
||||
let events = events
|
||||
.iter()
|
||||
.map(|e| LogEvent::deserialize_capnp(e))
|
||||
.flatten()
|
||||
.skip_while(|item| item.id != cursor)
|
||||
.skip(1)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
Ok(items)
|
||||
.collect();
|
||||
|
||||
Ok(events)
|
||||
}
|
||||
async fn get_from_beginning(&self) -> anyhow::Result<Vec<LogEvent>> {
|
||||
let events = self.agents.read().await;
|
||||
Ok(events.iter().cloned().collect())
|
||||
let events = self.db.get_all("events_log").await?;
|
||||
|
||||
let events = events
|
||||
.iter()
|
||||
.map(|e| LogEvent::deserialize_capnp(e))
|
||||
.flatten()
|
||||
.collect();
|
||||
|
||||
Ok(events)
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user