1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use std::{
    io,
    pin::Pin,
    task::{ready, Context, Poll},
};

use actix_web::body::{BodySize, MessageBody};
use bytes::Bytes;
use tokio::{
    io::AsyncWrite,
    sync::mpsc::{UnboundedReceiver, UnboundedSender},
};

/// Returns an `AsyncWrite` response body writer and its associated body type.
///
/// # Examples
/// ```
/// # use actix_web::{HttpResponse, web};
/// use tokio::io::AsyncWriteExt as _;
/// use actix_web_lab::body;
///
/// # async fn index() {
/// let (mut wrt, body) = body::writer();
///
/// let _ = tokio::spawn(async move {
///     wrt.write_all(b"body from another thread").await
/// });
///
/// HttpResponse::Ok().body(body)
/// # ;}
/// ```
pub fn writer() -> (Writer, impl MessageBody) {
    let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
    (Writer { tx }, BodyStream { rx })
}

/// An `AsyncWrite` response body writer.
#[derive(Debug, Clone)]
pub struct Writer {
    tx: UnboundedSender<Bytes>,
}

impl AsyncWrite for Writer {
    fn poll_write(
        self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<Result<usize, io::Error>> {
        self.tx
            .send(Bytes::copy_from_slice(buf))
            .map_err(|_| io::Error::new(io::ErrorKind::Other, "TODO"))?;

        Poll::Ready(Ok(buf.len()))
    }

    fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        Poll::Ready(Ok(()))
    }

    fn poll_shutdown(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
        Poll::Ready(Ok(()))
    }
}

#[derive(Debug)]
struct BodyStream {
    rx: UnboundedReceiver<Bytes>,
}

impl MessageBody for BodyStream {
    type Error = io::Error;

    fn size(&self) -> BodySize {
        BodySize::Stream
    }

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<Option<Result<Bytes, Self::Error>>> {
        Poll::Ready(ready!(self.rx.poll_recv(cx)).map(Ok))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    static_assertions::assert_impl_all!(Writer: Send, Sync, Unpin);
    static_assertions::assert_impl_all!(BodyStream: Send, Sync, Unpin, MessageBody);
}