1use crate::errors::{MarketDataError, Result};
6use governor::{
7 clock::DefaultClock,
8 state::{direct::NotKeyed, InMemoryState},
9 Quota, RateLimiter,
10};
11use reqwest::{Client, Method, StatusCode};
12use serde::{de::DeserializeOwned, Serialize};
13use std::num::NonZeroU32;
14use std::sync::Arc;
15use std::time::Duration;
16use tokio::time::sleep;
17use tracing::{error, warn};
18
19pub struct RestClient {
20 client: Client,
21 base_url: String,
22 rate_limiter: Arc<RateLimiter<NotKeyed, InMemoryState, DefaultClock>>,
23}
24
25impl RestClient {
26 pub fn new(base_url: String, requests_per_minute: u32) -> Self {
27 let client = Client::builder()
28 .timeout(Duration::from_secs(30))
29 .build()
30 .expect("Failed to build HTTP client");
31
32 let quota = Quota::per_minute(NonZeroU32::new(requests_per_minute).unwrap());
33 let rate_limiter = Arc::new(RateLimiter::direct(quota));
34
35 Self {
36 client,
37 base_url,
38 rate_limiter,
39 }
40 }
41
42 pub fn with_timeout(mut self, timeout: Duration) -> Self {
43 self.client = Client::builder()
44 .timeout(timeout)
45 .build()
46 .expect("Failed to build HTTP client");
47 self
48 }
49
50 pub async fn request<T: DeserializeOwned>(
52 &self,
53 method: Method,
54 path: &str,
55 headers: Vec<(&str, &str)>,
56 body: Option<impl Serialize>,
57 ) -> Result<T> {
58 self.rate_limiter.until_ready().await;
60
61 let url = format!("{}{}", self.base_url, path);
62 let mut req = self.client.request(method.clone(), &url);
63
64 for (key, value) in headers {
66 req = req.header(key, value);
67 }
68
69 if let Some(body) = body {
71 req = req.json(&body);
72 }
73
74 self.send_with_retry(req, 3).await
76 }
77
78 async fn send_with_retry<T: DeserializeOwned>(
80 &self,
81 req: reqwest::RequestBuilder,
82 max_attempts: u32,
83 ) -> Result<T> {
84 let mut attempt = 0;
85 let mut delay = Duration::from_millis(100);
86
87 loop {
88 attempt += 1;
89
90 let req_clone = req
91 .try_clone()
92 .ok_or_else(|| MarketDataError::Network("Failed to clone request".to_string()))?;
93
94 match req_clone.send().await {
95 Ok(response) => {
96 return self.handle_response(response).await;
97 }
98 Err(e) if attempt >= max_attempts => {
99 error!("Request failed after {} attempts: {}", max_attempts, e);
100 return Err(MarketDataError::Network(e.to_string()));
101 }
102 Err(e) => {
103 warn!(
104 "Request attempt {} failed: {}, retrying in {:?}",
105 attempt, e, delay
106 );
107 sleep(delay).await;
108 delay *= 2; }
110 }
111 }
112 }
113
114 async fn handle_response<T: DeserializeOwned>(&self, response: reqwest::Response) -> Result<T> {
116 match response.status() {
117 StatusCode::OK => response
118 .json()
119 .await
120 .map_err(|e| MarketDataError::Parse(format!("Failed to parse response: {}", e))),
121 StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => {
122 let error_text = response.text().await.unwrap_or_default();
123 Err(MarketDataError::Auth(error_text))
124 }
125 StatusCode::TOO_MANY_REQUESTS => Err(MarketDataError::RateLimit),
126 StatusCode::NOT_FOUND => Err(MarketDataError::SymbolNotFound("Unknown".to_string())),
127 StatusCode::SERVICE_UNAVAILABLE | StatusCode::GATEWAY_TIMEOUT => {
128 let error_text = response.text().await.unwrap_or_default();
129 Err(MarketDataError::ProviderUnavailable(error_text))
130 }
131 _ => {
132 let status = response.status();
133 let error_text = response.text().await.unwrap_or_default();
134 Err(MarketDataError::Network(format!(
135 "HTTP {}: {}",
136 status, error_text
137 )))
138 }
139 }
140 }
141
142 pub async fn get<T: DeserializeOwned>(
144 &self,
145 path: &str,
146 headers: Vec<(&str, &str)>,
147 ) -> Result<T> {
148 self.request(Method::GET, path, headers, None::<()>).await
149 }
150
151 pub async fn post<T: DeserializeOwned, B: Serialize>(
153 &self,
154 path: &str,
155 headers: Vec<(&str, &str)>,
156 body: B,
157 ) -> Result<T> {
158 self.request(Method::POST, path, headers, Some(body)).await
159 }
160
161 pub async fn delete<T: DeserializeOwned>(
163 &self,
164 path: &str,
165 headers: Vec<(&str, &str)>,
166 ) -> Result<T> {
167 self.request(Method::DELETE, path, headers, None::<()>)
168 .await
169 }
170}
171
172#[cfg(test)]
173mod tests {
174 use super::*;
175
176 #[test]
177 fn test_rest_client_creation() {
178 let client = RestClient::new("https://api.example.com".to_string(), 200);
179 assert_eq!(client.base_url, "https://api.example.com");
180 }
181
182 #[tokio::test]
183 async fn test_rate_limiting() {
184 let client = RestClient::new("https://api.example.com".to_string(), 60);
185
186 let start = std::time::Instant::now();
188 client.rate_limiter.until_ready().await;
189 assert!(start.elapsed() < Duration::from_millis(100));
190 }
191}