Skip to main content

ullun/
stream.rs

1//! Streaming response bodies
2//!
3//! [`Response::stream`](crate::response::Response::stream) hands out a
4//! [`BodySender`]; whatever is sent through it goes to the client right away.
5//! For Server-Sent Events see [`sse`](crate::sse).
6
7use bytes::Bytes;
8use tokio::sync::mpsc;
9
10/// The client closed the connection (or the response was dropped)
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub struct Disconnected;
13
14impl std::fmt::Display for Disconnected {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        f.write_str("client disconnected")
17    }
18}
19
20impl std::error::Error for Disconnected {}
21
22/// Sends body chunks of a streaming response; clone it to feed one stream from
23/// several tasks. The body ends when all clones are dropped.
24#[derive(Clone)]
25pub struct BodySender {
26    tx: mpsc::Sender<Bytes>,
27}
28
29impl BodySender {
30    pub(crate) fn new(tx: mpsc::Sender<Bytes>) -> Self {
31        Self { tx }
32    }
33
34    /// Queue a chunk; waits while the client is slower than the producer
35    /// (the channel is bounded), fails once the client is gone.
36    pub async fn send(&self, chunk: impl Into<Bytes>) -> Result<(), Disconnected> {
37        self.tx.send(chunk.into()).await.map_err(|_| Disconnected)
38    }
39
40    /// True once the client has gone away
41    pub fn is_closed(&self) -> bool {
42        self.tx.is_closed()
43    }
44
45    /// Completes when the client has gone away, e.g. to stop a producer that is
46    /// waiting for its next event
47    pub async fn closed(&self) {
48        self.tx.closed().await
49    }
50}