Split repository into 3 crates

This commit is contained in:
Philip (a-0) 2024-01-05 20:59:25 +01:00
parent d8f1733eb3
commit 31dc4fd4a3
35 changed files with 4011 additions and 498 deletions

View file

@ -1,114 +0,0 @@
use std::sync::{Arc, RwLock};
use anyhow::Error;
use cozo::DbInstance;
use tracing::{debug, error};
use crate::comm::{
messages::{Message, MessageContent},
CommHandle, Peer,
};
use self::types::{Element, ElementContent, ElementId, Tag};
pub mod types;
mod api_state;
mod comm_state;
mod queries;
mod schema;
pub use api_state::ApiState;
pub use comm_state::CommState;
pub struct State {
db: DbInstance,
comm_handle: RwLock<Option<Arc<CommHandle>>>,
}
impl State {
pub async fn new() -> anyhow::Result<Arc<State>> {
let db = DbInstance::new("mem", "", Default::default());
match db {
Ok(d) => {
schema::add_schema(&d)?;
Ok(Arc::new(State {
db: d,
comm_handle: RwLock::new(None),
}))
}
Err(e) => Err(Error::msg(format!("{:?}", e))),
}
}
pub fn set_comm_handle(&self, handle: Arc<CommHandle>) {
*self
.comm_handle
.write()
.as_deref_mut()
.expect("Could not set state's CommHandle") = Some(handle);
}
pub fn set_element_content(
&self,
element_id: &ElementId,
content: &ElementContent,
) -> anyhow::Result<()> {
let res = queries::elements::set_content(&self.db, element_id, content);
debug!(
"Set content of element with id {:?}: {:?}",
element_id,
self.get_element(element_id)
);
self.send_to_peers(MessageContent::SetElement {
id: element_id.clone(),
content: content.clone(),
});
res
}
pub fn remove_element(&self, element_id: &ElementId) -> anyhow::Result<()> {
let res = queries::elements::remove(&self.db, element_id);
self.send_to_peers(MessageContent::RemoveElement {
id: element_id.clone(),
});
res
}
pub fn get_element(&self, id: &ElementId) -> anyhow::Result<Element> {
queries::elements::get(&self.db, id)
}
pub fn get_elements_by_tag(&self, tag: &Tag) -> Vec<ElementId> {
queries::elements::get_by_tag(&self.db, tag)
.map_err(|e| {
error!("{}", e);
e
})
.unwrap_or(vec![])
}
pub fn set_peer(&self, peer: &Peer) -> anyhow::Result<()> {
queries::peers::put(&self.db, &peer.id(), &peer.name())
}
pub fn get_peers(&self) -> anyhow::Result<Vec<Peer>> {
queries::peers::get(&self.db)
}
fn send_to_peers(&self, ct: MessageContent) {
match self.comm_handle.read() {
Ok(opt) => {
if opt.is_some() {
let arc = opt.as_ref().unwrap().clone();
tokio::spawn(async move {
let _ = arc.broadcast(Message::new(ct)).await;
});
}
}
Err(e) => debug!("{}", e),
}
}
}