use core::pin::Pin;
use core::sync::atomic::{AtomicU32, Ordering};
use core::task::{Context, Poll};
use std::sync::Arc;
use futures_core::Stream;
use happenstance_core::{
AppendCondition, AppendError, ConditionViolated, Event, EventId, EventStore, Query,
ReadOptions, SendEventStore, SequencePosition, SequencedEvent,
};
#[derive(Debug, Default)]
struct Armed {
violate: AtomicU32,
fail_read: AtomicU32,
contend: AtomicU32,
}
impl Armed {
fn take(counter: &AtomicU32) -> bool {
counter
.try_update(Ordering::Relaxed, Ordering::Relaxed, |remaining| {
remaining.checked_sub(1)
})
.is_ok()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FaultyStoreError<E> {
Injected,
Contended,
Store(E),
}
impl<E: core::fmt::Display> core::fmt::Display for FaultyStoreError<E> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Injected => f.write_str(
"the test fixture injected this failure; nothing underneath it went wrong",
),
Self::Contended => f.write_str(
"the test fixture refused this append as a contended store would; \
nothing underneath it went wrong and a retry may succeed",
),
Self::Store(err) => write!(f, "the wrapped store failed: {err}"),
}
}
}
impl<E: core::error::Error + 'static> core::error::Error for FaultyStoreError<E> {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Injected | Self::Contended => None,
Self::Store(err) => Some(err),
}
}
}
#[derive(Debug)]
struct InjectedRead<St> {
injected: bool,
inner: Pin<Box<St>>,
}
impl<St, E> Stream for InjectedRead<St>
where
St: Stream<Item = Result<SequencedEvent, E>>,
{
type Item = Result<SequencedEvent, FaultyStoreError<E>>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = self.get_mut();
if this.injected {
this.injected = false;
return Poll::Ready(Some(Err(FaultyStoreError::Injected)));
}
this.inner
.as_mut()
.poll_next(cx)
.map(|item| item.map(|event| event.map_err(FaultyStoreError::Store)))
}
}
#[derive(Debug, Clone)]
pub struct FaultyStore<S: EventStore> {
inner: S,
armed: Arc<Armed>,
}
#[derive(Debug, Clone)]
pub struct SendFaultyStore<S: SendEventStore> {
inner: S,
armed: Arc<Armed>,
}
impl<S: EventStore> FaultyStore<S> {
#[must_use]
pub fn new(inner: S) -> Self {
Self {
inner,
armed: Arc::new(Armed::default()),
}
}
#[must_use]
pub fn violate_next(self, n: u32) -> Self {
self.armed.violate.store(n, Ordering::Relaxed);
self
}
#[must_use]
pub fn fail_next_read(self, n: u32) -> Self {
self.armed.fail_read.store(n, Ordering::Relaxed);
self
}
#[must_use]
pub fn contend_next(self, n: u32) -> Self {
self.armed.contend.store(n, Ordering::Relaxed);
self
}
}
impl<S: SendEventStore> SendFaultyStore<S> {
#[must_use]
pub fn new(inner: S) -> Self {
Self {
inner,
armed: Arc::new(Armed::default()),
}
}
#[must_use]
pub fn violate_next(self, n: u32) -> Self {
self.armed.violate.store(n, Ordering::Relaxed);
self
}
#[must_use]
pub fn fail_next_read(self, n: u32) -> Self {
self.armed.fail_read.store(n, Ordering::Relaxed);
self
}
#[must_use]
pub fn contend_next(self, n: u32) -> Self {
self.armed.contend.store(n, Ordering::Relaxed);
self
}
}
impl<S: EventStore> EventStore for FaultyStore<S> {
type Error = FaultyStoreError<S::Error>;
fn read(
&self,
query: &Query,
options: ReadOptions,
) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> {
InjectedRead {
injected: take_read_failure(&self.armed),
inner: Box::pin(EventStore::read(&self.inner, query, options)),
}
}
async fn append(
&self,
events: &[Event],
condition: Option<&AppendCondition>,
) -> Result<SequencePosition, AppendError<Self::Error>> {
if take_contention(&self.armed) {
return Err(injected_contention());
}
if take_violation(&self.armed) {
return Err(injected_violation());
}
EventStore::append(&self.inner, events, condition)
.await
.map_err(|err| err.map_store(FaultyStoreError::Store))
}
async fn head(&self) -> Result<Option<SequencePosition>, Self::Error> {
EventStore::head(&self.inner)
.await
.map_err(FaultyStoreError::Store)
}
async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error> {
EventStore::contains_event_id(&self.inner, id)
.await
.map_err(FaultyStoreError::Store)
}
}
impl<S: SendEventStore + Sync> SendEventStore for SendFaultyStore<S> {
type Error = FaultyStoreError<S::Error>;
fn read(
&self,
query: &Query,
options: ReadOptions,
) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> + Send {
InjectedRead {
injected: take_read_failure(&self.armed),
inner: Box::pin(SendEventStore::read(&self.inner, query, options)),
}
}
async fn append(
&self,
events: &[Event],
condition: Option<&AppendCondition>,
) -> Result<SequencePosition, AppendError<Self::Error>> {
if take_contention(&self.armed) {
return Err(injected_contention());
}
if take_violation(&self.armed) {
return Err(injected_violation());
}
SendEventStore::append(&self.inner, events, condition)
.await
.map_err(|err| err.map_store(FaultyStoreError::Store))
}
async fn head(&self) -> Result<Option<SequencePosition>, Self::Error> {
SendEventStore::head(&self.inner)
.await
.map_err(FaultyStoreError::Store)
}
async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error> {
SendEventStore::contains_event_id(&self.inner, id)
.await
.map_err(FaultyStoreError::Store)
}
}
fn injected_violation<E>() -> AppendError<E> {
AppendError::ConditionViolated(ConditionViolated::unspecified())
}
fn injected_contention<E>() -> AppendError<FaultyStoreError<E>> {
AppendError::Busy(FaultyStoreError::Contended)
}
fn take_contention(armed: &Armed) -> bool {
Armed::take(&armed.contend)
}
fn take_read_failure(armed: &Armed) -> bool {
Armed::take(&armed.fail_read)
}
fn take_violation(armed: &Armed) -> bool {
Armed::take(&armed.violate)
}