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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
use async_std::sync;
use std::io;
use std::time::Duration;
use async_std::io::Read as AsyncRead;
use async_std::prelude::*;
use async_std::task::{ready, Context, Poll};
use std::pin::Pin;
pin_project_lite::pin_project! {
#[derive(Debug)]
pub struct Encoder {
buf: Option<Vec<u8>>,
#[pin]
receiver: sync::Receiver<Vec<u8>>,
cursor: usize,
}
}
impl AsyncRead for Encoder {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<io::Result<usize>> {
if let None = self.buf {
self.buf = match ready!(Pin::new(&mut self.receiver).poll_next(cx)) {
Some(buf) => {
log::trace!("> Received a new buffer with len {}", buf.len());
Some(buf)
}
None => {
log::trace!("> Encoder done reading");
return Poll::Ready(Ok(0));
}
};
};
let local_buf = self.buf.as_mut().unwrap();
let local_len = local_buf.len();
let max = buf.len().min(local_buf.len());
buf[..max].clone_from_slice(&local_buf[..max]);
self.cursor += max;
if self.cursor == local_len {
self.buf = None;
self.cursor = 0;
};
Poll::Ready(Ok(max))
}
}
#[derive(Debug)]
pub struct Sender(sync::Sender<Vec<u8>>);
pub fn encode() -> (Sender, Encoder) {
let (sender, receiver) = sync::channel(1);
let encoder = Encoder {
receiver,
buf: None,
cursor: 0,
};
(Sender(sender), encoder)
}
impl Sender {
pub async fn send(&self, name: &str, data: &[u8], id: Option<&str>) {
let msg = format!("event:{}\n", name);
self.0.send(msg.into_bytes()).await;
if let Some(id) = id {
self.0.send(format!("id:{}\n", id).into_bytes()).await;
}
let mut msg = b"data:".to_vec();
msg.extend_from_slice(data);
msg.extend_from_slice(b"\n\n");
self.0.send(msg).await;
}
pub async fn send_retry(&self, dur: Duration, id: Option<&str>) {
if let Some(id) = id {
self.0.send(format!("id:{}\n", id).into_bytes()).await;
}
let dur = dur.as_secs_f64() as u64;
let msg = format!("retry:{}\n\n", dur);
self.0.send(msg.into_bytes()).await;
}
}
impl Clone for Sender {
fn clone(&self) -> Self {
Self(self.0.clone())
}
}