Skip to main content

df_hyperliquid_core/client/native/
socket.rs

1//! The websocket for native programs: a [`Feed`] carries one [`crate::live::Session`]
2//! over tokio-tungstenite and hands back [`crate::live::Event`]s, each frame's text beside it
3//! when asked. Subscriptions made while down are sent on the next open; a post made while down
4//! is refused, and one cut off by a drop is reported, never resent.
5
6use std::time::{Duration, SystemTime, UNIX_EPOCH};
7
8use crate::live::{Event, FeedError, PING, Post, Refused, Session, Subscription, Tick};
9use futures_util::{SinkExt, StreamExt};
10use tokio::{
11    net::TcpStream,
12    sync::{mpsc, oneshot},
13    task::JoinHandle,
14    time::{Instant, sleep_until},
15};
16use tokio_tungstenite::{
17    MaybeTlsStream, WebSocketStream, connect_async,
18    tungstenite::{Message, Utf8Bytes},
19};
20
21use crate::client::native::clock;
22
23enum Command {
24    Subscribe(Subscription, oneshot::Sender<Result<(), Refused>>),
25    Unsubscribe(Subscription),
26    Post(Post, oneshot::Sender<Result<u64, Refused>>),
27}
28
29/// An event, and for a frame the text it arrived as.
30type Delivered = (Event, Option<Utf8Bytes>);
31
32/// One websocket connection, kept open. Dropping the feed closes it.
33pub struct Feed {
34    commands: mpsc::UnboundedSender<Command>,
35    events: mpsc::UnboundedReceiver<Delivered>,
36    task: JoinHandle<()>,
37}
38
39impl Feed {
40    /// Connects to the session's network on the current tokio runtime.
41    #[must_use]
42    pub fn start(session: Session) -> Feed {
43        let url = session.url();
44        Feed::start_at(url, session)
45    }
46
47    /// Connects to `url` instead of the session's network: a proxy, or a test.
48    #[must_use]
49    pub fn start_at(url: impl Into<String>, session: Session) -> Feed {
50        let (commands, inbox) = mpsc::unbounded_channel();
51        let (outbox, events) = mpsc::unbounded_channel();
52        let task = tokio::spawn(run(url.into(), session, inbox, outbox));
53        Feed { commands, events, task }
54    }
55
56    /// Wants `subscription` from now on, across reconnects. Refused past the
57    /// session's limits.
58    pub async fn subscribe(&self, subscription: Subscription) -> Result<(), FeedError> {
59        let (reply, answer) = oneshot::channel();
60        self.commands.send(Command::Subscribe(subscription, reply)).map_err(|_| FeedError::Stopped)?;
61        Ok(answer.await.map_err(|_| FeedError::Stopped)??)
62    }
63
64    /// Stops wanting `subscription`, and unsubscribes on the socket when it is open. A
65    /// subscription that was not wanted is ignored. [`FeedError::Stopped`] once the feed has stopped.
66    pub fn unsubscribe(&self, subscription: Subscription) -> Result<(), FeedError> {
67        self.commands.send(Command::Unsubscribe(subscription)).map_err(|_| FeedError::Stopped)
68    }
69
70    /// Sends an info request or a signed action over the socket, and gives
71    /// its id; the answer arrives as [`crate::live::Frame::Post`] with the same id.
72    pub async fn post(&self, request: Post) -> Result<u64, FeedError> {
73        let (reply, answer) = oneshot::channel();
74        self.commands.send(Command::Post(request, reply)).map_err(|_| FeedError::Stopped)?;
75        Ok(answer.await.map_err(|_| FeedError::Stopped)??)
76    }
77
78    /// The next event; `None` once the feed has stopped.
79    pub async fn next(&mut self) -> Option<Event> {
80        self.events.recv().await.map(|(event, _)| event)
81    }
82
83    /// The next event, and for a frame, read or not, the text it arrived as: for a program that
84    /// still reads some channels its own way. `None` once the feed has stopped.
85    pub async fn next_with_text(&mut self) -> Option<(Event, Option<String>)> {
86        let (event, text) = self.events.recv().await?;
87        Some((event, text.map(|text| text.as_str().to_owned())))
88    }
89
90    /// Closes the socket and stops.
91    pub fn close(self) {
92        drop(self);
93    }
94}
95
96impl Drop for Feed {
97    fn drop(&mut self) {
98        self.task.abort();
99    }
100}
101
102type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;
103
104/// Whether the connection was lost, and why, or the feed is done.
105enum Outcome {
106    Lost(String),
107    Stop,
108}
109
110async fn run(
111    url: String,
112    mut session: Session,
113    mut commands: mpsc::UnboundedReceiver<Command>,
114    events: mpsc::UnboundedSender<Delivered>,
115) {
116    loop {
117        // While it dials, the session still answers: a subscription is kept for
118        // the open, a post is refused. Nothing waits on a handshake.
119        let dial = connect_async(url.as_str());
120        tokio::pin!(dial);
121        let dialled = loop {
122            tokio::select! {
123                dialled = &mut dial => break dialled,
124                command = commands.recv() => match command {
125                    Some(command) => {
126                        handle(&mut session, command);
127                    }
128                    None => return,
129                },
130            }
131        };
132        let reason = match dialled {
133            Ok((mut socket, _)) => match open(&mut socket, &mut session, &mut commands, &events).await {
134                Outcome::Lost(reason) => reason,
135                Outcome::Stop => return,
136            },
137            Err(error) => error.to_string(),
138        };
139        let retry = session.closed(clock(), random());
140        let until = Instant::now() + Duration::from_millis(retry.after_ms);
141        if events.send((Event::Closed { reason, retry }, None)).is_err() {
142            return;
143        }
144        // Until the next dial, subscriptions are kept for it and posts refused.
145        loop {
146            tokio::select! {
147                () = sleep_until(until) => break,
148                command = commands.recv() => match command {
149                    Some(command) => {
150                        handle(&mut session, command);
151                    }
152                    None => return,
153                },
154            }
155        }
156    }
157}
158
159async fn open(
160    socket: &mut Socket,
161    session: &mut Session,
162    commands: &mut mpsc::UnboundedReceiver<Command>,
163    events: &mpsc::UnboundedSender<Delivered>,
164) -> Outcome {
165    for frame in session.opened(clock()) {
166        if let Err(error) = socket.send(Message::text(frame)).await {
167            return Outcome::Lost(error.to_string());
168        }
169    }
170    if events.send((Event::Opened, None)).is_err() {
171        return Outcome::Stop;
172    }
173    loop {
174        let wake = session.due().map(|at| Instant::now() + Duration::from_millis(at.saturating_sub(clock())));
175        tokio::select! {
176            message = socket.next() => match message {
177                Some(Ok(Message::Text(text))) => {
178                    let event = match session.received(clock(), &text) {
179                        Ok(frame) => Event::Frame(Box::new(frame)),
180                        Err(bad) => Event::Unreadable(bad),
181                    };
182                    if events.send((event, Some(text))).is_err() {
183                        return Outcome::Stop;
184                    }
185                }
186                Some(Ok(Message::Close(frame))) => {
187                    return Outcome::Lost(frame.map_or_else(|| "the venue closed the socket".to_owned(), |frame| frame.reason.to_string()));
188                }
189                // Pings are answered by tungstenite; the venue's own heartbeat is text.
190                Some(Ok(_)) => {}
191                Some(Err(error)) => return Outcome::Lost(error.to_string()),
192                None => return Outcome::Lost("the socket ended".to_owned()),
193            },
194            command = commands.recv() => match command {
195                Some(command) => {
196                    if let Some(frame) = handle(session, command)
197                        && let Err(error) = socket.send(Message::text(frame)).await
198                    {
199                        return Outcome::Lost(error.to_string());
200                    }
201                }
202                None => {
203                    let _ = socket.close(None).await;
204                    return Outcome::Stop;
205                }
206            },
207            () = until(wake) => match session.tick(clock()) {
208                Tick::Wait => {}
209                Tick::Ping => {
210                    if let Err(error) = socket.send(Message::text(PING)).await {
211                        return Outcome::Lost(error.to_string());
212                    }
213                }
214                Tick::Reconnect => {
215                    let _ = socket.close(None).await;
216                    return Outcome::Lost("nothing arrived for too long".to_owned());
217                }
218            },
219        }
220    }
221}
222
223/// Puts a command to the session and answers its caller; gives the frame to
224/// send, if the socket is open and there is one.
225fn handle(session: &mut Session, command: Command) -> Option<String> {
226    match command {
227        Command::Subscribe(subscription, reply) => match session.subscribe(subscription) {
228            Ok(frame) => {
229                let _ = reply.send(Ok(()));
230                frame
231            }
232            Err(refused) => {
233                let _ = reply.send(Err(refused));
234                None
235            }
236        },
237        Command::Unsubscribe(subscription) => session.unsubscribe(&subscription),
238        Command::Post(request, reply) => match session.post(&request) {
239            Ok((id, frame)) => {
240                let _ = reply.send(Ok(id));
241                Some(frame)
242            }
243            Err(refused) => {
244                let _ = reply.send(Err(refused));
245                None
246            }
247        },
248    }
249}
250
251async fn until(wake: Option<Instant>) {
252    match wake {
253        Some(at) => sleep_until(at).await,
254        None => std::future::pending().await,
255    }
256}
257
258/// Enough to spread reconnects: many clients dropped at once must not return
259/// at once. Not for anything secret.
260fn random() -> u64 {
261    let nanos = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |since| u64::from(since.subsec_nanos()));
262    nanos.wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ clock().rotate_left(29)
263}
264
265#[cfg(test)]
266#[path = "tests/socket.rs"]
267mod tests;