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
//! An implementation of the [EventSource][] API using [Surf][].
//!
//! # Surf Cargo Features
//! `surf-sse` wraps the [Surf][] library. By default, [`surf-sse`][surf-sse] uses the default
//! [Surf][] features. If you are using a non-default Surf client implementation or feature set,
//! you can disable [`surf-sse`][surf-sse]'s default feature:
//! ```toml
//! surf = { version = "*", features = ["hyper-client"] }
//! surf-sse = { version = "*", default-features = false }
//! ```
//!
//! This way, [`surf-sse`][surf-sse] will also use the "hyper-client" feature.
//!
//! # Logging
//!
//! [`surf-sse`][surf-sse] uses the [`log`][log] crate for some rudimentary connection logging. If you need to debug
//! an EventSource connection, enable trace logging for the `surf-sse` target. For example, with
//! [`env_logger`][env_logger]:
//! ```bash
//! RUST_LOG=surf-sse=trace \
//! cargo run
//! ```
//!
//! # Examples
//! ```rust,no_run
//! # async_std::task::block_on(async move {
//! #
//! use futures_util::stream::TryStreamExt; // for try_next()
//! use surf_sse::EventSource;
//!
//! let mut events = EventSource::new("https://announce.u-wave.net/events".parse().unwrap());
//!
//! while let Some(message) = events.try_next().await.unwrap() {
//!     dbg!(message);
//! }
//! #
//! # });
//! ```
//!
//! [EventSource]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource
//! [Surf]: https://github.com/http-rs/surf
//! [surf-sse]: https://github.com/goto-bus-stop/surf-sse
//! [log]: https://docs.rs/log
//! [env_logger]: https://docs.rs/env_logger

#![deny(future_incompatible)]
#![deny(nonstandard_style)]
#![deny(rust_2018_idioms)]
#![deny(unsafe_code)]
#![warn(missing_docs)]
#![warn(unused)]

use futures_core::stream::Stream;
use futures_timer::Delay;
use log::trace;
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
pub use surf::Url;

/// An event.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Event {
    /// The event name, defaults to "message".
    pub event: String,
    /// The event data as a UTF-8 String.
    pub data: String,
}

/// The state of the connection.
///
/// Unlike browser implementations of the EventSource API, this does not have a `Closed` value, because
/// the stream is closed by dropping the struct. At that point, there's no way to inspect the state
/// anyway.
///
/// A `Closed` value may be added in the future when there is more robust error handling in place.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReadyState {
    /// The client is connecting. It may have sent a request already, or be waiting for a retry
    /// timer.
    Connecting = 0,
    /// The connection is open and ready to read messages.
    Open = 1,
}

/// Represents an EventSource "error" event.
///
/// Note that you should not always stop reading messages when an error occurs. Many errors are
/// benign. EventSources retry a lot, emitting errors on every failure.
#[derive(Debug)]
pub enum Error {
    /// The connection was closed by the server. EventSource will reopen the connection.
    Retry,
    /// An error occurred while connecting to the endpoint. EventSource will retry the connection.
    ConnectionError(surf::Error),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Retry => write!(f, "the connection was closed by the server, retrying."),
            Self::ConnectionError(inner) => inner.fmt(f),
        }
    }
}

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

/// Wrapper for a dynamic Future type that adds an opaque Debug implementation.
struct DynDebugFuture<T>(Pin<Box<dyn Future<Output = T>>>);
impl<T> Future for DynDebugFuture<T> {
    type Output = T;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        Pin::new(&mut self.0).poll(cx)
    }
}

impl<T> fmt::Debug for DynDebugFuture<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[opaque Future type]")
    }
}

type EventStream = sse_codec::DecodeStream<surf::Response>;
type ConnectionFuture = DynDebugFuture<Result<surf::Response, surf::Error>>;

/// Represents the internal state machine.
#[derive(Debug)]
#[allow(clippy::large_enum_variant)] // `EventStream` is large but it's the active one most of the time
enum ConnectState {
    /// We're receiving messages.
    Streaming(EventStream),
    /// We're connecting to the endpoint.
    Connecting(ConnectionFuture),
    /// We're waiting to retry.
    WaitingToRetry(Delay),
    /// We're not doing anything. Currently only used as a default value. This can be used for the Closed state later.
    Idle,
}

/// A Server-Sent Events/Event Sourcing client, similar to [`EventSource`][EventSource] in the browser.
///
/// [EventSource]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource
#[derive(Debug)]
pub struct EventSource {
    client: surf::Client,
    url: Url,
    retry_time: Duration,
    last_event_id: Option<String>,
    state: ConnectState,
}

impl EventSource {
    /// Create a new connection.
    ///
    /// This constructor creates a new [`surf::Client`][] for the event sourcing connection. If you
    /// already have a [`surf::Client`][], consider using [`EventSource::with_client`][].
    ///
    /// [`surf::Client`]: https://docs.rs/surf/2.x/surf/struct.Client.html
    /// [`EventSource::with_client`]: #method.with_client
    pub fn new(url: Url) -> Self {
        Self::with_client(surf::client(), url)
    }

    /// Create a new connection.
    pub fn with_client(client: surf::Client, url: Url) -> Self {
        let mut event_source = Self {
            client,
            url,
            retry_time: Duration::from_secs(3),
            last_event_id: None,
            state: ConnectState::Idle,
        };
        event_source.start_connect();
        event_source
    }

    /// Get the URL that this client connects to.
    pub fn url(&self) -> &Url {
        &self.url
    }

    /// Get the state of the connection. See the documentation for `ReadyState`.
    pub fn ready_state(&self) -> ReadyState {
        match self.state {
            ConnectState::Streaming(_) => ReadyState::Open,
            ConnectState::Connecting(_) | ConnectState::WaitingToRetry(_) => ReadyState::Connecting,
            ConnectState::Idle => unreachable!("ReadyState::Closed"),
        }
    }

    /// Get the current retry timeout. If the connection dies, it is reopened after this time.
    pub fn retry_time(&self) -> Duration {
        self.retry_time
    }

    /// Override the retry timeout. If the connection dies, it is reopened after this time. Note
    /// that the timeout will be reset again if the server sends a new `retry:` message.
    pub fn set_retry_time(&mut self, duration: Duration) {
        self.retry_time = duration;
    }

    fn start_connect(&mut self) {
        trace!(target: "surf-sse", "connecting to {}", self.url);
        let mut request = surf::get(self.url.clone()).header("Accept", "text/event-stream");
        // If the EventSource object's last event ID string is not the empty string, set `Last-Event-ID`/last event ID string, encoded as UTF-8, in request's header list.
        if let Some(id) = &self.last_event_id {
            request = request.header("Last-Event-ID", id.as_str());
        }

        let client = self.client.clone();
        let request_future = Box::pin(async move { client.send(request).await });

        self.state = ConnectState::Connecting(DynDebugFuture(request_future));
    }

    fn start_retry(&mut self) {
        trace!(target: "surf-sse", "connection to {}, retrying in {:?}", self.url, self.retry_time);
        self.state = ConnectState::WaitingToRetry(Delay::new(self.retry_time));
    }

    fn start_receiving(&mut self, response: surf::Response) {
        trace!(target: "surf-sse", "connected to {}, now waiting for events", self.url);
        self.state = ConnectState::Streaming(sse_codec::decode_stream(response));
    }
}

impl Stream for EventSource {
    type Item = Result<Event, Error>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match &mut self.state {
            ConnectState::Streaming(event_stream) => {
                match Pin::new(event_stream).poll_next(cx) {
                    Poll::Pending => Poll::Pending,
                    Poll::Ready(Some(Ok(event))) => match event {
                        sse_codec::Event::Message { id, event, data } => {
                            self.last_event_id = id;
                            Poll::Ready(Some(Ok(Event { event, data })))
                        }
                        sse_codec::Event::Retry { retry } => {
                            self.retry_time = Duration::from_millis(retry);
                            Poll::Pending
                        }
                    },
                    Poll::Ready(Some(Err(_))) => {
                        // we care even less about "incorrect" messages than sse_codec does!
                        Poll::Pending
                    }
                    // Clients will reconnect if the connection is closed.
                    Poll::Ready(None) => {
                        self.start_retry();
                        let error = Error::Retry;
                        Poll::Ready(Some(Err(error)))
                    }
                }
            }

            ConnectState::WaitingToRetry(timer) => {
                match Pin::new(timer).poll(cx) {
                    Poll::Pending => (),
                    Poll::Ready(()) => self.start_connect(),
                }
                Poll::Pending
            }

            ConnectState::Connecting(connecting) => {
                match Pin::new(connecting).poll(cx) {
                    Poll::Pending => Poll::Pending,
                    // A client can be told to stop reconnecting using the HTTP 204 No Content response code.
                    Poll::Ready(Ok(response)) if response.status() == 204 => Poll::Ready(None),
                    Poll::Ready(Ok(response)) => {
                        self.start_receiving(response);
                        self.poll_next(cx)
                    }
                    Poll::Ready(Err(error)) => {
                        self.start_retry();
                        let error = Error::ConnectionError(error);
                        Poll::Ready(Some(Err(error)))
                    }
                }
            }

            ConnectState::Idle => unreachable!(),
        }
    }
}

/// Extension trait with event sourcing methods for Surf clients.
///
/// ```rust,no_run
/// use surf_sse::ClientExt;
/// use futures_util::stream::StreamExt; // for `.next`
///
/// let client = surf::client();
/// let mut events = client.connect_event_source("https://announce.u-wave.net".parse().unwrap());
/// async_std::task::block_on(async move {
///     while let Some(event) = events.next().await {
///         dbg!(event.unwrap());
///     }
/// });
/// ```
pub trait ClientExt {
    /// Connect to an event sourcing / server-sent events endpoint.
    fn connect_event_source(&self, url: Url) -> EventSource;
}

impl ClientExt for surf::Client {
    fn connect_event_source(&self, url: Url) -> EventSource {
        EventSource::with_client(self.clone(), url)
    }
}