diff --git a/src/error.rs b/src/error.rs index f1fedd7..8fd29dc 100644 --- a/src/error.rs +++ b/src/error.rs @@ -15,6 +15,10 @@ pub enum Error { #[error("Config: {0}")] Config(#[from] ron::error::SpannedError), + // Duplicate event + #[error("Duplicate")] + Duplicate, + // End of Input #[error("End of input")] EndOfInput, diff --git a/src/store/mod.rs b/src/store/mod.rs index c3df13a..6fb8487 100644 --- a/src/store/mod.rs +++ b/src/store/mod.rs @@ -2,7 +2,8 @@ pub mod event_store; pub use event_store::EventStore; use crate::error::Error; -use crate::types::Id; +use crate::types::Event; +use heed::types::{OwnedType, UnalignedSlice}; use heed::{Database, Env, EnvFlags, EnvOpenOptions}; use std::fs; @@ -10,7 +11,7 @@ use std::fs; pub struct Store { events: EventStore, env: Env, - ids: Database, + ids: Database, OwnedType>, } impl Store { @@ -37,7 +38,8 @@ impl Store { let mut txn = env.write_txn()?; let ids = env .database_options() - .types::() + .types::, OwnedType>() + .name("ids") .create(&mut txn)?; txn.commit()?; @@ -51,4 +53,24 @@ impl Store { ids, }) } + + pub fn store_event(&self, event: &Event) -> Result { + // TBD: should we validate the event? + + let mut txn = self.env.write_txn()?; + let offset; + + // Only if it doesn't already exist + if self.ids.get(&txn, event.id().0.as_slice())?.is_none() { + offset = self.events.store_event(event)?; + + // Index by id + self.ids.put(&mut txn, event.id().0.as_slice(), &offset)?; + txn.commit()?; + } else { + return Err(Error::Duplicate); + } + + Ok(offset) + } }