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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
use serde::Serialize;
use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt::{self, Display, Formatter, Write};
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use futures::{future, Stream, TryStream, TryStreamExt};
use http::header::{HeaderValue, CACHE_CONTROL, CONTENT_TYPE};
use pin_project::pin_project;
use serde_json::{self, Error};
use tokio::time::{self, Sleep};
use salvo_core::http::Response;
use self::sealed::SseError;
#[derive(Debug)]
enum DataType {
Text(String),
Json(String),
}
#[derive(Default, Debug)]
pub struct SseEvent {
name: Option<String>,
id: Option<String>,
data: Option<DataType>,
comment: Option<String>,
retry: Option<Duration>,
}
impl SseEvent {
pub fn data<T: Into<String>>(mut self, data: T) -> SseEvent {
self.data = Some(DataType::Text(data.into()));
self
}
pub fn json_data<T: Serialize>(mut self, data: T) -> Result<SseEvent, Error> {
self.data = Some(DataType::Json(serde_json::to_string(&data)?));
Ok(self)
}
pub fn comment<T: Into<String>>(mut self, comment: T) -> SseEvent {
self.comment = Some(comment.into());
self
}
pub fn name<T: Into<String>>(mut self, event: T) -> SseEvent {
self.name = Some(event.into());
self
}
pub fn retry(mut self, duration: Duration) -> SseEvent {
self.retry = Some(duration.into());
self
}
pub fn id<T: Into<String>>(mut self, id: T) -> SseEvent {
self.id = Some(id.into());
self
}
}
impl Display for SseEvent {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
if let Some(ref comment) = &self.comment {
":".fmt(f)?;
comment.fmt(f)?;
f.write_char('\n')?;
}
if let Some(ref name) = &self.name {
"event:".fmt(f)?;
name.fmt(f)?;
f.write_char('\n')?;
}
match self.data {
Some(DataType::Text(ref data)) => {
for line in data.split('\n') {
"data:".fmt(f)?;
line.fmt(f)?;
f.write_char('\n')?;
}
}
Some(DataType::Json(ref data)) => {
"data:".fmt(f)?;
data.fmt(f)?;
f.write_char('\n')?;
}
None => {}
}
if let Some(ref id) = &self.id {
"id:".fmt(f)?;
id.fmt(f)?;
f.write_char('\n')?;
}
if let Some(ref duration) = &self.retry {
"retry:".fmt(f)?;
let secs = duration.as_secs();
let millis = duration.subsec_millis();
if secs > 0 {
secs.fmt(f)?;
if millis < 10 {
f.write_str("00")?;
} else if millis < 100 {
f.write_char('0')?;
}
}
millis.fmt(f)?;
f.write_char('\n')?;
}
f.write_char('\n')?;
Ok(())
}
}
#[allow(missing_debug_implementations)]
#[pin_project]
pub struct SseKeepAlive<S> {
#[pin]
event_stream: S,
comment_text: Cow<'static, str>,
max_interval: Duration,
#[pin]
alive_timer: Sleep,
}
impl<S> SseKeepAlive<S>
where
S: TryStream<Ok = SseEvent> + Send + 'static,
S::Error: StdError + Send + Sync + 'static,
{
pub fn new(event_stream: S) -> SseKeepAlive<S> {
let max_interval = Duration::from_secs(15);
let alive_timer = time::sleep(max_interval);
SseKeepAlive {
event_stream,
comment_text: Cow::Borrowed(""),
max_interval,
alive_timer,
}
}
pub fn interval(mut self, time: Duration) -> Self {
self.max_interval = time;
self
}
pub fn text(mut self, text: impl Into<Cow<'static, str>>) -> Self {
self.comment_text = text.into();
self
}
pub fn streaming(self, res: &mut Response) {
write_request_headers(res);
let body_stream = self
.map_err(|error| {
tracing::error!("sse stream error: {}", error);
SseError
})
.into_stream()
.and_then(|event| future::ready(Ok(event.to_string())));
res.streaming(body_stream);
}
}
#[inline]
fn write_request_headers(res: &mut Response) {
res.headers_mut().insert(CONTENT_TYPE, HeaderValue::from_static("text/event-stream"));
res.headers_mut().insert(CACHE_CONTROL, HeaderValue::from_static("no-cache"));
}
pub fn streaming<S>(res: &mut Response, event_stream: S)
where
S: TryStream<Ok = SseEvent> + Send + 'static,
S::Error: StdError + Send + Sync + 'static,
{
write_request_headers(res);
let body_stream = event_stream
.map_err(|error| {
tracing::error!("sse stream error: {}", error);
SseError
})
.into_stream()
.and_then(|event| future::ready(Ok(event.to_string())));
res.streaming(body_stream);
}
impl<S> Stream for SseKeepAlive<S>
where
S: TryStream<Ok = SseEvent> + Send + 'static,
S::Error: StdError + Send + Sync + 'static,
{
type Item = Result<SseEvent, SseError>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let mut pin = self.project();
match pin.event_stream.try_poll_next(cx) {
Poll::Pending => match Pin::new(&mut pin.alive_timer).poll(cx) {
Poll::Pending => Poll::Pending,
Poll::Ready(_) => {
pin.alive_timer.reset(tokio::time::Instant::now() + *pin.max_interval);
let comment_str = pin.comment_text.clone();
let event = SseEvent::default().comment(comment_str);
Poll::Ready(Some(Ok(event)))
}
},
Poll::Ready(Some(Ok(event))) => {
pin.alive_timer.reset(tokio::time::Instant::now() + *pin.max_interval);
Poll::Ready(Some(Ok(event)))
}
Poll::Ready(None) => Poll::Ready(None),
Poll::Ready(Some(Err(error))) => {
tracing::error!("sse::keep error: {}", error);
Poll::Ready(Some(Err(SseError)))
}
}
}
}
mod sealed {
use super::*;
#[derive(Debug)]
pub struct SseError;
impl Display for SseError {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "sse error")
}
}
impl StdError for SseError {}
}