|
1 |
| -use async_std::io::prelude::*; |
2 |
| -use async_std::io::Write as AsyncWrite; |
| 1 | +use async_std::sync; |
3 | 2 | use std::io;
|
4 | 3 | use std::time::Duration;
|
5 | 4 |
|
6 |
| -/// An SSE protocol encoder. |
7 |
| -#[derive(Debug)] |
8 |
| -pub struct Encoder<W> { |
9 |
| - writer: W, |
10 |
| -} |
| 5 | +use async_std::io::Read as AsyncRead; |
| 6 | +use async_std::prelude::*; |
| 7 | +use async_std::task::{ready, Context, Poll}; |
| 8 | +use std::pin::Pin; |
11 | 9 |
|
12 |
| -/// Encode a new SSE connection. |
13 |
| -pub fn encode<W: AsyncWrite + Unpin>(writer: W) -> Encoder<W> { |
14 |
| - Encoder { writer } |
| 10 | +pin_project_lite::pin_project! { |
| 11 | + /// An SSE protocol encoder. |
| 12 | + #[derive(Debug)] |
| 13 | + pub struct Encoder { |
| 14 | + buf: Option<Vec<u8>>, |
| 15 | + #[pin] |
| 16 | + receiver: sync::Receiver<Vec<u8>>, |
| 17 | + cursor: usize, |
| 18 | + } |
15 | 19 | }
|
16 | 20 |
|
17 |
| -impl<W> Encoder<W> { |
18 |
| - /// Access the inner writer from the Encoder. |
19 |
| - pub fn into_writer(self) -> W { |
20 |
| - self.writer |
| 21 | +impl AsyncRead for Encoder { |
| 22 | + fn poll_read( |
| 23 | + mut self: Pin<&mut Self>, |
| 24 | + cx: &mut Context<'_>, |
| 25 | + buf: &mut [u8], |
| 26 | + ) -> Poll<io::Result<usize>> { |
| 27 | + // Request a new buffer if we don't have one yet. |
| 28 | + if let None = self.buf { |
| 29 | + self.buf = match ready!(Pin::new(&mut self.receiver).poll_next(cx)) { |
| 30 | + Some(buf) => { |
| 31 | + log::trace!("> Received a new buffer with len {}", buf.len()); |
| 32 | + Some(buf) |
| 33 | + } |
| 34 | + None => { |
| 35 | + log::trace!("> Encoder done reading"); |
| 36 | + return Poll::Ready(Ok(0)); |
| 37 | + } |
| 38 | + }; |
| 39 | + }; |
| 40 | + |
| 41 | + // Write the current buffer to completion. |
| 42 | + let local_buf = self.buf.as_mut().unwrap(); |
| 43 | + let local_len = local_buf.len(); |
| 44 | + let max = buf.len().min(local_buf.len()); |
| 45 | + buf[..max].clone_from_slice(&local_buf[..max]); |
| 46 | + |
| 47 | + self.cursor += max; |
| 48 | + |
| 49 | + // Reset values if we're done reading. |
| 50 | + if self.cursor == local_len { |
| 51 | + self.buf = None; |
| 52 | + self.cursor = 0; |
| 53 | + }; |
| 54 | + |
| 55 | + // Return bytes read. |
| 56 | + Poll::Ready(Ok(max)) |
21 | 57 | }
|
22 | 58 | }
|
23 | 59 |
|
24 |
| -impl<W: AsyncWrite + Unpin> Encoder<W> { |
| 60 | +// impl AsyncBufRead for Encoder { |
| 61 | +// fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> { |
| 62 | +// match ready!(self.project().receiver.poll_next(cx)) { |
| 63 | +// Some(buf) => match &self.buf { |
| 64 | +// None => self.project().buf = &mut Some(buf), |
| 65 | +// Some(local_buf) => local_buf.extend(buf), |
| 66 | +// }, |
| 67 | +// None => { |
| 68 | +// if let None = self.buf { |
| 69 | +// self.project().buf = &mut Some(vec![]); |
| 70 | +// }; |
| 71 | +// } |
| 72 | +// }; |
| 73 | +// Poll::Ready(Ok(self.buf.as_ref().unwrap())) |
| 74 | +// } |
| 75 | + |
| 76 | +// fn consume(self: Pin<&mut Self>, amt: usize) { |
| 77 | +// Pin::new(self).cursor += amt; |
| 78 | +// } |
| 79 | +// } |
| 80 | + |
| 81 | +/// The sending side of the encoder. |
| 82 | +#[derive(Debug)] |
| 83 | +pub struct Sender(sync::Sender<Vec<u8>>); |
| 84 | + |
| 85 | +/// Create a new SSE encoder. |
| 86 | +pub fn encode() -> (Sender, Encoder) { |
| 87 | + let (sender, receiver) = sync::channel(1); |
| 88 | + let encoder = Encoder { |
| 89 | + receiver, |
| 90 | + buf: None, |
| 91 | + cursor: 0, |
| 92 | + }; |
| 93 | + (Sender(sender), encoder) |
| 94 | +} |
| 95 | + |
| 96 | +impl Sender { |
25 | 97 | /// Send a new message over SSE.
|
26 |
| - pub async fn send(&mut self, name: &str, data: &[u8], id: Option<&str>) -> io::Result<()> { |
| 98 | + pub async fn send(&self, name: &str, data: &[u8], id: Option<&str>) { |
27 | 99 | // Write the event name
|
28 |
| - self.writer.write_all(b"event:").await?; |
29 |
| - self.writer.write_all(name.as_bytes()).await?; |
30 |
| - self.writer.write_all(b"\n").await?; |
| 100 | + let msg = format!("event:{}\n", name); |
| 101 | + self.0.send(msg.into_bytes()).await; |
31 | 102 |
|
32 | 103 | // Write the id
|
33 | 104 | if let Some(id) = id {
|
34 |
| - self.writer.write_all(b"id:").await?; |
35 |
| - self.writer.write_all(id.as_bytes()).await?; |
36 |
| - self.writer.write_all(b"\n").await?; |
| 105 | + self.0.send(format!("id:{}\n", id).into_bytes()).await; |
37 | 106 | }
|
38 | 107 |
|
39 |
| - // Write the section |
40 |
| - self.writer.write_all(b"data:").await?; |
41 |
| - self.writer.write_all(data).await?; |
42 |
| - self.writer.write_all(b"\n").await?; |
43 |
| - |
44 |
| - // Finalize the message |
45 |
| - self.writer.write_all(b"\n").await?; |
46 |
| - |
47 |
| - Ok(()) |
| 108 | + // Write the data section, and end. |
| 109 | + let mut msg = b"data:".to_vec(); |
| 110 | + msg.extend_from_slice(data); |
| 111 | + msg.extend_from_slice(b"\n\n"); |
| 112 | + self.0.send(msg).await; |
48 | 113 | }
|
49 | 114 |
|
50 | 115 | /// Send a new "retry" message over SSE.
|
51 |
| - pub async fn send_retry(&mut self, dur: Duration, id: Option<&str>) -> io::Result<()> { |
| 116 | + pub async fn send_retry(&self, dur: Duration, id: Option<&str>) { |
52 | 117 | // Write the id
|
53 | 118 | if let Some(id) = id {
|
54 |
| - self.writer.write_all(b"id:").await?; |
55 |
| - self.writer.write_all(id.as_bytes()).await?; |
56 |
| - self.writer.write_all(b"\n").await?; |
| 119 | + self.0.send(format!("id:{}\n", id).into_bytes()).await; |
57 | 120 | }
|
58 | 121 |
|
59 |
| - // Write the section |
60 |
| - self.writer.write_all(b"retry:").await?; |
61 |
| - self.writer |
62 |
| - .write_all(&format!("{}", dur.as_secs_f64() as u64).as_bytes()) |
63 |
| - .await?; |
64 |
| - self.writer.write_all(b"\n").await?; |
65 |
| - |
66 |
| - // Finalize the message |
67 |
| - self.writer.write_all(b"\n").await?; |
68 |
| - |
69 |
| - Ok(()) |
| 122 | + // Write the retry section, and end. |
| 123 | + let dur = dur.as_secs_f64() as u64; |
| 124 | + let msg = format!("retry:{}\n\n", dur); |
| 125 | + self.0.send(msg.into_bytes()).await; |
70 | 126 | }
|
71 | 127 | }
|
0 commit comments