Store Events

This commit is contained in:
Mike Dilger 2024-02-14 15:00:58 +13:00
parent 42b5042aa6
commit 0e218e95ef
2 changed files with 29 additions and 3 deletions

View File

@ -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,

View File

@ -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<Id, usize>,
ids: Database<UnalignedSlice<u8>, OwnedType<usize>>,
}
impl Store {
@ -37,7 +38,8 @@ impl Store {
let mut txn = env.write_txn()?;
let ids = env
.database_options()
.types::<Id, usize>()
.types::<UnalignedSlice<u8>, OwnedType<usize>>()
.name("ids")
.create(&mut txn)?;
txn.commit()?;
@ -51,4 +53,24 @@ impl Store {
ids,
})
}
pub fn store_event(&self, event: &Event) -> Result<usize, Error> {
// 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)
}
}