Skip to main content

wse_client/
events.rs

1//! The client as a stream: messages and events in one queue, for an
2//! application that reads them in a loop.
3
4use std::collections::VecDeque;
5use std::pin::Pin;
6use std::task::{Context, Poll};
7
8use tokio::sync::mpsc;
9
10use crate::client::Client;
11use crate::config::Config;
12use crate::delivery;
13use crate::error::Error;
14use crate::handler::{Event, Handler};
15use crate::message::{Message, OwnedMessage};
16
17/// What the [`Events`] stream yields.
18#[derive(Clone, Debug)]
19#[non_exhaustive]
20pub enum Incoming {
21    Message(OwnedMessage),
22    Event(Event),
23    /// Bytes the server application sent as they are.
24    Binary(bytes::Bytes),
25}
26
27/// What the server sends, in order. While the application does not read,
28/// the client stops reading too and the server holds back; in the browser,
29/// which cannot hold a WebSocket back, what comes waits in memory.
30///
31/// The delivery ([`Config::delivery`]) sees what is read in the order it is
32/// read: a message read before the events show another user is the last
33/// user's, and a topic not continuous holds its messages here until
34/// [`Client::resynced`].
35pub struct Events {
36    rx: Receiver,
37    gate: delivery::Shared,
38    /// Says that the gate made something (held messages handed on).
39    wake: mpsc::UnboundedReceiver<()>,
40}
41
42impl std::fmt::Debug for Events {
43    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
44        f.debug_struct("Events").finish_non_exhaustive()
45    }
46}
47
48#[cfg(not(target_arch = "wasm32"))]
49type Sender = mpsc::Sender<Incoming>;
50#[cfg(not(target_arch = "wasm32"))]
51type Receiver = mpsc::Receiver<Incoming>;
52#[cfg(target_arch = "wasm32")]
53type Sender = mpsc::UnboundedSender<Incoming>;
54#[cfg(target_arch = "wasm32")]
55type Receiver = mpsc::UnboundedReceiver<Incoming>;
56
57impl Events {
58    /// The next message or event; `None` once the client stopped and
59    /// everything was read.
60    pub async fn next(&mut self) -> Option<Incoming> {
61        futures_util::future::poll_fn(|cx| self.poll(cx)).await
62    }
63
64    /// What came already, without waiting: None when nothing is waiting
65    /// now (or the stream ended).
66    pub fn try_next(&mut self) -> Option<Incoming> {
67        while self.wake.try_recv().is_ok() {}
68        loop {
69            if let Some(item) = delivery::lock(&self.gate).take_out() {
70                return Some(item);
71            }
72            let incoming = self.rx.try_recv().ok()?;
73            if let Some(item) = self.pass(incoming) {
74                return Some(item);
75            }
76        }
77    }
78
79    /// One item read, through the delivery's gate: None when it holds it.
80    /// Taken and passed without a wait, so a read given up loses nothing.
81    fn pass(&mut self, incoming: Incoming) -> Option<Incoming> {
82        let mut gate = delivery::lock(&self.gate);
83        match incoming {
84            Incoming::Message(message) => gate.owned(message).map(Incoming::Message),
85            Incoming::Event(event) => {
86                gate.event(&event);
87                Some(Incoming::Event(event))
88            }
89            binary => Some(binary),
90        }
91    }
92
93    fn poll(&mut self, cx: &mut Context<'_>) -> Poll<Option<Incoming>> {
94        loop {
95            // What the gate made comes first: it is older than what waits.
96            if let Some(item) = delivery::lock(&self.gate).take_out() {
97                return Poll::Ready(Some(item));
98            }
99            // A wake only says to look again; its waker stays registered.
100            while let Poll::Ready(Some(())) = self.wake.poll_recv(cx) {}
101            match self.rx.poll_recv(cx) {
102                Poll::Ready(Some(incoming)) => {
103                    if let Some(item) = self.pass(incoming) {
104                        return Poll::Ready(Some(item));
105                    }
106                }
107                Poll::Ready(None) => return Poll::Ready(delivery::lock(&self.gate).take_out()),
108                Poll::Pending => {
109                    // Made while the queue was looked at.
110                    return match delivery::lock(&self.gate).take_out() {
111                        Some(item) => Poll::Ready(Some(item)),
112                        None => Poll::Pending,
113                    };
114                }
115            }
116        }
117    }
118}
119
120impl futures_util::Stream for Events {
121    type Item = Incoming;
122
123    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Incoming>> {
124        self.poll(cx)
125    }
126}
127
128/// How many the stream holds before the client stops reading.
129#[cfg(not(target_arch = "wasm32"))]
130const QUEUE: usize = 1024;
131
132/// Connects, and returns the client with the stream of what the server
133/// sends. See [`Client::connect`].
134pub async fn connect(config: Config) -> Result<(Client, Events), Error> {
135    with_events(config, true).await
136}
137
138/// Starts, and returns at once the client with the stream of what the
139/// server sends: the connection is made in the background. See
140/// [`Client::start`].
141pub async fn start(config: Config) -> Result<(Client, Events), Error> {
142    with_events(config, false).await
143}
144
145async fn with_events(config: Config, wait: bool) -> Result<(Client, Events), Error> {
146    #[cfg(not(target_arch = "wasm32"))]
147    let (tx, rx) = mpsc::channel(QUEUE);
148    #[cfg(target_arch = "wasm32")]
149    let (tx, rx) = mpsc::unbounded_channel();
150    let queue = Queue {
151        tx,
152        waiting: VecDeque::new(),
153    };
154    let (wake_tx, wake) = mpsc::unbounded_channel();
155    let (client, gate) = Client::launch(config, |_| queue, Some(wake_tx), wait).await?;
156    Ok((client, Events { rx, gate, wake }))
157}
158
159/// A handler that puts everything in the stream's queue.
160struct Queue {
161    tx: Sender,
162    /// What did not fit; read is held until it does.
163    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
164    waiting: VecDeque<Incoming>,
165}
166
167impl Queue {
168    #[cfg(not(target_arch = "wasm32"))]
169    fn push(&mut self, item: Incoming) {
170        if !self.waiting.is_empty() {
171            self.waiting.push_back(item);
172            return;
173        }
174        match self.tx.try_send(item) {
175            Ok(()) => {}
176            Err(mpsc::error::TrySendError::Full(item)) => self.waiting.push_back(item),
177            // Nobody reads the stream any more.
178            Err(mpsc::error::TrySendError::Closed(_)) => {}
179        }
180    }
181
182    #[cfg(target_arch = "wasm32")]
183    fn push(&mut self, item: Incoming) {
184        // Nobody reads the stream any more: dropped.
185        let _ = self.tx.send(item);
186    }
187}
188
189impl Handler for Queue {
190    fn message(&mut self, message: &Message<'_>) {
191        self.push(Incoming::Message(message.to_owned()));
192    }
193
194    fn event(&mut self, event: Event) {
195        self.push(Incoming::Event(event));
196    }
197
198    fn binary(&mut self, data: &[u8]) {
199        self.push(Incoming::Binary(bytes::Bytes::copy_from_slice(data)));
200    }
201
202    #[cfg(not(target_arch = "wasm32"))]
203    async fn ready(&mut self) {
204        // Room first, then the item: dropped while it waits, nothing is
205        // lost.
206        while !self.waiting.is_empty() {
207            let Ok(permit) = self.tx.reserve().await else {
208                self.waiting.clear();
209                return;
210            };
211            if let Some(item) = self.waiting.pop_front() {
212                permit.send(item);
213            }
214        }
215    }
216}