Skip to main content

polyoxide_core/
request.rs

1use std::marker::PhantomData;
2
3use reqwest::Response;
4use serde::de::DeserializeOwned;
5
6use crate::client::HttpClient;
7use crate::ApiError;
8
9/// Query parameter builder
10pub trait QueryBuilder: Sized {
11    /// Add a query parameter
12    fn add_query(&mut self, key: String, value: String);
13
14    /// Add a query parameter
15    fn query(mut self, key: impl Into<String>, value: impl ToString) -> Self {
16        self.add_query(key.into(), value.to_string());
17        self
18    }
19
20    /// Add optional query parameter (only if Some)
21    fn query_opt(mut self, key: impl Into<String>, value: Option<impl ToString>) -> Self {
22        if let Some(v) = value {
23            self.add_query(key.into(), v.to_string());
24        }
25        self
26    }
27
28    /// Add multiple query parameters with the same key
29    fn query_many<I, V>(self, key: impl Into<String>, values: I) -> Self
30    where
31        I: IntoIterator<Item = V>,
32        V: ToString,
33    {
34        let key = key.into();
35        let mut result = self;
36        for value in values {
37            result.add_query(key.clone(), value.to_string());
38        }
39        result
40    }
41
42    /// Add multiple optional query parameters with the same key
43    fn query_many_opt<I, V>(self, key: impl Into<String>, values: Option<I>) -> Self
44    where
45        I: IntoIterator<Item = V>,
46        V: ToString,
47    {
48        if let Some(values) = values {
49            self.query_many(key, values)
50        } else {
51            self
52        }
53    }
54}
55
56/// Trait for error types that can be created from API responses
57pub trait RequestError: From<ApiError> + std::fmt::Debug {
58    /// Create error from HTTP response
59    fn from_response(response: Response) -> impl std::future::Future<Output = Self> + Send;
60}
61
62/// Generic request builder for simple GET-only APIs (Gamma, Data)
63pub struct Request<T, E> {
64    pub(crate) http_client: HttpClient,
65    pub(crate) path: String,
66    pub(crate) query: Vec<(String, String)>,
67    pub(crate) _marker: PhantomData<(T, E)>,
68}
69
70impl<T, E> Request<T, E> {
71    /// Create a new request
72    pub fn new(http_client: HttpClient, path: impl Into<String>) -> Self {
73        Self {
74            http_client,
75            path: path.into(),
76            query: Vec::new(),
77            _marker: PhantomData,
78        }
79    }
80}
81
82impl<T, E> QueryBuilder for Request<T, E> {
83    fn add_query(&mut self, key: String, value: String) {
84        self.query.push((key, value));
85    }
86}
87
88impl<T: DeserializeOwned, E: RequestError> Request<T, E> {
89    /// Execute the request and deserialize response
90    pub async fn send(self) -> Result<T, E> {
91        let response = self.send_raw().await?;
92
93        // Get text for debugging
94        let text = response
95            .text()
96            .await
97            .map_err(|e| E::from(ApiError::from(e)))?;
98
99        // Deserialize and provide better error context
100        serde_json::from_str(&text).map_err(|e| {
101            tracing::error!("Deserialization failed: {}", e);
102            tracing::error!("Failed to deserialize: {}", text);
103            E::from(ApiError::from(e))
104        })
105    }
106
107    /// Execute the request and return raw response
108    pub async fn send_raw(self) -> Result<Response, E> {
109        let url = self
110            .http_client
111            .base_url
112            .join(&self.path)
113            .map_err(|e| E::from(ApiError::from(e)))?;
114
115        let http_client = self.http_client;
116        let query = self.query;
117        let path = self.path;
118        let mut attempt = 0u32;
119
120        loop {
121            http_client.acquire_rate_limit(&path, None).await;
122
123            let mut request = http_client.client.get(url.clone());
124
125            if !query.is_empty() {
126                request = request.query(&query);
127            }
128
129            let response = request
130                .send()
131                .await
132                .map_err(|e| E::from(ApiError::from(e)))?;
133            let status = response.status();
134
135            if let Some(backoff) = http_client.should_retry(status, attempt) {
136                attempt += 1;
137                tracing::warn!(
138                    "Rate limited (429) on {}, retry {} after {}ms",
139                    path,
140                    attempt,
141                    backoff.as_millis()
142                );
143                tokio::time::sleep(backoff).await;
144                continue;
145            }
146
147            tracing::debug!("Response status: {}", status);
148
149            if !status.is_success() {
150                let error = E::from_response(response).await;
151                tracing::error!("Request failed: {:?}", error);
152                return Err(error);
153            }
154
155            return Ok(response);
156        }
157    }
158}
159
160/// Type marker for deserializable responses
161pub struct TypedRequest<T> {
162    pub(crate) _marker: PhantomData<T>,
163}
164
165impl<T> TypedRequest<T> {
166    pub fn new() -> Self {
167        Self {
168            _marker: PhantomData,
169        }
170    }
171}
172
173impl<T> Default for TypedRequest<T> {
174    fn default() -> Self {
175        Self::new()
176    }
177}
178
179#[cfg(test)]
180mod tests {
181    use super::*;
182    use crate::HttpClientBuilder;
183
184    // ── QueryBuilder via Request<T, E> ──────────────────────────
185
186    /// Helper to build a Request and extract its query pairs for assertions.
187    fn make_request() -> Request<(), ApiError> {
188        let http = HttpClientBuilder::new("https://example.com")
189            .build()
190            .unwrap();
191        Request::new(http, "/test")
192    }
193
194    #[test]
195    fn test_query_adds_key_value() {
196        let req = make_request().query("limit", 10);
197        assert_eq!(req.query, vec![("limit".into(), "10".into())]);
198    }
199
200    #[test]
201    fn test_query_chaining_preserves_order() {
202        let req = make_request()
203            .query("limit", 10)
204            .query("offset", "abc")
205            .query("active", true);
206        assert_eq!(
207            req.query,
208            vec![
209                ("limit".into(), "10".into()),
210                ("offset".into(), "abc".into()),
211                ("active".into(), "true".into()),
212            ]
213        );
214    }
215
216    #[test]
217    fn test_query_opt_some_adds_parameter() {
218        let req = make_request().query_opt("tag", Some("politics"));
219        assert_eq!(req.query, vec![("tag".into(), "politics".into())]);
220    }
221
222    #[test]
223    fn test_query_opt_none_skips_parameter() {
224        let req = make_request().query_opt("tag", None::<&str>);
225        assert!(req.query.is_empty());
226    }
227
228    #[test]
229    fn test_query_opt_interleaved_with_query() {
230        let req = make_request()
231            .query("limit", 25)
232            .query_opt("cursor", None::<String>)
233            .query("active", true)
234            .query_opt("slug", Some("will-x-happen"));
235
236        assert_eq!(
237            req.query,
238            vec![
239                ("limit".into(), "25".into()),
240                ("active".into(), "true".into()),
241                ("slug".into(), "will-x-happen".into()),
242            ]
243        );
244    }
245
246    #[test]
247    fn test_query_many_adds_repeated_key() {
248        let req = make_request().query_many("id", vec!["abc", "def", "ghi"]);
249        assert_eq!(
250            req.query,
251            vec![
252                ("id".into(), "abc".into()),
253                ("id".into(), "def".into()),
254                ("id".into(), "ghi".into()),
255            ]
256        );
257    }
258
259    #[test]
260    fn test_query_many_empty_iterator() {
261        let req = make_request().query_many("id", Vec::<String>::new());
262        assert!(req.query.is_empty());
263    }
264
265    #[test]
266    fn test_query_many_opt_some_adds_values() {
267        let ids = vec![1u64, 2, 3];
268        let req = make_request().query_many_opt("id", Some(ids));
269        assert_eq!(
270            req.query,
271            vec![
272                ("id".into(), "1".into()),
273                ("id".into(), "2".into()),
274                ("id".into(), "3".into()),
275            ]
276        );
277    }
278
279    #[test]
280    fn test_query_many_opt_none_skips() {
281        let req = make_request().query_many_opt("id", None::<Vec<String>>);
282        assert!(req.query.is_empty());
283    }
284
285    #[test]
286    fn test_query_duplicate_keys_allowed() {
287        let req = make_request()
288            .query("sort", "price")
289            .query("sort", "volume");
290        assert_eq!(
291            req.query,
292            vec![
293                ("sort".into(), "price".into()),
294                ("sort".into(), "volume".into()),
295            ]
296        );
297    }
298
299    // ── Request::new ────────────────────────────────────────────
300
301    #[test]
302    fn test_request_new_stores_path() {
303        let req = make_request();
304        assert_eq!(req.path, "/test");
305        assert!(req.query.is_empty());
306    }
307
308    #[test]
309    fn test_request_new_with_string_path() {
310        let http = HttpClientBuilder::new("https://example.com")
311            .build()
312            .unwrap();
313        let req: Request<(), ApiError> = Request::new(http, String::from("/events"));
314        assert_eq!(req.path, "/events");
315    }
316
317    // ── TypedRequest ────────────────────────────────────────────
318
319    #[test]
320    fn test_typed_request_new_and_default() {
321        let _t1: TypedRequest<String> = TypedRequest::new();
322        let _t2: TypedRequest<String> = TypedRequest::default();
323        // Both should compile and create distinct instances — no state to verify
324    }
325}