plexus_client/watch.rs
1//! `watch((a, b, c))` — several method streams in, one stream out whose item
2//! is exactly the union of theirs (RETURNS-38).
3//!
4//! ```
5//! use futures::{executor::block_on, stream, StreamExt};
6//! use plexus_client::{watch, Watched3};
7//!
8//! # struct TicketsEvent; struct ChatsEvent; struct DeployEvent;
9//! let tickets = stream::iter(vec![TicketsEvent]);
10//! let chats = stream::iter(vec![ChatsEvent]);
11//! let deployments = stream::iter(vec![DeployEvent]);
12//!
13//! let mut s = watch((tickets, chats, deployments));
14//! block_on(async {
15//! while let Some(it) = s.next().await {
16//! // No wildcard: the item is exactly one of the three.
17//! match it {
18//! Watched3::A(TicketsEvent) => {}
19//! Watched3::B(ChatsEvent) => {}
20//! Watched3::C(DeployEvent) => {}
21//! }
22//! }
23//! });
24//! ```
25//!
26//! Rust has no variadics, so the streams go in as a tuple: [`Watch`] is
27//! implemented for tuples of 2 to 12 streams, each giving its own
28//! `WatchingN` stream of `WatchedN` items — one variant per element, in the
29//! tuple's order, holding that stream's own item unchanged. A one-tuple is
30//! the stream itself.
31//!
32//! # The rules
33//!
34//! | when | then |
35//! |---|---|
36//! | items arrive | they come out as each stream yields them; a stream that is ready is never starved (the merge polls round-robin) |
37//! | one stream ends | it is dropped at once, and the merge goes on; it ends when all have |
38//! | one stream yields an error | it is an item like any other (`Watched3::B(Err(e))` — the variant names its source); the others go on |
39//! | [`Errors::Stop`] ([`watch_with`], or [`WatchingN::stop_on_error`](Watching3::stop_on_error)) | the failing item is the last: every other stream is dropped with it and the merge ends |
40//! | the merge is dropped | every stream it still holds is dropped, once each — over a `WsTransport` that is one `call_unsub` per live subscription |
41//!
42//! Nothing is new on the wire: each stream is the call it already was.
43//!
44//! # The item is exact
45//!
46//! Widening the union does not compile:
47//!
48//! ```compile_fail
49//! use futures::{executor::block_on, stream, StreamExt};
50//! use plexus_client::{watch, Watched3};
51//! struct A; struct B; struct C; struct Wide;
52//! let mut s = watch((stream::iter(vec![A]), stream::iter(vec![B]), stream::iter(vec![C])));
53//! let _: Option<Watched3<Wide, Wide, Wide>> = block_on(s.next());
54//! ```
55//!
56//! Nor does watching nothing:
57//!
58//! ```compile_fail
59//! let _ = plexus_client::watch(());
60//! ```
61//!
62//! A stream that is not `Unpin` (an `async_stream` block, say) goes in
63//! boxed: `Box::pin(s)`. Every generated client stream already is.
64
65use futures_core::stream::{FusedStream, Stream};
66use std::fmt;
67use std::pin::Pin;
68use std::task::{Context, Poll};
69
70/// What the merge does when one of its streams yields an error.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
72pub enum Errors {
73 /// The error is an item, and the other streams go on (the default).
74 #[default]
75 Continue,
76 /// The error is the last item: the merge drops every stream it holds
77 /// and ends.
78 Stop,
79}
80
81/// An item that may be a failure — what [`Errors::Stop`] looks at.
82/// Implemented for `Result`, which every client stream yields.
83pub trait Fallible {
84 fn is_failure(&self) -> bool;
85}
86
87impl<T, E> Fallible for Result<T, E> {
88 fn is_failure(&self) -> bool {
89 self.is_err()
90 }
91}
92
93/// Several streams, given as a tuple, merged into one. See the
94/// [module docs](self).
95pub trait Watch {
96 /// The merged stream.
97 type Watching: Stream;
98 fn watch(self) -> Self::Watching;
99}
100
101/// A merged stream that can be told to end at the first failure.
102pub trait StopOnError {
103 fn stop_on_error(self) -> Self;
104}
105
106/// Merge the streams of a tuple into one: `watch((a, b, c))`.
107///
108/// Its item is `Watched3<A::Item, B::Item, C::Item>` — exactly the three,
109/// tagged by position; `watch((a,))` is `a` itself.
110pub fn watch<W: Watch>(streams: W) -> W::Watching {
111 streams.watch()
112}
113
114/// [`watch`], with the policy for an error said up front.
115pub fn watch_with<W>(streams: W, errors: Errors) -> W::Watching
116where
117 W: Watch,
118 W::Watching: StopOnError,
119{
120 let w = streams.watch();
121 match errors {
122 Errors::Continue => w,
123 Errors::Stop => w.stop_on_error(),
124 }
125}
126
127/// One stream is its own merge: its type unchanged.
128impl<A: Stream> Watch for (A,) {
129 type Watching = A;
130 fn watch(self) -> A {
131 self.0
132 }
133}
134
135macro_rules! watch_arity {
136 ($Watched:ident, $Watching:ident, $n:expr; $( ($V:ident, $f:ident, $i:expr) ),+ ) => {
137 /// One item of a merged stream: which stream it came from (the
138 /// variant, in the tuple's order) and that stream's own item.
139 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
140 pub enum $Watched<$($V),+> {
141 $( $V($V), )+
142 }
143
144 impl<$($V),+> $Watched<$($V),+> {
145 /// The source's position in the tuple, from 0.
146 pub fn index(&self) -> usize {
147 match self {
148 $( $Watched::$V(_) => $i, )+
149 }
150 }
151 }
152
153 impl<$($V: Fallible),+> Fallible for $Watched<$($V),+> {
154 fn is_failure(&self) -> bool {
155 match self {
156 $( $Watched::$V(x) => x.is_failure(), )+
157 }
158 }
159 }
160
161 /// The merge of a tuple of streams; see [`watch`].
162 #[must_use = "streams do nothing unless polled"]
163 pub struct $Watching<$($V: Stream),+> {
164 $( $f: Option<$V>, )+
165 /// The stream polled first next time — round-robin, so a busy
166 /// stream cannot starve the others.
167 next: usize,
168 stop_if: Option<fn(&$Watched<$($V::Item),+>) -> bool>,
169 ended: bool,
170 }
171
172 impl<$($V: Stream),+> $Watching<$($V),+> {
173 /// End at the first failure: it is delivered as the last item,
174 /// and every other stream is dropped with it.
175 pub fn stop_on_error(mut self) -> Self
176 where
177 $( $V::Item: Fallible, )+
178 {
179 self.stop_if = Some(|w| w.is_failure());
180 self
181 }
182
183 /// How many streams the merge still holds: each is let go when
184 /// it is seen to end (polled to its end), or with the merge.
185 pub fn live(&self) -> usize {
186 0 $( + usize::from(self.$f.is_some()) )+
187 }
188
189 fn end(&mut self) {
190 self.ended = true;
191 $( self.$f = None; )+
192 }
193 }
194
195 impl<$($V: Stream),+> StopOnError for $Watching<$($V),+>
196 where
197 $( $V::Item: Fallible, )+
198 {
199 fn stop_on_error(self) -> Self {
200 $Watching::stop_on_error(self)
201 }
202 }
203
204 impl<$($V: Stream),+> fmt::Debug for $Watching<$($V),+> {
205 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
206 f.debug_struct(stringify!($Watching))
207 .field("live", &self.live())
208 .field("stop_on_error", &self.stop_if.is_some())
209 .field("ended", &self.ended)
210 .finish()
211 }
212 }
213
214 impl<$($V: Stream + Unpin),+> Watch for ($($V,)+) {
215 type Watching = $Watching<$($V),+>;
216 #[allow(non_snake_case)]
217 fn watch(self) -> Self::Watching {
218 let ($($V,)+) = self;
219 $Watching {
220 $( $f: Some($V), )+
221 next: 0,
222 stop_if: None,
223 ended: false,
224 }
225 }
226 }
227
228 impl<$($V: Stream + Unpin),+> Stream for $Watching<$($V),+> {
229 type Item = $Watched<$($V::Item),+>;
230
231 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
232 let this = self.get_mut();
233 if this.ended {
234 return Poll::Ready(None);
235 }
236 let start = this.next;
237 this.next = (start + 1) % $n;
238 for k in 0..$n {
239 let i = (start + k) % $n;
240 $(
241 if i == $i {
242 if let Some(s) = this.$f.as_mut() {
243 match Pin::new(s).poll_next(cx) {
244 Poll::Ready(Some(x)) => {
245 let item = $Watched::$V(x);
246 if this.stop_if.is_some_and(|stop| stop(&item)) {
247 this.end();
248 }
249 return Poll::Ready(Some(item));
250 }
251 // Ended: let it go now, not when the merge goes.
252 Poll::Ready(None) => this.$f = None,
253 Poll::Pending => {}
254 }
255 }
256 }
257 )+
258 }
259 if this.live() == 0 {
260 this.ended = true;
261 Poll::Ready(None)
262 } else {
263 Poll::Pending
264 }
265 }
266
267 fn size_hint(&self) -> (usize, Option<usize>) {
268 let mut lo = 0usize;
269 let mut hi = Some(0usize);
270 $(
271 if let Some(s) = &self.$f {
272 let (l, h) = s.size_hint();
273 lo = lo.saturating_add(l);
274 hi = match (hi, h) {
275 (Some(a), Some(b)) => a.checked_add(b),
276 _ => None,
277 };
278 }
279 )+
280 if self.stop_if.is_some() {
281 lo = lo.min(1);
282 }
283 (lo, hi)
284 }
285 }
286
287 impl<$($V: Stream + Unpin),+> FusedStream for $Watching<$($V),+> {
288 fn is_terminated(&self) -> bool {
289 self.ended
290 }
291 }
292 };
293}
294
295watch_arity!(Watched2, Watching2, 2; (A, a, 0), (B, b, 1));
296watch_arity!(Watched3, Watching3, 3; (A, a, 0), (B, b, 1), (C, c, 2));
297watch_arity!(Watched4, Watching4, 4; (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3));
298watch_arity!(Watched5, Watching5, 5; (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3), (E, e, 4));
299watch_arity!(Watched6, Watching6, 6; (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3), (E, e, 4), (F, f, 5));
300watch_arity!(Watched7, Watching7, 7; (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3), (E, e, 4), (F, f, 5), (G, g, 6));
301watch_arity!(Watched8, Watching8, 8;
302 (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3), (E, e, 4), (F, f, 5), (G, g, 6), (H, h, 7));
303watch_arity!(Watched9, Watching9, 9;
304 (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3), (E, e, 4), (F, f, 5), (G, g, 6), (H, h, 7), (I, i_, 8));
305watch_arity!(Watched10, Watching10, 10;
306 (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3), (E, e, 4), (F, f, 5), (G, g, 6), (H, h, 7), (I, i_, 8),
307 (J, j, 9));
308watch_arity!(Watched11, Watching11, 11;
309 (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3), (E, e, 4), (F, f, 5), (G, g, 6), (H, h, 7), (I, i_, 8),
310 (J, j, 9), (K, k, 10));
311watch_arity!(Watched12, Watching12, 12;
312 (A, a, 0), (B, b, 1), (C, c, 2), (D, d, 3), (E, e, 4), (F, f, 5), (G, g, 6), (H, h, 7), (I, i_, 8),
313 (J, j, 9), (K, k, 10), (L, l, 11));