use std::error::Error as StdError;
use std::future::Future;
use crate::codec::Codec;
use crate::{HeaderMap, OutgoingFor, PayloadForm, Publisher, Transaction};
pub trait PublishSink: Send {
type Payload: PayloadForm;
type Error: StdError + Send + Sync + 'static;
type Options: Clone + Send + Sync + 'static;
fn send(
&mut self,
msg: OutgoingFor<'_, Self::Payload>,
options: Option<&Self::Options>,
) -> impl Future<Output = Result<(), Self::Error>> + Send;
fn base_headers(&self) -> Option<&HeaderMap> {
None
}
}
impl<P: Publisher + ?Sized> PublishSink for &P {
type Payload = P::Payload;
type Error = P::Error;
type Options = P::Options;
fn send(
&mut self,
msg: OutgoingFor<'_, Self::Payload>,
options: Option<&Self::Options>,
) -> impl Future<Output = Result<(), Self::Error>> + Send {
(**self).publish(msg, options)
}
fn base_headers(&self) -> Option<&HeaderMap> {
(**self).base_headers()
}
}
impl<T: Transaction> PublishSink for &mut T {
type Payload = T::Payload;
type Error = T::Error;
type Options = T::Options;
fn send(
&mut self,
msg: OutgoingFor<'_, Self::Payload>,
options: Option<&Self::Options>,
) -> impl Future<Output = Result<(), Self::Error>> + Send {
(**self).publish(msg, options)
}
fn base_headers(&self) -> Option<&HeaderMap> {
(**self).base_headers()
}
}
#[diagnostic::on_unimplemented(
message = "no codec is available for this publish",
label = "this codec position resolves to nothing",
note = "enable a codec feature on `ruststream` (`json`, `cbor` or `msgpack`), name one for \
this publish with `.with_codec(JsonCodec)`, or give the message type its own bytes \
with `#[derive(Serialized)]` so no codec is needed"
)]
pub trait PublishCodec {
type Codec: Codec;
fn codec(&self) -> &Self::Codec;
}
impl<C: Codec> PublishCodec for &C {
type Codec = C;
fn codec(&self) -> &C {
self
}
}
#[derive(Debug, Clone, Copy, Default)]
pub struct UnnamedCodec {
#[cfg(any(feature = "json", feature = "cbor", feature = "msgpack"))]
resolved: crate::codec::DefaultCodec,
}
impl UnnamedCodec {
#[must_use]
pub fn new() -> Self {
Self::default()
}
}
#[cfg(any(feature = "json", feature = "cbor", feature = "msgpack"))]
impl PublishCodec for UnnamedCodec {
type Codec = crate::codec::DefaultCodec;
fn codec(&self) -> &Self::Codec {
&self.resolved
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct CallCodec<C>(pub(crate) C);
impl<C: Codec> PublishCodec for CallCodec<C> {
type Codec = C;
fn codec(&self) -> &C {
&self.0
}
}