Skip to main content

ice_rpc_rx/
event.rs

1//! The event vocabulary of a stream, and its producer side.
2//!
3//! [`Event`] is what a consumer observes, [`ObservableError`] is the single
4//! error type it may carry, and [`Sender`] is the producer side of a local
5//! channel. Nothing here knows about the wire: framing and serialization belong
6//! to the transport, which converts these events to its own representation.
7
8use crate::error::RpcError;
9
10/// The single error type of the whole streaming API.
11///
12/// Follows the Rx pattern: a single `error` channel whose payload distinguishes
13/// a **business** error (authored by the service) from a **technical** one
14/// (raised by the framework/transport). [`ObservableError::Empty`] is a
15/// pull-side artefact and never travels over the wire.
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum ObservableError<E> {
18    /// Business error emitted by the service.
19    Business(E),
20    /// Technical RPC error (transport, discovery, protocol, ...).
21    Technical(RpcError),
22    /// The stream ended without emitting any value.
23    Empty,
24}
25
26impl<E> ObservableError<E> {
27    /// Returns `true` when this is a technical error.
28    #[inline]
29    pub fn is_technical(&self) -> bool {
30        matches!(self, ObservableError::Technical(_))
31    }
32
33    /// Returns `true` when this is a business error.
34    #[inline]
35    pub fn is_business(&self) -> bool {
36        matches!(self, ObservableError::Business(_))
37    }
38
39    /// Returns the inner business error, if any.
40    #[inline]
41    pub fn as_business(&self) -> Option<&E> {
42        match self {
43            ObservableError::Business(e) => Some(e),
44            ObservableError::Technical(_) | ObservableError::Empty => None,
45        }
46    }
47
48    /// Returns the inner technical error, if any.
49    #[inline]
50    pub fn as_technical(&self) -> Option<&RpcError> {
51        match self {
52            ObservableError::Technical(e) => Some(e),
53            ObservableError::Business(_) | ObservableError::Empty => None,
54        }
55    }
56}
57
58impl<E: std::fmt::Display> std::fmt::Display for ObservableError<E> {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        match self {
61            ObservableError::Business(e) => write!(f, "{e}"),
62            ObservableError::Technical(e) => write!(f, "{e}"),
63            ObservableError::Empty => write!(f, "stream ended without a value"),
64        }
65    }
66}
67
68impl<E: std::fmt::Debug + std::fmt::Display> std::error::Error for ObservableError<E> {}
69
70/// Event emitted by a stream, as observed by consumers.
71///
72/// This is the user-facing event type: a single `Error` variant carries both
73/// business and technical failures ([`ObservableError`]). Whatever single-sample
74/// optimization a source applies internally is normalized away before a consumer
75/// sees it (see [`Observable::recv`](crate::Observable::recv)).
76#[derive(Debug, Clone, PartialEq, Eq)]
77pub enum Event<T, E> {
78    /// Intermediate business value.
79    Next(T),
80    /// Normal end of the stream.
81    Complete,
82    /// Terminal error (business or technical).
83    Error(ObservableError<E>),
84}
85
86impl<T, E> Event<T, E> {
87    /// Returns `true` if this event terminates the stream.
88    #[inline]
89    pub fn is_terminal(&self) -> bool {
90        matches!(self, Event::Complete | Event::Error(_))
91    }
92}
93
94/// Producer-side sender of stream events.
95///
96/// Producers emit through the ergonomic methods [`Sender::send_next`],
97/// [`Sender::send_complete`], [`Sender::send_complete_with`] and
98/// [`Sender::send_error`]. [`Sender::send_event`] is a passthrough used by the
99/// transport relays to forward any [`Event`], including technical errors.
100///
101/// The channel carries [`Event`]s, not wire samples: the wire vocabulary belongs
102/// to the transport, which is the only layer that frames a sample, stamps its
103/// `EventKind` and serializes it. The single-sample optimization is preserved
104/// across that boundary by [`Sender::send_complete_with`], which enqueues
105/// `Next(value)` then `Complete`: the transport bridge folds the pair back into
106/// one `CompleteWith` sample.
107pub struct Sender<T, E> {
108    /// Shared with `channel` in [`super::stream`].
109    pub(crate) inner: async_channel::Sender<Event<T, E>>,
110}
111
112impl<T, E> Clone for Sender<T, E> {
113    fn clone(&self) -> Self {
114        Self {
115            inner: self.inner.clone(),
116        }
117    }
118}
119
120impl<T, E> Sender<T, E> {
121    /// Sends a business value.
122    #[inline]
123    pub async fn send_next(&self, value: T) -> Result<(), async_channel::SendError<Event<T, E>>> {
124        self.inner.send(Event::Next(value)).await
125    }
126
127    /// Sends a normal end of stream.
128    #[inline]
129    pub async fn send_complete(&self) -> Result<(), async_channel::SendError<Event<T, E>>> {
130        self.inner.send(Event::Complete).await
131    }
132
133    /// Sends a single terminal value (producer shortcut, one wire sample).
134    ///
135    /// Enqueues `Next(value)` then `Complete`. The pair travels as two channel
136    /// events and is folded back into a single wire sample by the transport
137    /// bridge, so the sample a subscriber receives is unchanged. A caller that
138    /// uses this on a **bounded** channel must leave room for two events.
139    #[inline]
140    pub async fn send_complete_with(
141        &self,
142        value: T,
143    ) -> Result<(), async_channel::SendError<Event<T, E>>> {
144        self.inner.send(Event::Next(value)).await?;
145        self.inner.send(Event::Complete).await
146    }
147
148    /// Sends a business error.
149    #[inline]
150    pub async fn send_error(&self, err: E) -> Result<(), async_channel::SendError<Event<T, E>>> {
151        self.inner
152            .send(Event::Error(ObservableError::Business(err)))
153            .await
154    }
155
156    /// Forwards any consumer [`Event`] (transport/relay passthrough).
157    ///
158    /// The only way a technical error transits.
159    #[inline]
160    pub async fn send_event(
161        &self,
162        event: Event<T, E>,
163    ) -> Result<(), async_channel::SendError<Event<T, E>>> {
164        self.inner.send(event).await
165    }
166
167    /// Non-blocking variant of [`Sender::send_next`].
168    #[inline]
169    pub fn try_send_next(&self, value: T) -> Result<(), async_channel::TrySendError<Event<T, E>>> {
170        self.inner.try_send(Event::Next(value))
171    }
172
173    /// Non-blocking variant of [`Sender::send_complete`].
174    #[inline]
175    pub fn try_send_complete(&self) -> Result<(), async_channel::TrySendError<Event<T, E>>> {
176        self.inner.try_send(Event::Complete)
177    }
178
179    /// Non-blocking variant of [`Sender::send_complete_with`].
180    ///
181    /// Both events go through the same non-blocking send, so a channel with room
182    /// for one event only leaves a `Next` queued when the `Complete` is rejected:
183    /// a caller that swallows that error hands its consumer an unterminated
184    /// stream. Treat any failure here as fatal for the response.
185    #[inline]
186    pub fn try_send_complete_with(
187        &self,
188        value: T,
189    ) -> Result<(), async_channel::TrySendError<Event<T, E>>> {
190        self.inner.try_send(Event::Next(value))?;
191        self.inner.try_send(Event::Complete)
192    }
193
194    /// Non-blocking variant of [`Sender::send_error`].
195    #[inline]
196    pub fn try_send_error(&self, err: E) -> Result<(), async_channel::TrySendError<Event<T, E>>> {
197        self.inner
198            .try_send(Event::Error(ObservableError::Business(err)))
199    }
200
201    /// Non-blocking variant of [`Sender::send_event`].
202    #[inline]
203    pub fn try_send_event(
204        &self,
205        event: Event<T, E>,
206    ) -> Result<(), async_channel::TrySendError<Event<T, E>>> {
207        self.inner.try_send(event)
208    }
209
210    /// Returns `true` once the receiving end is gone.
211    ///
212    /// A multicast relay uses it to drop the subscribers that stopped
213    /// listening, instead of keeping a sender that can deliver nothing. Gated
214    /// behind `operators`: only the `Subject` relay calls it.
215    #[cfg(feature = "operators")]
216    #[inline]
217    pub(crate) fn is_closed(&self) -> bool {
218        self.inner.is_closed()
219    }
220}