use crate::error::{BoxError, causes};
use crate::message::SourceMessage;
use std::{error::Error as StdError, fmt, future::Future, pin::Pin};
type CompletionFuture = Pin<Box<dyn Future<Output = Result<(), BoxError>> + Send>>;
#[must_use = "a pending completion must be awaited before acknowledging the input"]
pub struct Completion(Option<CompletionFuture>);
impl Completion {
pub fn done() -> Self {
Self(None)
}
pub fn pending<F>(future: F) -> Self
where
F: Future<Output = Result<(), BoxError>> + Send + 'static,
{
Self(Some(Box::pin(future)))
}
pub fn is_done(&self) -> bool {
self.0.is_none()
}
pub async fn wait(self) -> Result<(), BoxError> {
match self.0 {
Some(future) => future.await,
None => Ok(()),
}
}
}
#[derive(Debug)]
pub struct PublishRejected(BoxError);
impl PublishRejected {
pub fn wrap(error: impl Into<BoxError>) -> BoxError {
Box::new(Self(error.into()))
}
pub fn is(error: &(dyn StdError + 'static)) -> bool {
causes(error).any(|cause| cause.is::<Self>())
}
}
impl fmt::Display for PublishRejected {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("output rejected by its destination")
}
}
impl StdError for PublishRejected {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(self.0.as_ref())
}
}
pub trait Sink<T>: Send + Sync + 'static {
type Prepared: Send + Sync + 'static;
fn prepare(&self, value: T) -> Result<Self::Prepared, BoxError>;
fn prepare_from<M: SourceMessage>(
&self,
value: T,
delivery: &M,
) -> Result<Self::Prepared, BoxError> {
let _ = delivery;
self.prepare(value)
}
fn publish(&self, output: &Self::Prepared)
-> impl Future<Output = Result<(), BoxError>> + Send;
fn submit(
&self,
output: &Self::Prepared,
) -> impl Future<Output = Result<Completion, BoxError>> + Send {
async move {
self.publish(output).await?;
Ok(Completion::done())
}
}
fn close(&self) -> impl Future<Output = Result<(), BoxError>> + Send {
async { Ok(()) }
}
}