use alloc::sync::Arc;
use futures::StreamExt;
use mnesis::{Id, Version};
use crate::PersistedEnvelope;
use crate::catchup::{AllCatchup, StreamCatchup};
use crate::step::Step;
use crate::store::{RawEventStore, Store};
use crate::stream_id::StreamKey;
use crate::subscription_cursor::live_stepped;
use crate::wake::WakeSource;
pub struct Subscription<S> {
store: Arc<S>,
}
impl<S> core::fmt::Debug for Subscription<S> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Subscription").finish_non_exhaustive()
}
}
impl<S> Subscription<S> {
#[must_use]
pub fn new(store: &Store<S>) -> Self {
Self {
store: Arc::clone(store.arc()),
}
}
}
impl<S: RawEventStore + WakeSource> Subscription<S> {
#[allow(
clippy::type_complexity,
reason = "the Step-tagged item is intrinsic to the contract; an alias would \
hide the `impl Stream`/`use<>` capture the API depends on"
)]
pub fn subscribe<I: Id>(
&self,
id: &I,
from: Option<Version>,
) -> Result<
impl futures_core::Stream<Item = Result<Step<PersistedEnvelope>, <S as RawEventStore>::Error>>
+ Send
+ use<S, I>,
<S as WakeSource>::Error,
>
where
<S as RawEventStore>::Stream: Unpin,
{
let catchup = StreamCatchup::new(Arc::clone(&self.store), id.as_ref())?;
Ok(live_stepped(catchup, from).map(|item| item.map(|step| step.map(|(_, env)| env))))
}
#[allow(
clippy::type_complexity,
reason = "the position-tagged `$all` Step item is intrinsic to the contract; an \
alias would hide the `impl Stream`/`use<>` capture the API depends on"
)]
pub fn subscribe_all(
&self,
from: Option<<S as RawEventStore>::AllPosition>,
) -> Result<
impl futures_core::Stream<
Item = Result<
Step<(
<S as RawEventStore>::AllPosition,
StreamKey,
PersistedEnvelope,
)>,
<S as RawEventStore>::Error,
>,
> + Send
+ use<S>,
<S as WakeSource>::Error,
>
where
<S as RawEventStore>::AllStream: Unpin,
{
let catchup = AllCatchup::new(Arc::clone(&self.store))?;
Ok(live_stepped(catchup, from))
}
}