Skip to main content

df_hyperliquid_core/live/session/
mod.rs

1//! One connection's state with no socket and no clock: the socket's owner hands in what happened
2//! and when, and sends what comes back. Of the venue's per-IP limits, subscriptions, users and
3//! posts in flight are refused here; connections and message rates are the owner's to keep.
4
5pub mod limits;
6pub mod timing;
7
8pub use limits::{
9    Limits, MAX_CONNECTIONS, MAX_INFLIGHT_POSTS, MAX_MESSAGES_PER_MINUTE, MAX_NEW_CONNECTIONS_PER_MINUTE,
10    MAX_SUBSCRIPTIONS, MAX_USERS, Refused,
11};
12pub use timing::{Retry, Tick, Timing};
13
14use crate::client::Network;
15use crate::live::{BadFrame, Frame, Post, Subscription, decode, post, subscribe, unsubscribe};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18enum Link {
19    Closed,
20    Open {
21        /// When it opened.
22        since: u64,
23        /// When anything last arrived; `since` until something does.
24        heard: u64,
25        /// When the venue last sent what keeps the socket open on its side, a pong or a
26        /// subscription's data; `since` until it does. Its acks, refusals and post answers do
27        /// not count: a socket that gets only acks is closed at 60 s all the same.
28        kept: u64,
29        /// Whether anything has arrived at all.
30        talked: bool,
31        /// When the last ping went out; `since` until one does.
32        pinged: u64,
33    },
34}
35
36/// One connection to one network's websocket.
37#[derive(Debug, Clone)]
38pub struct Session {
39    network: Network,
40    limits: Limits,
41    timing: Timing,
42    wanted: Vec<Subscription>,
43    link: Link,
44    /// Reconnects since a socket last worked.
45    failures: u32,
46    next_id: u64,
47    waiting: Vec<u64>,
48}
49
50impl Session {
51    /// A closed session on `network`, with the venue's limits and the default timing.
52    #[must_use]
53    pub fn new(network: Network) -> Self {
54        Session {
55            network,
56            limits: Limits::VENUE,
57            timing: Timing::DEFAULT,
58            wanted: Vec::new(),
59            link: Link::Closed,
60            failures: 0,
61            next_id: 1,
62            waiting: Vec::new(),
63        }
64    }
65
66    /// The limits are per IP: sessions sharing one split them.
67    #[must_use]
68    pub const fn with_limits(mut self, limits: Limits) -> Self {
69        self.limits = limits;
70        self
71    }
72
73    /// The same session with other timing.
74    #[must_use]
75    pub const fn with_timing(mut self, timing: Timing) -> Self {
76        self.timing = timing;
77        self
78    }
79
80    /// The network it connects to.
81    #[must_use]
82    pub const fn network(&self) -> Network {
83        self.network
84    }
85
86    /// Where to connect: the network's public websocket.
87    #[must_use]
88    pub const fn url(&self) -> &'static str {
89        self.network.ws_url()
90    }
91
92    /// Whether a socket is open, from [`Session::opened`] until [`Session::closed`].
93    #[must_use]
94    pub const fn is_open(&self) -> bool {
95        matches!(self.link, Link::Open { .. })
96    }
97
98    /// What this session subscribes to on every socket, in the order it was asked for.
99    #[must_use]
100    pub fn wanted(&self) -> &[Subscription] {
101        &self.wanted
102    }
103
104    /// The distinct users the wanted subscriptions follow.
105    #[must_use]
106    pub fn users(&self) -> usize {
107        let mut users: Vec<_> = self.wanted.iter().filter_map(Subscription::user).collect();
108        users.sort_unstable();
109        users.dedup();
110        users.len()
111    }
112
113    /// The ids of posts sent on this socket and not yet answered.
114    #[must_use]
115    pub fn waiting(&self) -> &[u64] {
116        &self.waiting
117    }
118
119    /// Wants `subscription` from now on, on this socket and every later one. Gives the frame to
120    /// send when the socket is open and it is new; nothing when it was already wanted. Past the
121    /// limits, or when the venue would not take it, it is refused and not kept.
122    pub fn subscribe(&mut self, subscription: Subscription) -> Result<Option<String>, Refused> {
123        if self.wanted.contains(&subscription) {
124            return Ok(None);
125        }
126        subscription.check()?;
127        if self.wanted.len() >= self.limits.subscriptions {
128            return Err(Refused::Subscriptions { limit: self.limits.subscriptions });
129        }
130        if let Some(user) = subscription.user()
131            && !self.wanted.iter().any(|wanted| wanted.user() == Some(user))
132            && self.users() >= self.limits.users
133        {
134            return Err(Refused::Users { limit: self.limits.users });
135        }
136        let frame = self.is_open().then(|| subscribe(&subscription));
137        self.wanted.push(subscription);
138        Ok(frame)
139    }
140
141    /// Stops wanting `subscription`. Gives the frame to send when the socket is open and it was
142    /// wanted.
143    pub fn unsubscribe(&mut self, subscription: &Subscription) -> Option<String> {
144        let at = self.wanted.iter().position(|wanted| wanted == subscription)?;
145        let gone = self.wanted.remove(at);
146        self.is_open().then(|| unsubscribe(&gone))
147    }
148
149    /// Gives the next post's id and its frame. Only on an open socket, and only while fewer
150    /// than the limit are waiting for an answer.
151    pub fn post(&mut self, request: &Post) -> Result<(u64, String), Refused> {
152        if !self.is_open() {
153            return Err(Refused::Closed);
154        }
155        if self.waiting.len() >= self.limits.posts {
156            return Err(Refused::Posts { limit: self.limits.posts });
157        }
158        let id = self.next_id;
159        self.next_id = self.next_id.saturating_add(1);
160        self.waiting.push(id);
161        Ok((id, post(id, request)))
162    }
163
164    /// The socket opened at `now`. Gives the frames that subscribe to everything wanted, in
165    /// order.
166    pub fn opened(&mut self, now: u64) -> Vec<String> {
167        self.link = Link::Open { since: now, heard: now, kept: now, talked: false, pinged: now };
168        self.wanted.iter().map(subscribe).collect()
169    }
170
171    /// A text frame arrived at `now`. Anything that arrives shows the socket is alive, whether it
172    /// reads or not; only a pong or a subscription's data puts off the next ping. A post's answer
173    /// or refusal stops it waiting.
174    pub fn received(&mut self, now: u64, text: &str) -> Result<Frame, BadFrame> {
175        let frame = decode(text);
176        if let Link::Open { heard, kept, talked, .. } = &mut self.link {
177            *heard = (*heard).max(now);
178            *talked = true;
179            if frame.as_ref().is_ok_and(|frame| !matches!(frame, Frame::Ack(_) | Frame::Error(_) | Frame::Post(_))) {
180                *kept = (*kept).max(now);
181            }
182        }
183        let answered = match &frame {
184            Ok(Frame::Post(reply)) => Some(reply.id),
185            Ok(Frame::Error(refusal)) => refusal.post_id(),
186            _ => None,
187        };
188        if let Some(id) = answered {
189            self.waiting.retain(|waiting| *waiting != id);
190        }
191        frame
192    }
193}
194
195#[cfg(test)]
196#[path = "tests/session.rs"]
197mod tests;