|
| 1 | +//! A wrapper around the `EventSource` API using the Futures API to be used with async rust. |
| 2 | +//! |
| 3 | +//! EventSource is similar to WebSocket with the major differences being: |
| 4 | +//! |
| 5 | +//! * they are a one-way stream of server generated events |
| 6 | +//! * their connection is managed entirely by the browser |
| 7 | +//! * their data is slightly more structured including an id, type and data |
| 8 | +//! |
| 9 | +//! EventSource is therefore suitable for simpler scenarios than WebSocket. |
| 10 | +//! |
| 11 | +//! See the [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events) to learn more. |
| 12 | +//! |
| 13 | +//! # Example |
| 14 | +//! |
| 15 | +//! ```rust |
| 16 | +//! use gloo_net::eventsource::futures::EventSource; |
| 17 | +//! use wasm_bindgen_futures::spawn_local; |
| 18 | +//! use futures::StreamExt; |
| 19 | +//! |
| 20 | +//! # macro_rules! console_log { |
| 21 | +//! # ($($expr:expr),*) => {{}}; |
| 22 | +//! # } |
| 23 | +//! # fn no_run() { |
| 24 | +//! let mut es = EventSource::new("http://api.example.com/ssedemo.php").unwrap(); |
| 25 | +//! es.subscribe_event("some-event-type").unwrap(); |
| 26 | +//! es.subscribe_event("another-event-type").unwrap(); |
| 27 | +//! |
| 28 | +//! spawn_local(async move { |
| 29 | +//! while let Some((event_type, msg)) = es.next().await { |
| 30 | +//! console_log!(format!("1. {}: {:?}", event_type, msg)) |
| 31 | +//! } |
| 32 | +//! console_log!("EventSource Closed"); |
| 33 | +//! }) |
| 34 | +//! # } |
| 35 | +//! ``` |
| 36 | +use crate::eventsource::{EventSourceError, State}; |
| 37 | +use crate::js_to_js_error; |
| 38 | +use futures_channel::mpsc; |
| 39 | +use futures_core::{ready, Stream}; |
| 40 | +use gloo_utils::errors::JsError; |
| 41 | +use pin_project::{pin_project, pinned_drop}; |
| 42 | +use std::ops::DerefMut; |
| 43 | +use std::pin::Pin; |
| 44 | +use std::sync::{Arc, Mutex}; |
| 45 | +use std::task::{Context, Poll}; |
| 46 | +use wasm_bindgen::prelude::*; |
| 47 | +use wasm_bindgen::JsCast; |
| 48 | +use web_sys::MessageEvent; |
| 49 | + |
| 50 | +/// Wrapper around browser's EventSource API. |
| 51 | +#[allow(missing_debug_implementations)] |
| 52 | +#[pin_project(PinnedDrop)] |
| 53 | +pub struct EventSource { |
| 54 | + es: web_sys::EventSource, |
| 55 | + message_sender: mpsc::UnboundedSender<StreamMessage>, |
| 56 | + #[pin] |
| 57 | + message_receiver: mpsc::UnboundedReceiver<StreamMessage>, |
| 58 | + #[allow(clippy::type_complexity)] |
| 59 | + closures: Arc< |
| 60 | + Mutex<( |
| 61 | + Vec<Closure<dyn FnMut(MessageEvent)>>, |
| 62 | + Closure<dyn FnMut(web_sys::Event)>, |
| 63 | + )>, |
| 64 | + >, |
| 65 | +} |
| 66 | + |
| 67 | +impl EventSource { |
| 68 | + /// Establish an EventSource. |
| 69 | + /// |
| 70 | + /// This function may error in the following cases: |
| 71 | + /// - The connection url is invalid |
| 72 | + /// |
| 73 | + /// The error returned is [`JsError`]. See the |
| 74 | + /// [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/EventSource#exceptions_thrown) |
| 75 | + /// to learn more. |
| 76 | + pub fn new(url: &str) -> Result<Self, JsError> { |
| 77 | + let es = web_sys::EventSource::new(url).map_err(js_to_js_error)?; |
| 78 | + |
| 79 | + let (message_sender, message_receiver) = mpsc::unbounded(); |
| 80 | + |
| 81 | + let error_callback: Closure<dyn FnMut(web_sys::Event)> = { |
| 82 | + let sender = message_sender.clone(); |
| 83 | + Closure::wrap(Box::new(move |e: web_sys::Event| { |
| 84 | + let sender = sender.clone(); |
| 85 | + let is_connecting = e |
| 86 | + .current_target() |
| 87 | + .and_then(|target| target.dyn_into::<web_sys::EventSource>().ok()) |
| 88 | + .map(|es| es.ready_state() == web_sys::EventSource::CONNECTING) |
| 89 | + .unwrap_or(false); |
| 90 | + if !is_connecting { |
| 91 | + let _ = sender.unbounded_send(StreamMessage::ErrorEvent); |
| 92 | + }; |
| 93 | + }) as Box<dyn FnMut(web_sys::Event)>) |
| 94 | + }; |
| 95 | + |
| 96 | + es.set_onerror(Some(error_callback.as_ref().unchecked_ref())); |
| 97 | + |
| 98 | + Ok(Self { |
| 99 | + es, |
| 100 | + message_sender, |
| 101 | + message_receiver, |
| 102 | + closures: Arc::new(Mutex::new((vec![], error_callback))), |
| 103 | + }) |
| 104 | + } |
| 105 | + |
| 106 | + /// Subscribes to listening for a specific type of event. Can be |
| 107 | + /// called multiple times. |
| 108 | + /// |
| 109 | + /// All event types are streamed back with the element of the stream |
| 110 | + /// being a tuple of event type and message event. |
| 111 | + /// |
| 112 | + /// The event type of "message" is a special case, as it will capture |
| 113 | + /// events without an event field as well as events that have the |
| 114 | + /// specific type `event: message`. It will not trigger on any |
| 115 | + /// other event type. |
| 116 | + pub fn subscribe_event(&mut self, event_type: &str) -> Result<(), JsError> { |
| 117 | + let event_type = event_type.to_string(); |
| 118 | + match self.closures.lock() { |
| 119 | + Ok(mut closures) => { |
| 120 | + let (message_callbacks, _) = closures.deref_mut(); |
| 121 | + |
| 122 | + let message_callback: Closure<dyn FnMut(MessageEvent)> = { |
| 123 | + let sender = self.message_sender.clone(); |
| 124 | + let event_type = event_type.to_string(); |
| 125 | + Closure::wrap(Box::new(move |e: MessageEvent| { |
| 126 | + let sender = sender.clone(); |
| 127 | + let event_type = event_type.to_string(); |
| 128 | + let _ = sender.unbounded_send(StreamMessage::Message(event_type, e)); |
| 129 | + }) as Box<dyn FnMut(MessageEvent)>) |
| 130 | + }; |
| 131 | + |
| 132 | + self.es |
| 133 | + .add_event_listener_with_callback( |
| 134 | + &event_type, |
| 135 | + message_callback.as_ref().unchecked_ref(), |
| 136 | + ) |
| 137 | + .map_err(js_to_js_error)?; |
| 138 | + |
| 139 | + message_callbacks.push(message_callback); |
| 140 | + Ok(()) |
| 141 | + } |
| 142 | + Err(e) => Err(js_sys::Error::new(&format!("Failed to subscribe: {}", e)).into()), |
| 143 | + } |
| 144 | + } |
| 145 | + |
| 146 | + /// Closes the EventSource. |
| 147 | + /// |
| 148 | + /// See the [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close#parameters) |
| 149 | + /// to learn about this function |
| 150 | + pub fn close(self) { |
| 151 | + self.es.close(); |
| 152 | + } |
| 153 | + |
| 154 | + /// The current state of the EventSource. |
| 155 | + pub fn state(&self) -> State { |
| 156 | + let ready_state = self.es.ready_state(); |
| 157 | + match ready_state { |
| 158 | + 0 => State::Connecting, |
| 159 | + 1 => State::Open, |
| 160 | + 2 => State::Closed, |
| 161 | + _ => unreachable!(), |
| 162 | + } |
| 163 | + } |
| 164 | +} |
| 165 | + |
| 166 | +#[derive(Clone)] |
| 167 | +enum StreamMessage { |
| 168 | + ErrorEvent, |
| 169 | + Message(String, MessageEvent), |
| 170 | +} |
| 171 | + |
| 172 | +impl Stream for EventSource { |
| 173 | + type Item = Result<(String, MessageEvent), EventSourceError>; |
| 174 | + |
| 175 | + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { |
| 176 | + let msg = ready!(self.project().message_receiver.poll_next(cx)); |
| 177 | + match msg { |
| 178 | + Some(StreamMessage::Message(event_type, msg)) => { |
| 179 | + Poll::Ready(Some(Ok((event_type, msg)))) |
| 180 | + } |
| 181 | + Some(StreamMessage::ErrorEvent) => { |
| 182 | + Poll::Ready(Some(Err(EventSourceError::ConnectionError))) |
| 183 | + } |
| 184 | + None => Poll::Ready(None), |
| 185 | + } |
| 186 | + } |
| 187 | +} |
| 188 | + |
| 189 | +#[pinned_drop] |
| 190 | +impl PinnedDrop for EventSource { |
| 191 | + fn drop(self: Pin<&mut Self>) { |
| 192 | + self.es.close(); |
| 193 | + } |
| 194 | +} |
| 195 | + |
| 196 | +#[cfg(test)] |
| 197 | +mod tests { |
| 198 | + use super::*; |
| 199 | + use futures::StreamExt; |
| 200 | + use wasm_bindgen_futures::spawn_local; |
| 201 | + use wasm_bindgen_test::*; |
| 202 | + |
| 203 | + wasm_bindgen_test_configure!(run_in_browser); |
| 204 | + |
| 205 | + const SSE_ECHO_SERVER_URL: &str = env!("SSE_ECHO_SERVER_URL"); |
| 206 | + |
| 207 | + #[wasm_bindgen_test] |
| 208 | + fn eventsource_works() { |
| 209 | + let mut es = EventSource::new(SSE_ECHO_SERVER_URL).unwrap(); |
| 210 | + es.subscribe_event("server").unwrap(); |
| 211 | + es.subscribe_event("request").unwrap(); |
| 212 | + |
| 213 | + spawn_local(async move { |
| 214 | + assert_eq!(es.next().await.unwrap().unwrap().0, "server".to_string()); |
| 215 | + assert_eq!(es.next().await.unwrap().unwrap().0, "request".to_string()); |
| 216 | + }); |
| 217 | + } |
| 218 | + |
| 219 | + #[wasm_bindgen_test] |
| 220 | + fn eventsource_close_works() { |
| 221 | + let mut es = EventSource::new("rubbish").unwrap(); |
| 222 | + |
| 223 | + spawn_local(async move { |
| 224 | + // we should expect an immediate failure |
| 225 | + |
| 226 | + assert_eq!( |
| 227 | + es.next().await, |
| 228 | + Some(Err(EventSourceError::ConnectionError)) |
| 229 | + ); |
| 230 | + }) |
| 231 | + } |
| 232 | +} |
0 commit comments