sseer 0.3.0

Various helpers for getting Event streams out of your SSE responses
Documentation
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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
use core::{
    error::Error,
    fmt::{Display, Formatter},
    pin::Pin,
    task::{Context, Poll, ready},
    time::Duration,
};

use crate::event_stream::EventStream;
use bytes_utils::Str;
use futures_core::future::BoxFuture;
use futures_timer::Delay;

use http_body_util::BodyDataStream;
use pin_project_lite::pin_project;
use reqwest::{
    Body, Error as ReqwestError, RequestBuilder, Response, StatusCode,
    header::{ACCEPT, CONTENT_TYPE, HeaderName, HeaderValue},
};

use crate::{
    constants::EMPTY_STR,
    errors::{CantCloneError, EventStreamError},
    event::Event,
    response_to_stream,
    retry::{DEFAULT_RETRY, ExponentialBackoff, RetryPolicy},
};

/// Events emitted by [EventSource]
#[derive(Debug, Clone)]
pub enum StreamEvent {
    /// A new connection has been opened
    Open,
    Event(Event),
}

impl From<Event> for StreamEvent {
    fn from(event: Event) -> Self {
        StreamEvent::Event(event)
    }
}

pin_project! {
    #[project = EventSourceProjection]
    #[derive(Debug)]
    pub struct EventSource<R> {
        builder: RequestBuilder,
        #[pin]
        connection_state: ConnectionState,
        last_event_id: Str,
        retry_policy: R
    }
}

pin_project! {
    #[project = ConnectionStateProjection]
    enum ConnectionState {
        Connecting {
            #[pin]
            future: BoxFuture<'static, Result<Response, ReqwestError>>,
            retry_state: Option<(usize, Duration)>,
        },
        Retrying {
            #[pin]
            delay: Delay,
            attempt_number: usize,
            delay_duration: Duration,
        },
        Open {
            #[pin]
            stream: EventStream<BodyDataStream<Body>>,
            retry_state: Option<(usize, Duration)>,
        },
        Closed,
    }
}

impl std::fmt::Debug for ConnectionState {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Connecting { retry_state, .. } => f
                .debug_struct("Connecting")
                .field("future", &"future")
                .field("retry_state", retry_state)
                .finish(),
            Self::Retrying {
                delay,
                attempt_number,
                delay_duration,
            } => f
                .debug_struct("Retrying")
                .field("delay", delay)
                .field("attempt_number", attempt_number)
                .field("delay_duration", delay_duration)
                .finish(),
            Self::Open {
                stream,
                retry_state,
            } => f
                .debug_struct("Open")
                .field("stream", stream)
                .field("retry_state", retry_state)
                .finish(),
            Self::Closed => write!(f, "Closed"),
        }
    }
}

impl<'pin, R> EventSourceProjection<'pin, R> {
    fn initiate_connection(
        &mut self,
        retry_state: Option<(usize, Duration)>,
    ) -> Result<(), EventSourceErrorKind> {
        let req = self.builder.try_clone().unwrap().header(
            HeaderName::from_static("last-event-id"),
            HeaderValue::from_str(self.last_event_id).map_err(|_| {
                EventSourceErrorKind::InvalidLastEventId(self.last_event_id.clone())
            })?,
        );
        let res_future = Box::pin(req.send());
        *self.connection_state = ConnectionState::Connecting {
            future: res_future,
            retry_state,
        };
        Ok(())
    }

    fn handle_successful_response(
        &mut self,
        response: Response,
        retry_state: Option<(usize, Duration)>,
    ) -> Result<(), EventSourceErrorKind> {
        let status = response.status();
        if !status.is_success() {
            return Err(EventSourceErrorKind::InvalidStatusCode {
                status,
                response: Box::new(response),
            });
        }

        if let Some(content_type) = response.headers().get(CONTENT_TYPE)
            && !content_type.as_bytes().starts_with(b"text/event-stream")
        {
            return Err(EventSourceErrorKind::InvalidContentType {
                status,
                content_type: content_type.clone(),
                response: Box::new(response),
            });
        }

        let stream = response_to_stream(response);
        *self.connection_state = ConnectionState::Open {
            stream,
            retry_state,
        };
        Ok(())
    }

    fn start_retry(&mut self, attempt_number: usize, delay_duration: Duration) {
        self.connection_state.set(ConnectionState::Retrying {
            delay: Delay::new(delay_duration),
            attempt_number,
            delay_duration,
        })
    }

    fn handle_error(&mut self, err: &EventSourceErrorKind, last_retry: Option<(usize, Duration)>)
    where
        R: RetryPolicy<EventSourceErrorKind>,
    {
        if let Some(retry_delay) = self.retry_policy.retry(err, last_retry) {
            let retry_num = last_retry.map(|retry| retry.0).unwrap_or(1);
            self.start_retry(retry_num, retry_delay);
        } else {
            self.connection_state.set(ConnectionState::Closed);
        }
    }

    fn handle_event(&mut self, event: &Event)
    where
        R: RetryPolicy<EventSourceErrorKind>,
    {
        *self.last_event_id = event.id.clone();
        if let Some(duration) = event.retry {
            self.retry_policy.set_reconnection_time(duration)
        }
    }
}

impl<R> EventSource<R> {
    pub fn new_with_retry(
        request: RequestBuilder,
        retry_policy: R,
    ) -> Result<Self, CantCloneError> {
        let request = request.header(ACCEPT, HeaderValue::from_static("text/event-stream"));
        let req_fut = Box::pin(request.try_clone().ok_or(CantCloneError)?.send());

        Ok(EventSource {
            builder: request,
            connection_state: ConnectionState::Connecting {
                future: req_fut,
                retry_state: None,
            },
            last_event_id: EMPTY_STR,
            retry_policy,
        })
    }
}

impl EventSource<ExponentialBackoff> {
    pub fn new(request: RequestBuilder) -> Result<EventSource<ExponentialBackoff>, CantCloneError> {
        let request = request.header(ACCEPT, HeaderValue::from_static("text/event-stream"));
        let req_fut = Box::pin(request.try_clone().ok_or(CantCloneError)?.send());

        Ok(EventSource {
            builder: request,
            connection_state: ConnectionState::Connecting {
                future: req_fut,
                retry_state: None,
            },
            last_event_id: EMPTY_STR,
            retry_policy: DEFAULT_RETRY,
        })
    }
}

#[derive(Debug)]
enum EventSourceErrorKind {
    /// The last event ID contains non-visible ascii characters, unusable in a [`HeaderValue`]
    InvalidLastEventId(Str),
    /// Reqwest has had an error when getting a response
    Transport(ReqwestError),
    /// The underlying stream has ran into an error
    Stream(EventStreamError<ReqwestError>),
    /// Received a [non 2xx][reqwest::StatusCode::is_success] response
    InvalidStatusCode {
        status: StatusCode,
        response: Box<Response>, // boxed because this was a big error
    },
    /// Received a 2XX status, but the [Content-Type][CONTENT_TYPE] was not "text/event-stream"
    InvalidContentType {
        status: StatusCode,
        content_type: HeaderValue,
        response: Box<Response>,
    },
    /// The underlying stream has ran to completion
    StreamEnded, // not sure how i feel about this being an error tbh, change me?
}

impl Display for EventSourceErrorKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self {
            EventSourceErrorKind::InvalidLastEventId(s) => s.fmt(f),
            EventSourceErrorKind::Transport(err) => err.fmt(f),
            EventSourceErrorKind::Stream(err) => err.fmt(f),
            EventSourceErrorKind::InvalidStatusCode { status, .. } => write!(
                f,
                "got non 2XX status code {status}: '{canonical}'",
                canonical = status.canonical_reason().unwrap_or("no canonical reason")
            ),
            EventSourceErrorKind::InvalidContentType {
                status,
                content_type,
                ..
            } => write!(
                f,
                "got invalid content-type '{content_type}' on status '{status}' request",
                content_type = content_type
                    .to_str()
                    .unwrap_or("unable to read content-type as str")
            ),
            EventSourceErrorKind::StreamEnded => "stream ended".fmt(f),
        }
    }
}

impl Error for EventSourceErrorKind {}

#[derive(Debug)]
pub struct EventSourceError {
    retry_state: Option<(usize, Duration)>,
    kind: EventSourceErrorKind,
}

impl Display for EventSourceError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let retry_state = self
            .retry_state
            .as_ref()
            .map(|(attempts, duration)| format!("attempts: '{attempts}' duration: {duration:?}"))
            .unwrap_or(String::from("no last retry"));
        write!(
            f,
            "Error '{kind}' with last retry: {retry_state}",
            kind = self.kind
        )
    }
}

impl std::error::Error for EventSourceError {}

impl EventSourceError {
    fn new(
        kind: impl Into<EventSourceErrorKind>,
        retry_state: impl Into<Option<(usize, Duration)>>,
    ) -> Self {
        Self {
            retry_state: retry_state.into(),
            kind: kind.into(),
        }
    }

    /// Was this error caused by [Response::status] being a non 2XX
    pub fn is_status_code(&self) -> bool {
        matches!(self.kind, EventSourceErrorKind::InvalidStatusCode { .. })
    }

    /// Was this error caused by [Content-Type][CONTENT_TYPE] not being "text/event-stream"
    pub fn is_content_type(&self) -> bool {
        matches!(self.kind, EventSourceErrorKind::InvalidContentType { .. })
    }

    /// Was the error caused by an invalid [`Response`]
    pub fn is_response_err(&self) -> bool {
        matches!(
            self.kind,
            EventSourceErrorKind::InvalidContentType { .. }
                | EventSourceErrorKind::InvalidStatusCode { .. }
        )
    }

    /// Get the status code that caused this error, if it was caused by an invalid [`Response`]
    pub fn status_code(&self) -> Option<StatusCode> {
        match &self.kind {
            EventSourceErrorKind::InvalidStatusCode { status, .. }
            | EventSourceErrorKind::InvalidContentType { status, .. } => Some(*status),
            _ => None,
        }
    }

    /// Gets a reference to the underlying response if this error was caused by an invalid [`Response`]
    pub fn response(&self) -> Option<&Response> {
        match &self.kind {
            EventSourceErrorKind::InvalidStatusCode { response, .. }
            | EventSourceErrorKind::InvalidContentType { response, .. } => Some(response),

            _ => None,
        }
    }

    /// If this error comes from a [`Response`], return the raw response, collected status code and the [Content-Type][CONTENT_TYPE] header if it has been extracted already
    pub fn into_response_err(self) -> Option<(Response, StatusCode, Option<HeaderValue>)> {
        match self.kind {
            EventSourceErrorKind::InvalidStatusCode { response, status } => {
                Some((*response, status, None))
            }
            EventSourceErrorKind::InvalidContentType {
                status,
                content_type,
                response,
            } => Some((*response, status, Some(content_type))),
            _ => None,
        }
    }

    /// Is this error because the stream has stopped?
    pub fn is_stream_ended(&self) -> bool {
        matches!(self.kind, EventSourceErrorKind::StreamEnded)
    }
}

impl From<ReqwestError> for EventSourceErrorKind {
    fn from(value: ReqwestError) -> Self {
        Self::Transport(value)
    }
}

impl From<EventStreamError<ReqwestError>> for EventSourceErrorKind {
    fn from(value: EventStreamError<ReqwestError>) -> Self {
        Self::Stream(value)
    }
}

impl<R> futures_core::Stream for EventSource<R>
where
    R: RetryPolicy<EventSourceErrorKind>,
{
    type Item = Result<StreamEvent, EventSourceError>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        let mut this = self.project();
        loop {
            match this.connection_state.as_mut().project() {
                ConnectionStateProjection::Connecting {
                    future,
                    retry_state,
                } => {
                    let retry_state = *retry_state;
                    match ready!(future.poll(cx)) {
                        Ok(response) => {
                            if let Err(kind) =
                                this.handle_successful_response(response, retry_state)
                            {
                                return Poll::Ready(Some(Err(EventSourceError::new(
                                    kind,
                                    retry_state,
                                ))));
                            };
                            return Poll::Ready(Some(Ok(StreamEvent::Open)));
                        }
                        Err(err) => {
                            this.connection_state.set(ConnectionState::Closed);
                            return Poll::Ready(Some(Err(EventSourceError::new(err, retry_state))));
                        }
                    }
                }
                ConnectionStateProjection::Retrying {
                    delay,
                    attempt_number,
                    delay_duration,
                } => {
                    ready!(delay.poll(cx));
                    let retry_state = Some((*attempt_number + 1, *delay_duration));
                    if let Err(err) = this.initiate_connection(retry_state) {
                        this.connection_state.set(ConnectionState::Closed);
                        return Poll::Ready(Some(Err(EventSourceError::new(err, retry_state))));
                    }
                }
                ConnectionStateProjection::Open {
                    stream,
                    retry_state,
                } => {
                    let retry_state = *retry_state;
                    match ready!(stream.poll_next(cx)) {
                        Some(Ok(event)) => {
                            this.handle_event(&event);
                            return Poll::Ready(Some(Ok(event.into())));
                        }
                        Some(Err(err)) => {
                            let err_kind = err.into();
                            this.handle_error(&err_kind, retry_state);
                            return Poll::Ready(Some(Err(EventSourceError::new(
                                err_kind,
                                retry_state,
                            ))));
                        }
                        None => {
                            let err_kind = EventSourceErrorKind::StreamEnded;
                            this.handle_error(&err_kind, retry_state);
                            return Poll::Ready(Some(Err(EventSourceError::new(
                                err_kind,
                                retry_state,
                            ))));
                        }
                    }
                }
                ConnectionStateProjection::Closed => return Poll::Ready(None),
            }
        }
    }
}