use core::future::Future;
use std::sync::Arc;
use futures_core::Stream;
use happenstance_core::{
AppendCondition, AppendError, Authority, Checkpoint, CommitError, Event, EventId, EventType,
MemoryEventStore, MemoryProjectionStore, ProjectionId, ProjectionProbe, Query, QueryItem,
ReadOptions, ResetError, SendEventStore, SendProjectionStore, SequencePosition, SequencedEvent,
Tags,
};
use crate::contract::{Capability, Fixture, ProjectionFixture};
#[must_use]
pub fn event(event_type: &str) -> Event {
Event::new(event_type, &b"{}"[..]).expect("valid event type")
}
#[must_use]
pub fn tagged_event(event_type: &str, tags: &[(&str, &str)]) -> Event {
event(event_type).with_tags(self::tags(tags))
}
#[must_use]
pub fn event_with_payload(event_type: &str, payload: &'static [u8]) -> Event {
Event::new(event_type, payload).expect("valid event type")
}
#[must_use]
pub fn event_with_owned_payload(event_type: &str, payload: Vec<u8>) -> Event {
Event::new(event_type, payload).expect("valid event type")
}
#[must_use]
pub fn tags(pairs: &[(&str, &str)]) -> Tags {
Tags::from_pairs(pairs.iter().copied()).expect("valid tags")
}
#[must_use]
pub fn event_type(value: &str) -> EventType {
EventType::new(value).expect("valid event type")
}
#[must_use]
pub fn query_of_types(types: &[&str]) -> Query {
Query::from_item(QueryItem::of_types(types.iter().copied()).expect("valid types"))
}
#[must_use]
pub fn query_tagged(pairs: &[(&str, &str)]) -> Query {
Query::from_item(QueryItem::tagged(tags(pairs)).expect("non-empty tags"))
}
#[must_use]
pub fn query_of(types: &[&str], pairs: &[(&str, &str)]) -> Query {
Query::from_item(QueryItem::new(types.iter().copied(), tags(pairs)).expect("valid query item"))
}
#[must_use]
pub fn item_of_types(types: &[&str]) -> QueryItem {
QueryItem::of_types(types.iter().copied()).expect("valid types")
}
#[must_use]
pub fn item_tagged(pairs: &[(&str, &str)]) -> QueryItem {
QueryItem::tagged(tags(pairs)).expect("non-empty tags")
}
#[must_use]
pub fn query_of_items(items: impl IntoIterator<Item = QueryItem>) -> Query {
Query::from_items(items).expect("non-empty query")
}
#[must_use]
pub fn condition(query: Query) -> AppendCondition {
AppendCondition::new(query)
}
#[must_use]
pub fn condition_after(query: Query, position: u64) -> AppendCondition {
AppendCondition::new(query).after(SequencePosition::new(position).expect("non-zero position"))
}
#[derive(Debug, Clone)]
pub struct MemoryHandle(Arc<MemoryEventStore>);
impl SendEventStore for MemoryHandle {
type Error = <MemoryEventStore as SendEventStore>::Error;
fn read(
&self,
query: &Query,
options: ReadOptions,
) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> + Send {
self.0.read(query, options)
}
async fn append(
&self,
events: &[Event],
condition: Option<&AppendCondition>,
) -> Result<SequencePosition, AppendError<Self::Error>> {
self.0.append(events, condition).await
}
async fn head(&self) -> Result<Option<SequencePosition>, Self::Error> {
self.0.head().await
}
async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error> {
self.0.contains_event_id(id).await
}
}
#[derive(Debug, Default)]
pub struct MemoryFixture(Arc<MemoryEventStore>);
impl MemoryFixture {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn sharing(store: Arc<MemoryEventStore>) -> Self {
Self(store)
}
}
impl Fixture for MemoryFixture {
type Store = MemoryHandle;
const SECOND_HANDLE: Capability = Capability::SUPPORTED;
const REOPEN: Capability = Capability::declined(
"MemoryEventStore is a Vec behind an RwLock, so there is no durable \
medium to reopen over: discarding process state is indistinguishable \
from discarding the events",
);
const MID_BATCH_FAULT: Capability = Capability::declined(
"MemoryEventStore appends by extending one Vec under one write lock, so there is no moment between two rows of a batch at which a fault could fire; a wrapper can fail the whole call and nothing can fail it part way through",
);
const READ_FAULT: Capability = Capability::declined(
"MemoryEventStore reads by iterating a Vec it already holds, so there is \
no fetch part way through a read to fail; injecting one means wrapping \
the store, which is what FaultyStore is for",
);
fn connect(&self) -> impl Future<Output = Self::Store> {
core::future::ready(MemoryHandle(Arc::clone(&self.0)))
}
}
#[derive(Debug, Clone)]
pub struct MemoryProjectionHandle(Arc<MemoryProjectionStore>);
impl MemoryProjectionHandle {
#[must_use]
pub fn new(store: Arc<MemoryProjectionStore>) -> Self {
Self(store)
}
}
impl SendProjectionStore for MemoryProjectionHandle {
type Error = <MemoryProjectionStore as SendProjectionStore>::Error;
type Batch = <MemoryProjectionStore as SendProjectionStore>::Batch;
async fn begin(&self) -> Result<Self::Batch, Self::Error> {
self.0.begin().await
}
async fn checkpoint(&self, id: &ProjectionId) -> Result<Checkpoint, Self::Error> {
self.0.checkpoint(id).await
}
async fn commit(
&self,
batch: Self::Batch,
id: &ProjectionId,
position: SequencePosition,
authority: Authority,
) -> Result<(), CommitError<Self::Error>> {
self.0.commit(batch, id, position, authority).await
}
async fn reset(
&self,
batch: Self::Batch,
id: &ProjectionId,
) -> Result<(), ResetError<Self::Error>> {
self.0.reset(batch, id).await
}
async fn rollback(&self, batch: Self::Batch) -> Result<(), Self::Error> {
self.0.rollback(batch).await
}
}
impl ProjectionProbe for MemoryProjectionHandle {
const READS_THROUGH_BATCH: bool = true;
async fn probe_write(
&self,
batch: &mut Self::Batch,
key: &str,
value: u64,
) -> Result<(), Self::Error> {
self.0.probe_write(batch, key, value).await
}
async fn probe_delete_all(&self, batch: &mut Self::Batch) -> Result<(), Self::Error> {
self.0.probe_delete_all(batch).await
}
async fn probe_read(&self, key: &str) -> Result<Option<u64>, Self::Error> {
self.0.probe_read(key).await
}
async fn probe_read_through(
&self,
batch: &mut Self::Batch,
key: &str,
) -> Result<Option<u64>, Self::Error> {
self.0.probe_read_through(batch, key).await
}
}
#[derive(Debug, Default)]
pub struct MemoryProjectionFixture(Arc<MemoryProjectionStore>);
impl MemoryProjectionFixture {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
impl ProjectionFixture for MemoryProjectionFixture {
type Store = MemoryProjectionHandle;
const SECOND_HANDLE: Capability = Capability::SUPPORTED;
const RESET_REFUSAL: Capability = Capability::declined(
"MemoryProjectionStore holds no protection policy, so there is no \
projection it could decline to reset: `reset` returns `Refused` on no \
path at all, and a store that refused arbitrarily would be a worse \
oracle",
);
const COMMIT_FAULT: Capability = Capability::declined(
"MemoryProjectionStore applies the read-model writes and the checkpoint \
under one write lock, so it has no write that can be made to fail and \
no moment between the two halves to fail in; arming a fault would mean \
building fault injection into a shipped store to satisfy a test",
);
fn connect(&self) -> impl Future<Output = Self::Store> {
core::future::ready(MemoryProjectionHandle(Arc::clone(&self.0)))
}
}
#[cfg(all(feature = "proptest", not(target_arch = "wasm32")))]
#[cfg_attr(docsrs, doc(cfg(feature = "proptest")))]
pub use proptest;
#[cfg(all(feature = "proptest", not(target_arch = "wasm32")))]
#[cfg_attr(docsrs, doc(cfg(feature = "proptest")))]
pub mod strategies {
use happenstance_core::{Event, EventType, Query, QueryItem, Tag, Tags};
use proptest::prelude::{Strategy, prop, prop_oneof};
pub fn any_tag() -> impl Strategy<Value = Tag> {
prop::sample::select(vec!["a", "b", "c", "d", "e"])
.prop_map(|value| Tag::new(value).expect("valid tag"))
}
pub fn any_tags() -> impl Strategy<Value = Tags> {
prop::collection::vec(any_tag(), 0..6).prop_map(|tags| tags.into_iter().collect())
}
pub fn any_event_type() -> impl Strategy<Value = EventType> {
prop::sample::select(vec!["A", "B", "C"])
.prop_map(|value| EventType::new(value).expect("valid event type"))
}
pub fn any_query_item() -> impl Strategy<Value = QueryItem> {
(prop::collection::vec(any_event_type(), 0..3), any_tags())
.prop_filter_map("an item must constrain types or tags", |(types, tags)| {
QueryItem::new(types, tags).ok()
})
}
pub fn any_query() -> impl Strategy<Value = Query> {
prop_oneof![
1 => prop::strategy::Just(Query::all()),
4 => prop::collection::vec(any_query_item(), 1..4)
.prop_map(|items| Query::from_items(items).expect("at least one item")),
]
}
pub fn any_event() -> impl Strategy<Value = Event> {
(
any_event_type(),
any_tags(),
prop::sample::select(vec![&b"{}"[..], &b"[1,2]"[..], &b"payload"[..]]),
prop::option::of(prop::sample::select(vec![
&b"trace-id"[..],
&b"causation"[..],
])),
)
.prop_map(|(event_type, tags, data, metadata)| {
let event = Event::new(event_type.as_str().to_owned(), data)
.expect("an EventType is already valid")
.with_tags(tags);
match metadata {
Some(metadata) => event.with_metadata(metadata),
None => event,
}
})
}
}