feat: with sled db

Signed-off-by: kjuulh <contact@kjuulh.io>
This commit is contained in:
2023-08-27 16:49:53 +02:00
parent 9e61ed7ef7
commit 757d1081bd
12 changed files with 682 additions and 31 deletions

View File

@@ -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)
}
}