Skip to main content

df_hyperliquid_core/live/store/
interest.rs

1//! What readers need kept live, counted, and the subscriptions that serve it. A subscription is
2//! wanted while any interest needs it; letting go and taking hold again before the next
3//! [`Store::changes`](crate::live::store::Store::changes) costs nothing on the socket.
4
5use std::{
6    collections::{BTreeMap, HashMap, HashSet},
7    sync::mpsc::{self, Receiver, Sender},
8};
9
10use crate::live::{Limits, Refused, Subscription};
11use crate::markets::Interval;
12use crate::utils::Address;
13
14/// What a reader needs kept live. A coin is spelled as the venue spells it: `BTC`, `xyz:XYZ100`
15/// (HIP-3), `@107` or `PURR/USDC` (spot), `#14720` (an outcome side).
16#[derive(Debug, Clone, PartialEq, Eq, Hash)]
17#[non_exhaustive]
18pub enum Interest {
19    /// A market's whole book, ungrouped: its frames name no grouping, so one book a coin.
20    Book {
21        /// The coin.
22        coin: String,
23    },
24    /// A market's prints.
25    Trades {
26        /// The coin.
27        coin: String,
28    },
29    /// A market's candles at one interval.
30    Candles {
31        /// The coin.
32        coin: String,
33        /// The candle interval.
34        interval: Interval,
35    },
36    /// Every coin's mid on one perp dex, `""` the first, which also carries spot and outcomes.
37    Mids {
38        /// The dex, `""` for the first.
39        dex: String,
40    },
41    /// One market's context: a perp's, a spot pair's or an outcome side's.
42    Context {
43        /// The coin.
44        coin: String,
45    },
46    /// Every perp's context on every dex, in one frame.
47    PerpContexts,
48    /// Every spot pair's and outcome side's context, in one frame.
49    SpotContexts,
50    /// An account's clearinghouse on every dex, its spot balances and its mode: what its
51    /// positions, usable balances and worth are read from.
52    State {
53        /// The account.
54        user: Address,
55    },
56    /// An account's resting orders on one dex; spot and outcome orders come with the first.
57    Orders {
58        /// The account.
59        user: Address,
60        /// The dex, `""` for the first.
61        dex: String,
62    },
63    /// An account's fills.
64    Fills {
65        /// The account.
66        user: Address,
67    },
68    /// An account's funding payments.
69    Fundings {
70        /// The account.
71        user: Address,
72    },
73    /// Deposits, withdrawals, transfers and every other ledger row but funding.
74    Ledger {
75        /// The account.
76        user: Address,
77    },
78}
79
80impl Interest {
81    /// The subscriptions that serve it.
82    #[must_use]
83    pub fn subscriptions(&self) -> Vec<Subscription> {
84        match self {
85            Interest::Book { coin } => {
86                vec![Subscription::L2Book { coin: coin.clone(), n_sig_figs: None, mantissa: None, fast: false }]
87            }
88            Interest::Trades { coin } => vec![Subscription::Trades { coin: coin.clone() }],
89            Interest::Candles { coin, interval } => {
90                vec![Subscription::Candle { coin: coin.clone(), interval: *interval }]
91            }
92            Interest::Mids { dex } => vec![Subscription::AllMids { dex: dex.clone() }],
93            Interest::Context { coin } => vec![Subscription::ActiveAssetCtx { coin: coin.clone() }],
94            Interest::PerpContexts => vec![Subscription::AllDexsAssetCtxs],
95            Interest::SpotContexts => vec![Subscription::SpotAssetCtxs],
96            Interest::State { user } => vec![
97                Subscription::AllDexsClearinghouseState { user: *user },
98                Subscription::SpotState { user: *user, ignore_portfolio_margin: false },
99                Subscription::WebData3 { user: *user },
100            ],
101            Interest::Orders { user, dex } => vec![Subscription::OpenOrders { user: *user, dex: dex.clone() }],
102            Interest::Fills { user } => vec![Subscription::UserFills { user: *user, aggregate_by_time: false }],
103            Interest::Fundings { user } => vec![Subscription::UserFundings { user: *user }],
104            Interest::Ledger { user } => vec![Subscription::UserNonFundingLedgerUpdates { user: *user }],
105        }
106    }
107
108    /// The account it follows, for the ones that follow one.
109    #[must_use]
110    pub const fn user(&self) -> Option<Address> {
111        match self {
112            Interest::State { user }
113            | Interest::Orders { user, .. }
114            | Interest::Fills { user }
115            | Interest::Fundings { user }
116            | Interest::Ledger { user } => Some(*user),
117            _ => None,
118        }
119    }
120}
121
122/// A hold on an interest. Dropping it ends the interest, as
123/// [`Store::release`](crate::live::store::Store::release) does.
124#[must_use = "dropping a handle ends its interest"]
125#[derive(Debug)]
126pub struct Handle {
127    id: u64,
128    interest: Interest,
129    released: Sender<u64>,
130}
131
132impl Handle {
133    /// The interest it holds.
134    #[must_use]
135    pub const fn interest(&self) -> &Interest {
136        &self.interest
137    }
138}
139
140impl Drop for Handle {
141    fn drop(&mut self) {
142        // The store may be gone already; then there is nothing left to end.
143        let _ = self.released.send(self.id);
144    }
145}
146
147/// What to tell the socket: what nothing needs any more, then what is newly needed, each in the
148/// order it was first wanted.
149#[derive(Debug, Clone, Default, PartialEq, Eq)]
150#[non_exhaustive]
151pub struct Changes {
152    /// Subscriptions to drop, sent first.
153    pub unsubscribe: Vec<Subscription>,
154    /// Subscriptions to add.
155    pub subscribe: Vec<Subscription>,
156}
157
158impl Changes {
159    /// Whether there is nothing to send.
160    #[must_use]
161    pub fn is_empty(&self) -> bool {
162        self.unsubscribe.is_empty() && self.subscribe.is_empty()
163    }
164}
165
166/// Every interest held, and the subscriptions they add up to.
167#[derive(Debug)]
168pub(crate) struct Interests {
169    limits: Limits,
170    next: u64,
171    held: BTreeMap<u64, Interest>,
172    /// How many interests need each subscription.
173    counts: HashMap<Subscription, usize>,
174    /// The wanted subscriptions, in the order each was first wanted.
175    order: Vec<Subscription>,
176    /// What the socket was last told to hold.
177    active: Vec<Subscription>,
178    /// The accounts followed, in the order first followed.
179    users: Vec<Address>,
180    released: Receiver<u64>,
181    sender: Sender<u64>,
182}
183
184impl Interests {
185    pub(crate) fn new(limits: Limits) -> Interests {
186        let (sender, released) = mpsc::channel();
187        Interests {
188            limits,
189            next: 1,
190            held: BTreeMap::new(),
191            counts: HashMap::new(),
192            order: Vec::new(),
193            active: Vec::new(),
194            users: Vec::new(),
195            released,
196            sender,
197        }
198    }
199
200    pub(crate) fn set_limits(&mut self, limits: Limits) {
201        self.limits = limits;
202    }
203
204    /// Holds `interest`, unless what it needs would take the subscriptions or the users past the
205    /// limits, or the venue would not take one of them; then nothing of it is held.
206    pub(crate) fn register(&mut self, interest: Interest) -> Result<Handle, Refused> {
207        let needed = interest.subscriptions();
208        let mut new: Vec<&Subscription> = Vec::new();
209        for subscription in &needed {
210            subscription.check()?;
211            if !self.counts.contains_key(subscription) && !new.contains(&subscription) {
212                new.push(subscription);
213            }
214        }
215        if self.order.len().saturating_add(new.len()) > self.limits.subscriptions {
216            return Err(Refused::Subscriptions { limit: self.limits.subscriptions });
217        }
218        if let Some(user) = interest.user()
219            && !self.users.contains(&user)
220        {
221            if self.users.len() >= self.limits.users {
222                return Err(Refused::Users { limit: self.limits.users });
223            }
224            self.users.push(user);
225        }
226        for subscription in needed {
227            let count = self.counts.entry(subscription.clone()).or_insert(0);
228            if *count == 0 {
229                self.order.push(subscription);
230            }
231            *count = count.saturating_add(1);
232        }
233        let id = self.next;
234        self.next = self.next.saturating_add(1);
235        self.held.insert(id, interest.clone());
236        Ok(Handle { id, interest, released: self.sender.clone() })
237    }
238
239    /// Ends every interest whose handle was dropped. Says whether any was.
240    pub(crate) fn drain(&mut self) -> bool {
241        let mut any = false;
242        while let Ok(id) = self.released.try_recv() {
243            let Some(interest) = self.held.remove(&id) else { continue };
244            any = true;
245            for subscription in interest.subscriptions() {
246                let Some(count) = self.counts.get_mut(&subscription) else { continue };
247                *count = count.saturating_sub(1);
248                if *count == 0 {
249                    self.counts.remove(&subscription);
250                    self.order.retain(|wanted| *wanted != subscription);
251                }
252            }
253        }
254        let order = &self.order;
255        self.users.retain(|user| order.iter().any(|wanted| wanted.user() == Some(*user)));
256        any
257    }
258
259    /// Whether an interest needs `subscription` now.
260    pub(crate) fn wants(&self, subscription: &Subscription) -> bool {
261        self.counts.contains_key(subscription)
262    }
263
264    /// Every subscription an interest needs, in the order first wanted.
265    pub(crate) fn wanted(&self) -> &[Subscription] {
266        &self.order
267    }
268
269    /// What changed since the socket was last told, which it now is.
270    pub(crate) fn changes(&mut self) -> Changes {
271        let held: HashSet<&Subscription> = self.active.iter().collect();
272        let unsubscribe = self.active.iter().filter(|held| !self.counts.contains_key(*held)).cloned().collect();
273        let subscribe = self.order.iter().filter(|wanted| !held.contains(wanted)).cloned().collect();
274        self.active.clone_from(&self.order);
275        Changes { unsubscribe, subscribe }
276    }
277
278    /// A subscription the socket refused: no longer held there, so the next changes ask again.
279    pub(crate) fn refused(&mut self, subscription: &Subscription) {
280        self.active.retain(|held| held != subscription);
281    }
282
283    /// The accounts the wanted subscriptions follow, in the order first followed.
284    pub(crate) fn users(&self) -> &[Address] {
285        &self.users
286    }
287}
288
289#[cfg(test)]
290#[path = "tests/interest.rs"]
291mod tests;