use core::num::NonZeroU64;
use core::sync::atomic::{AtomicU64, Ordering};
use std::sync::{PoisonError, RwLock};
use futures_core::Stream;
use happenstance_core::{
AppendCondition, AppendError, ConditionViolated, Event, EventId, MemoryStoreError, Query,
ReadOptions, RecordedAt, SendEventStore, SequencePosition, SequencedEvent, StoreId,
};
const RECORDED_AT: RecordedAt = RecordedAt::from_millis(1_700_000_000_000);
#[derive(Debug)]
pub struct GappyMemoryStore {
events: RwLock<Vec<SequencedEvent>>,
store_id: StoreId,
stride: NonZeroU64,
}
impl GappyMemoryStore {
#[must_use]
pub fn with_stride(stride: NonZeroU64) -> Self {
Self {
events: RwLock::new(Vec::new()),
store_id: next_store_id(),
stride,
}
}
#[must_use]
pub const fn store_id(&self) -> StoreId {
self.store_id
}
fn next_position(&self, previous: Option<SequencePosition>) -> SequencePosition {
let raw = match previous {
None => self.stride.get(),
Some(previous) => match previous.get().checked_add(self.stride.get()) {
Some(next) => next,
None => panic!(
"GappyMemoryStore has exhausted its position space: the next \
position after {previous} would overflow. Wrapping would \
break the strict monotonicity this store exists to keep"
),
},
};
SequencePosition::new(raw).unwrap_or(SequencePosition::FIRST)
}
fn read_guard(&self) -> std::sync::RwLockReadGuard<'_, Vec<SequencedEvent>> {
self.events.read().unwrap_or_else(PoisonError::into_inner)
}
}
fn next_store_id() -> StoreId {
static COUNTER: AtomicU64 = AtomicU64::new(1);
const TAG: u64 = 0x_6761_7070_795F_6D65;
let ordinal = COUNTER.fetch_add(1, Ordering::Relaxed);
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&TAG.to_be_bytes());
bytes[8..].copy_from_slice(&ordinal.to_be_bytes());
StoreId::from_bytes(bytes)
}
impl SendEventStore for GappyMemoryStore {
type Error = MemoryStoreError;
fn read(
&self,
query: &Query,
options: ReadOptions,
) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> + Send {
let guard = self.read_guard();
let matched = guard
.iter()
.filter(|event| query.matches(event.event_type(), event.tags()));
let mut selected: Vec<SequencedEvent> = if options.backwards {
matched
.rev()
.filter(|event| options.from.is_none_or(|from| event.position <= from))
.filter(|event| options.to.is_none_or(|to| event.position >= to))
.cloned()
.collect()
} else {
matched
.filter(|event| options.from.is_none_or(|from| event.position >= from))
.filter(|event| options.to.is_none_or(|to| event.position <= to))
.cloned()
.collect()
};
if let Some(limit) = options.limit {
selected.truncate(limit);
}
drop(guard);
Snapshot(selected.into_iter())
}
async fn append(
&self,
events: &[Event],
condition: Option<&AppendCondition>,
) -> Result<SequencePosition, AppendError<Self::Error>> {
if events.is_empty() {
return Err(AppendError::NoEvents);
}
let mut stored = self.events.write().unwrap_or_else(PoisonError::into_inner);
if let Some(condition) = condition {
let conflict = stored.iter().find(|existing| {
condition.is_violated_by(existing.position, existing.event_type(), existing.tags())
});
if let Some(conflict) = conflict {
return Err(AppendError::ConditionViolated(ConditionViolated::at(
conflict.position,
)));
}
}
let mut previous = stored.last().map(|event| event.position);
let mut last = None;
for event in events {
let position = self.next_position(previous);
stored.push(SequencedEvent::new(
position,
EventId::new(self.store_id, position),
RECORDED_AT,
event.clone(),
));
previous = Some(position);
last = Some(position);
}
match last {
Some(position) => Ok(position),
None => Err(AppendError::NoEvents),
}
}
async fn head(&self) -> Result<Option<SequencePosition>, Self::Error> {
Ok(self.read_guard().last().map(|event| event.position))
}
async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error> {
Ok(self.read_guard().iter().any(|event| event.id == id))
}
}
#[derive(Debug)]
struct Snapshot(std::vec::IntoIter<SequencedEvent>);
impl Stream for Snapshot {
type Item = Result<SequencedEvent, MemoryStoreError>;
fn poll_next(
self: core::pin::Pin<&mut Self>,
_cx: &mut core::task::Context<'_>,
) -> core::task::Poll<Option<Self::Item>> {
core::task::Poll::Ready(self.get_mut().0.next().map(Ok))
}
}