df_hyperliquid_core/live/store/
interest.rs1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
17#[non_exhaustive]
18pub enum Interest {
19 Book {
21 coin: String,
23 },
24 Trades {
26 coin: String,
28 },
29 Candles {
31 coin: String,
33 interval: Interval,
35 },
36 Mids {
38 dex: String,
40 },
41 Context {
43 coin: String,
45 },
46 PerpContexts,
48 SpotContexts,
50 State {
53 user: Address,
55 },
56 Orders {
58 user: Address,
60 dex: String,
62 },
63 Fills {
65 user: Address,
67 },
68 Fundings {
70 user: Address,
72 },
73 Ledger {
75 user: Address,
77 },
78}
79
80impl Interest {
81 #[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 #[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#[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 #[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 let _ = self.released.send(self.id);
144 }
145}
146
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
150#[non_exhaustive]
151pub struct Changes {
152 pub unsubscribe: Vec<Subscription>,
154 pub subscribe: Vec<Subscription>,
156}
157
158impl Changes {
159 #[must_use]
161 pub fn is_empty(&self) -> bool {
162 self.unsubscribe.is_empty() && self.subscribe.is_empty()
163 }
164}
165
166#[derive(Debug)]
168pub(crate) struct Interests {
169 limits: Limits,
170 next: u64,
171 held: BTreeMap<u64, Interest>,
172 counts: HashMap<Subscription, usize>,
174 order: Vec<Subscription>,
176 active: Vec<Subscription>,
178 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 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 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 pub(crate) fn wants(&self, subscription: &Subscription) -> bool {
261 self.counts.contains_key(subscription)
262 }
263
264 pub(crate) fn wanted(&self) -> &[Subscription] {
266 &self.order
267 }
268
269 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 pub(crate) fn refused(&mut self, subscription: &Subscription) {
280 self.active.retain(|held| held != subscription);
281 }
282
283 pub(crate) fn users(&self) -> &[Address] {
285 &self.users
286 }
287}
288
289#[cfg(test)]
290#[path = "tests/interest.rs"]
291mod tests;