df_hyperliquid_core/client/http/
limit.rs1use std::collections::VecDeque;
6
7pub const LIMIT: u32 = 1_200;
9
10pub const SOFT: u32 = LIMIT / 5 * 4;
13
14pub const WINDOW_MS: u64 = 60_000;
16
17pub const BASE_COOLDOWN_MS: u64 = 2_000;
19
20pub const MAX_COOLDOWN_MS: u64 = 60_000;
22
23const MAX_STRIKES: u32 = 6;
24
25#[must_use]
27pub fn base_weight(kind: &str) -> u32 {
28 match kind {
29 "l2Book" | "allMids" | "clearinghouseState" | "orderStatus" | "spotClearinghouseState" | "exchangeStatus" => 2,
30 "userRole" => 60,
31 _ => 20,
32 }
33}
34
35#[must_use]
38pub fn per_items(kind: &str) -> Option<usize> {
39 match kind {
40 "recentTrades"
41 | "historicalOrders"
42 | "userFills"
43 | "userFillsByTime"
44 | "fundingHistory"
45 | "userFunding"
46 | "nonUserFundingUpdates"
47 | "twapHistory"
48 | "userTwapSliceFills"
49 | "userTwapSliceFillsByTime"
50 | "delegatorHistory"
51 | "delegatorRewards"
52 | "validatorStats" => Some(20),
53 "candleSnapshot" => Some(60),
54 _ => None,
55 }
56}
57
58#[must_use]
60pub fn read_weight(kind: &str, items: usize) -> u32 {
61 let extra = per_items(kind).map_or(0, |per| items / per);
62 base_weight(kind).saturating_add(u32::try_from(extra).unwrap_or(u32::MAX))
63}
64
65#[must_use]
67pub fn action_weight(batched: usize) -> u32 {
68 1u32.saturating_add(u32::try_from(batched / 40).unwrap_or(u32::MAX))
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73#[non_exhaustive]
74pub struct Spent {
75 pub limit: u32,
77 pub minute: u32,
79 pub kinds: Vec<Kind>,
81 pub refused: u32,
83 pub cooldown_ms: u64,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq)]
89#[non_exhaustive]
90pub struct Kind {
91 pub name: String,
93 pub count: u32,
95 pub weight: u32,
97}
98
99#[derive(Debug, Default)]
102pub(crate) struct Meter {
103 sent: VecDeque<(u64, String, u32)>,
104 refused: VecDeque<u64>,
105}
106
107impl Meter {
108 fn prune(&mut self, now: u64) {
110 let gone = |at: u64| at.saturating_add(WINDOW_MS) <= now;
111 while self.sent.front().is_some_and(|(at, _, _)| gone(*at)) {
112 self.sent.pop_front();
113 }
114 while self.refused.front().is_some_and(|at| gone(*at)) {
115 self.refused.pop_front();
116 }
117 }
118
119 pub(crate) fn record(&mut self, now: u64, kind: &str, weight: u32) {
120 self.prune(now);
121 self.sent.push_back((now, kind.to_owned(), weight));
122 }
123
124 pub(crate) fn refuse(&mut self, now: u64) {
125 self.prune(now);
126 self.refused.push_back(now);
127 }
128
129 pub(crate) fn wait_for(&mut self, now: u64, need: u32) -> Option<u64> {
132 self.prune(now);
133 let spent = self.sent.iter().fold(0u32, |sum, (_, _, weight)| sum.saturating_add(*weight));
134 let mut over = spent.saturating_add(need).checked_sub(SOFT).filter(|over| *over > 0)?;
135 for (at, _, weight) in &self.sent {
136 if *weight >= over {
137 return Some(at.saturating_add(WINDOW_MS).saturating_sub(now).max(1));
138 }
139 over -= weight;
140 }
141 Some(WINDOW_MS)
142 }
143
144 pub(crate) fn spent(&mut self, now: u64) -> Spent {
146 self.prune(now);
147 let mut kinds: Vec<Kind> = Vec::new();
148 for (_, name, weight) in &self.sent {
149 match kinds.iter_mut().find(|kind| kind.name == *name) {
150 Some(kind) => {
151 kind.count += 1;
152 kind.weight = kind.weight.saturating_add(*weight);
153 }
154 None => kinds.push(Kind { name: name.clone(), count: 1, weight: *weight }),
155 }
156 }
157 kinds.sort_by(|a, b| b.weight.cmp(&a.weight).then_with(|| a.name.cmp(&b.name)));
158 let minute = kinds.iter().fold(0u32, |sum, kind| sum.saturating_add(kind.weight));
159 Spent {
160 limit: LIMIT,
161 minute,
162 kinds,
163 refused: u32::try_from(self.refused.len()).unwrap_or(u32::MAX),
164 cooldown_ms: 0,
165 }
166 }
167}
168
169#[derive(Debug, Clone, Copy)]
172pub(crate) struct Ticket(u64);
173
174#[derive(Debug, Default)]
177pub(crate) struct Gate {
178 until: u64,
179 strikes: u32,
181 epoch: u64,
183}
184
185impl Gate {
186 pub(crate) fn open(&self, now: u64) -> Result<Ticket, u64> {
188 match self.until > now {
189 true => Err(self.until - now),
190 false => Ok(Ticket(self.epoch)),
191 }
192 }
193
194 pub(crate) fn passed(&mut self, ticket: Ticket) {
197 if ticket.0 == self.epoch {
198 self.strikes = 0;
199 }
200 }
201
202 pub(crate) fn struck(&mut self, ticket: Ticket, now: u64, retry_after_ms: Option<u64>) -> u64 {
206 let wait = match ticket.0 == self.epoch {
207 true => {
208 self.epoch += 1;
209 self.strikes = (self.strikes + 1).min(MAX_STRIKES);
210 let backoff = (BASE_COOLDOWN_MS << (self.strikes - 1)).min(MAX_COOLDOWN_MS);
211 backoff.max(retry_after_ms.unwrap_or(0))
212 }
213 false => retry_after_ms.unwrap_or(0),
214 };
215 self.until = self.until.max(now.saturating_add(wait));
216 self.until.saturating_sub(now)
217 }
218
219 #[must_use]
220 pub(crate) const fn cooldown_ms(&self, now: u64) -> u64 {
221 self.until.saturating_sub(now)
222 }
223}
224
225#[cfg(test)]
226#[path = "tests/limit.rs"]
227mod tests;