Skip to main content

df_hyperliquid_core/client/web/socket/
mod.rs

1//! The websocket in the browser and Workers: a [`Feed`] carries one [`crate::live::Session`]
2//! over the global `WebSocket` and hands back [`crate::live::Event`]s, each frame's text beside
3//! it when asked. Subscriptions made while down are sent on the next open; a post made while
4//! down is refused, and one cut off by a drop is reported, never resent.
5//!
6//! Everything runs on the one JS thread: the socket's events and the timer call into the
7//! feed as tasks of their own, and [`Feed::next`] waits for the events they leave.
8
9mod js;
10
11use std::{
12    cell::RefCell,
13    collections::VecDeque,
14    future::poll_fn,
15    rc::Rc,
16    task::{Poll, Waker},
17};
18
19use crate::client::web::clock;
20use crate::client::web::socket::js::{Calls, connect, function, random, said};
21use crate::live::{Event, FeedError, PING, Post, Session, Subscription, Tick};
22use js_sys::Function;
23use wasm_bindgen::{JsCast, JsValue};
24use web_sys::{MessageEvent, WebSocket};
25
26/// One websocket connection, kept open. Dropping the feed closes it.
27pub struct Feed {
28    driver: Rc<RefCell<Driver>>,
29}
30
31impl Feed {
32    /// Connects to the session's network.
33    #[must_use]
34    pub fn start(session: Session) -> Feed {
35        let url = session.url();
36        Feed::start_at(url, session)
37    }
38
39    /// Connects to `url` instead of the session's network: a proxy, or a test.
40    #[must_use]
41    pub fn start_at(url: impl Into<String>, session: Session) -> Feed {
42        let global: JsValue = js_sys::global().into();
43        let timers = function(&global, "setTimeout").zip(function(&global, "clearTimeout"));
44        let driver = Rc::new_cyclic(|driver| {
45            RefCell::new(Driver {
46                url: url.into(),
47                session,
48                global,
49                timers,
50                socket: None,
51                timer: None,
52                calls: Calls::new(driver),
53                events: VecDeque::new(),
54                waker: None,
55                stopped: false,
56            })
57        });
58        if let Ok(mut driver) = driver.try_borrow_mut() {
59            if driver.timers.is_some() {
60                driver.dial();
61            } else {
62                driver.stop();
63            }
64        }
65        Feed { driver }
66    }
67
68    /// Wants `subscription` from now on, across reconnects. Refused past the
69    /// session's limits.
70    pub async fn subscribe(&self, subscription: Subscription) -> Result<(), FeedError> {
71        self.with(|driver| {
72            if let Some(frame) = driver.session.subscribe(subscription)? {
73                driver.carry(&frame);
74            }
75            Ok(())
76        })
77    }
78
79    /// Stops wanting `subscription`, and unsubscribes on the socket when it is open. A
80    /// subscription that was not wanted is ignored. [`FeedError::Stopped`] once the feed has stopped.
81    pub fn unsubscribe(&self, subscription: Subscription) -> Result<(), FeedError> {
82        self.with(|driver| {
83            if let Some(frame) = driver.session.unsubscribe(&subscription) {
84                driver.carry(&frame);
85            }
86            Ok(())
87        })
88    }
89
90    /// Sends an info request or a signed action over the socket, and gives
91    /// its id; the answer arrives as [`crate::live::Frame::Post`] with the same id.
92    pub async fn post(&self, request: Post) -> Result<u64, FeedError> {
93        self.with(|driver| {
94            let (id, frame) = driver.session.post(&request)?;
95            driver.carry(&frame);
96            Ok(id)
97        })
98    }
99
100    /// The next event; `None` once the feed has stopped.
101    pub async fn next(&mut self) -> Option<Event> {
102        self.next_with_text().await.map(|(event, _)| event)
103    }
104
105    /// The next event, and for a frame, read or not, the text it arrived as: for a program that
106    /// still reads some channels its own way. `None` once the feed has stopped.
107    pub async fn next_with_text(&mut self) -> Option<(Event, Option<String>)> {
108        poll_fn(|cx| {
109            let Ok(mut driver) = self.driver.try_borrow_mut() else {
110                // Never: the driver is only held inside a call, never across one.
111                cx.waker().wake_by_ref();
112                return Poll::Pending;
113            };
114            if let Some(delivered) = driver.events.pop_front() {
115                return Poll::Ready(Some(delivered));
116            }
117            if driver.stopped {
118                return Poll::Ready(None);
119            }
120            driver.waker = Some(cx.waker().clone());
121            Poll::Pending
122        })
123        .await
124    }
125
126    /// Closes the socket and stops.
127    pub fn close(self) {
128        drop(self);
129    }
130
131    /// Runs `act` on a feed that has not stopped. An event it leaves needs no
132    /// wake: [`Feed::next`] takes the feed mutably, so nothing waits on it.
133    fn with<T>(&self, act: impl FnOnce(&mut Driver) -> Result<T, FeedError>) -> Result<T, FeedError> {
134        let mut driver = self.driver.try_borrow_mut().map_err(|_| FeedError::Stopped)?;
135        if driver.stopped {
136            return Err(FeedError::Stopped);
137        }
138        act(&mut driver)
139    }
140}
141
142impl Drop for Feed {
143    fn drop(&mut self) {
144        if let Ok(mut driver) = self.driver.try_borrow_mut() {
145            driver.stop();
146        }
147    }
148}
149
150/// The feed's state. The socket's handlers and the timer hold it weakly, so
151/// the feed alone keeps it, and with it every closure JS can call.
152struct Driver {
153    url: String,
154    session: Session,
155    global: JsValue,
156    /// The global `setTimeout` and `clearTimeout`.
157    timers: Option<(Function, Function)>,
158    /// The socket dialling or open; none while waiting to dial again.
159    socket: Option<WebSocket>,
160    /// The pending timeout: the next tick while open, the next dial while
161    /// closed, none while dialling. A browser gives a number, Node an object.
162    timer: Option<JsValue>,
163    calls: Calls,
164    /// Each event, and for a frame the text it arrived as.
165    events: VecDeque<(Event, Option<String>)>,
166    waker: Option<Waker>,
167    stopped: bool,
168}
169
170impl Driver {
171    /// A new socket. While it dials, the session still answers: a subscription
172    /// is kept for the open, a post is refused. Nothing waits on a handshake.
173    fn dial(&mut self) {
174        match connect(&self.global, &self.url) {
175            Ok(socket) => {
176                socket.set_onopen(Some(self.calls.open.as_ref().unchecked_ref()));
177                socket.set_onmessage(Some(self.calls.message.as_ref().unchecked_ref()));
178                socket.set_onclose(Some(self.calls.close.as_ref().unchecked_ref()));
179                socket.set_onerror(Some(self.calls.error.as_ref().unchecked_ref()));
180                self.socket = Some(socket);
181            }
182            Err(reason) => self.lost(reason),
183        }
184    }
185
186    fn opened(&mut self) {
187        for frame in self.session.opened(clock()) {
188            if let Err(reason) = self.send(&frame) {
189                return self.lost(reason);
190            }
191        }
192        self.events.push_back((Event::Opened, None));
193        self.arm_tick();
194    }
195
196    fn received(&mut self, message: &MessageEvent) {
197        // The venue sends text only; anything else is not its.
198        let Some(text) = message.data().as_string() else { return };
199        let event = match self.session.received(clock(), &text) {
200            Ok(frame) => Event::Frame(Box::new(frame)),
201            Err(bad) => Event::Unreadable(bad),
202        };
203        self.events.push_back((event, Some(text)));
204    }
205
206    /// The timer fired: a tick while open, the next dial while closed.
207    fn woke(&mut self) {
208        self.timer = None;
209        if self.session.is_open() {
210            match self.session.tick(clock()) {
211                Tick::Wait => {}
212                Tick::Ping => {
213                    if let Err(reason) = self.send(PING) {
214                        return self.lost(reason);
215                    }
216                }
217                Tick::Reconnect => return self.lost("nothing arrived for too long".to_owned()),
218            }
219            self.arm_tick();
220        } else if self.socket.is_none() {
221            self.dial();
222        }
223    }
224
225    /// Sends `frame`, or drops a socket that will not take it.
226    fn carry(&mut self, frame: &str) {
227        if let Err(reason) = self.send(frame) {
228            self.lost(reason);
229        }
230    }
231
232    fn send(&self, frame: &str) -> Result<(), String> {
233        let Some(socket) = &self.socket else { return Err("no socket to send on".to_owned()) };
234        socket.send_with_str(frame).map_err(|error| said(&error).unwrap_or_else(|| "the send failed".to_owned()))
235    }
236
237    /// The socket is gone, or never came: report it with the session's delay,
238    /// and dial again after it.
239    fn lost(&mut self, reason: String) {
240        self.hang_up();
241        let retry = self.session.closed(clock(), random());
242        let after = retry.after_ms;
243        self.events.push_back((Event::Closed { reason, retry }, None));
244        self.arm(after);
245    }
246
247    /// Closes the socket after taking its handlers off, so nothing it still
248    /// has queued reaches the feed. A half-open socket's close may never
249    /// finish; nothing waits for it.
250    fn hang_up(&mut self) {
251        if let Some(socket) = self.socket.take() {
252            socket.set_onopen(None);
253            socket.set_onmessage(None);
254            socket.set_onclose(None);
255            socket.set_onerror(None);
256            let _ = socket.close();
257        }
258    }
259
260    fn stop(&mut self) {
261        self.hang_up();
262        self.disarm();
263        self.stopped = true;
264    }
265
266    /// The timer for the session's next tick, while open.
267    fn arm_tick(&mut self) {
268        if let Some(at) = self.session.due() {
269            self.arm(at.saturating_sub(clock()));
270        }
271    }
272
273    /// One timeout for `ms`, in place of any pending. Without a timer the feed
274    /// can neither tell a dead socket nor dial again, so it stops.
275    fn arm(&mut self, ms: u64) {
276        self.disarm();
277        let Some((set_timeout, _)) = &self.timers else { return self.stop() };
278        let delay = JsValue::from(u32::try_from(ms).map_or(LONGEST_DELAY, |ms| ms.min(LONGEST_DELAY)));
279        match set_timeout.call2(&self.global, self.calls.wake.as_ref(), &delay) {
280            Ok(timer) => self.timer = Some(timer),
281            Err(_) => self.stop(),
282        }
283    }
284
285    fn disarm(&mut self) {
286        if let (Some(timer), Some((_, clear_timeout))) = (self.timer.take(), &self.timers) {
287            let _ = clear_timeout.call1(&self.global, &timer);
288        }
289    }
290
291    /// The waker to call once the driver is let go, when `next` has something.
292    fn wakeable(&mut self) -> Option<Waker> {
293        if self.events.is_empty() && !self.stopped { None } else { self.waker.take() }
294    }
295}
296
297/// The longest delay `setTimeout` keeps; a longer one fires at once.
298const LONGEST_DELAY: u32 = 0x7fff_ffff;
299
300#[cfg(test)]
301#[cfg(target_arch = "wasm32")]
302#[path = "tests/feed.rs"]
303mod tests;