nautilus_hyperliquid/http/
rate_limits.rs1use std::time::{Duration, Instant};
17
18use serde_json::Value;
19use tokio::sync::Mutex;
20
21#[derive(Debug)]
22pub struct WeightedLimiter {
23 capacity: f64, refill_per_sec: f64, state: Mutex<State>,
26}
27
28#[derive(Debug)]
29struct State {
30 tokens: f64,
31 last_refill: Instant,
32}
33
34impl WeightedLimiter {
35 pub fn per_minute(capacity: u32) -> Self {
36 let cap = capacity as f64;
37 Self {
38 capacity: cap,
39 refill_per_sec: cap / 60.0,
40 state: Mutex::new(State {
41 tokens: cap,
42 last_refill: Instant::now(),
43 }),
44 }
45 }
46
47 pub async fn acquire(&self, weight: u32) {
49 let need = weight as f64;
50 loop {
51 let mut st = self.state.lock().await;
52 Self::refill_locked(&mut st, self.refill_per_sec, self.capacity);
53
54 if st.tokens >= need {
55 st.tokens -= need;
56 return;
57 }
58 let deficit = need - st.tokens;
59 let secs = deficit / self.refill_per_sec;
60 drop(st);
61 tokio::time::sleep(Duration::from_secs_f64(secs.max(0.01))).await;
62 }
63 }
64
65 pub async fn debit_extra(&self, extra: u32) {
67 if extra == 0 {
68 return;
69 }
70 let mut st = self.state.lock().await;
71 Self::refill_locked(&mut st, self.refill_per_sec, self.capacity);
72 st.tokens = (st.tokens - extra as f64).max(0.0);
73 }
74
75 pub async fn snapshot(&self) -> RateLimitSnapshot {
76 let mut st = self.state.lock().await;
77 Self::refill_locked(&mut st, self.refill_per_sec, self.capacity);
78 RateLimitSnapshot {
79 capacity: self.capacity as u32,
80 tokens: st.tokens.max(0.0) as u32,
81 }
82 }
83
84 fn refill_locked(st: &mut State, per_sec: f64, cap: f64) {
85 let dt = Instant::now().duration_since(st.last_refill).as_secs_f64();
86 if dt > 0.0 {
87 st.tokens = (st.tokens + dt * per_sec).min(cap);
88 st.last_refill = Instant::now();
89 }
90 }
91}
92
93#[derive(Debug, Clone, Copy)]
94pub struct RateLimitSnapshot {
95 pub capacity: u32,
96 pub tokens: u32,
97}
98
99pub fn backoff_full_jitter(attempt: u32, base: Duration, cap: Duration) -> Duration {
100 use std::{
101 collections::hash_map::DefaultHasher,
102 hash::{Hash, Hasher},
103 };
104
105 let mut hasher = DefaultHasher::new();
107 attempt.hash(&mut hasher);
108 Instant::now().elapsed().as_nanos().hash(&mut hasher);
109 let hash = hasher.finish();
110
111 let max = (base.as_millis() as u64)
112 .saturating_mul(1u64 << attempt.min(16))
113 .min(cap.as_millis() as u64)
114 .max(base.as_millis() as u64);
115 Duration::from_millis(hash % max)
116}
117
118pub fn info_base_weight(req: &crate::http::query::InfoRequest) -> u32 {
121 match req.request_type.as_str() {
122 "l2Book"
124 | "allMids"
125 | "clearinghouseState"
126 | "orderStatus"
127 | "spotClearinghouseState"
128 | "exchangeStatus" => 2,
129 "userRole" => 60,
131 _ => 20,
133 }
134}
135
136pub fn info_extra_weight(req: &crate::http::query::InfoRequest, json: &Value) -> u32 {
139 let items = match json {
140 Value::Array(a) => a.len(),
141 Value::Object(m) => m
142 .values()
143 .filter_map(|v| v.as_array().map(|a| a.len()))
144 .max()
145 .unwrap_or(0),
146 _ => 0,
147 };
148
149 let unit = match req.request_type.as_str() {
150 "candleSnapshot" => 60usize, "recentTrades"
152 | "historicalOrders"
153 | "userFills"
154 | "userFillsByTime"
155 | "fundingHistory"
156 | "userFunding"
157 | "nonUserFundingUpdates"
158 | "twapHistory"
159 | "userTwapSliceFills"
160 | "userTwapSliceFillsByTime"
161 | "delegatorHistory"
162 | "delegatorRewards"
163 | "validatorStats" => 20usize, _ => return 0,
165 };
166 (items / unit) as u32
167}
168
169pub fn exchange_weight(action: &crate::http::query::ExchangeAction) -> u32 {
171 use crate::http::query::ExchangeActionParams;
172
173 let batch_size = match &action.params {
175 ExchangeActionParams::Order(params) => params.orders.len(),
176 ExchangeActionParams::Cancel(params) => params.cancels.len(),
177 ExchangeActionParams::Modify(_) => {
178 1
180 }
181 ExchangeActionParams::UpdateLeverage(_) | ExchangeActionParams::UpdateIsolatedMargin(_) => {
182 0
183 }
184 };
185 1 + (batch_size as u32 / 40)
186}
187
188#[cfg(test)]
193mod tests {
194 use rstest::rstest;
195
196 use super::*;
197 use crate::http::query::{
198 CancelParams, ExchangeAction, ExchangeActionParams, ExchangeActionType, OrderParams,
199 UpdateLeverageParams,
200 };
201
202 #[rstest]
203 #[case(1, 1)]
204 #[case(39, 1)]
205 #[case(40, 2)]
206 #[case(79, 2)]
207 #[case(80, 3)]
208 fn test_exchange_weight_order_steps_every_40(
209 #[case] array_len: usize,
210 #[case] expected_weight: u32,
211 ) {
212 use rust_decimal::Decimal;
213
214 use super::super::models::{
215 Cloid, HyperliquidExecGrouping, HyperliquidExecLimitParams, HyperliquidExecOrderKind,
216 HyperliquidExecPlaceOrderRequest, HyperliquidExecTif,
217 };
218
219 let orders: Vec<HyperliquidExecPlaceOrderRequest> = (0..array_len)
220 .map(|_| HyperliquidExecPlaceOrderRequest {
221 asset: 0,
222 is_buy: true,
223 price: Decimal::new(50000, 0),
224 size: Decimal::new(1, 0),
225 reduce_only: false,
226 kind: HyperliquidExecOrderKind::Limit {
227 limit: HyperliquidExecLimitParams {
228 tif: HyperliquidExecTif::Gtc,
229 },
230 },
231 cloid: Some(Cloid::from_hex("0x00000000000000000000000000000000").unwrap()),
232 })
233 .collect();
234
235 let action = ExchangeAction {
236 action_type: ExchangeActionType::Order,
237 params: ExchangeActionParams::Order(OrderParams {
238 orders,
239 grouping: HyperliquidExecGrouping::Na,
240 }),
241 };
242 assert_eq!(exchange_weight(&action), expected_weight);
243 }
244
245 #[rstest]
246 fn test_exchange_weight_cancel() {
247 use super::super::models::{Cloid, HyperliquidExecCancelByCloidRequest};
248
249 let cancels: Vec<HyperliquidExecCancelByCloidRequest> = (0..40)
250 .map(|_| HyperliquidExecCancelByCloidRequest {
251 asset: 0,
252 cloid: Cloid::from_hex("0x00000000000000000000000000000000").unwrap(),
253 })
254 .collect();
255
256 let action = ExchangeAction {
257 action_type: ExchangeActionType::Cancel,
258 params: ExchangeActionParams::Cancel(CancelParams { cancels }),
259 };
260 assert_eq!(exchange_weight(&action), 2);
261 }
262
263 #[rstest]
264 fn test_exchange_weight_non_batch_action() {
265 let update_leverage = ExchangeAction {
266 action_type: ExchangeActionType::UpdateLeverage,
267 params: ExchangeActionParams::UpdateLeverage(UpdateLeverageParams {
268 asset: 1,
269 is_cross: true,
270 leverage: 10,
271 }),
272 };
273 assert_eq!(exchange_weight(&update_leverage), 1);
274 }
275
276 #[tokio::test]
277 async fn test_limiter_roughly_caps_to_capacity() {
278 let limiter = WeightedLimiter::per_minute(1200);
279
280 for _ in 0..60 {
282 limiter.acquire(20).await; }
284
285 let t0 = std::time::Instant::now();
287 limiter.acquire(20).await;
288 let elapsed = t0.elapsed();
289
290 assert!(
292 elapsed.as_millis() >= 500,
293 "Expected significant delay, was {}ms",
294 elapsed.as_millis()
295 );
296 }
297
298 #[tokio::test]
299 async fn test_limiter_debit_extra_works() {
300 let limiter = WeightedLimiter::per_minute(100);
301
302 let snapshot = limiter.snapshot().await;
304 assert_eq!(snapshot.capacity, 100);
305 assert_eq!(snapshot.tokens, 100);
306
307 limiter.acquire(30).await;
309 let snapshot = limiter.snapshot().await;
310 assert_eq!(snapshot.tokens, 70);
311
312 limiter.debit_extra(20).await;
314 let snapshot = limiter.snapshot().await;
315 assert_eq!(snapshot.tokens, 50);
316
317 limiter.debit_extra(100).await;
319 let snapshot = limiter.snapshot().await;
320 assert_eq!(snapshot.tokens, 0);
321 }
322
323 #[rstest]
324 #[case(0, 100)]
325 #[case(1, 200)]
326 #[case(2, 400)]
327 fn test_backoff_full_jitter_increases(#[case] attempt: u32, #[case] max_expected_ms: u64) {
328 let base = Duration::from_millis(100);
329 let cap = Duration::from_secs(5);
330
331 let delay = backoff_full_jitter(attempt, base, cap);
332
333 assert!(delay.as_millis() <= max_expected_ms as u128);
335 }
336
337 #[rstest]
338 fn test_backoff_full_jitter_respects_cap() {
339 let base = Duration::from_millis(100);
340 let cap = Duration::from_secs(5);
341
342 let delay_high = backoff_full_jitter(10, base, cap);
343 assert!(delay_high.as_millis() <= cap.as_millis());
344 }
345}