Skip to main content

polyoxide_core/
request.rs

1use std::marker::PhantomData;
2
3use reqwest::Response;
4use serde::de::DeserializeOwned;
5
6use crate::client::{retry_after_header, HttpClient};
7use crate::ApiError;
8
9/// Query parameter builder
10pub trait QueryBuilder: Sized {
11    /// Append a query parameter in place. Implementor hook for the builder methods below.
12    fn add_query(&mut self, key: String, value: String);
13
14    /// Append a query parameter and return `self` for chaining.
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: {}", crate::truncate_for_log(&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            let _permit = http_client.acquire_concurrency().await;
122            http_client.acquire_rate_limit(&path, None).await;
123
124            let mut request = http_client.client.get(url.clone());
125
126            if !query.is_empty() {
127                request = request.query(&query);
128            }
129
130            let response = request
131                .send()
132                .await
133                .map_err(|e| E::from(ApiError::from(e)))?;
134            let status = response.status();
135            let retry_after = retry_after_header(&response);
136
137            if let Some(backoff) = http_client.should_retry(status, attempt, retry_after.as_deref())
138            {
139                attempt += 1;
140                tracing::warn!(
141                    "Retriable status {} on {}, retry {} after {}ms",
142                    status,
143                    path,
144                    attempt,
145                    backoff.as_millis()
146                );
147                drop(_permit);
148                tokio::time::sleep(backoff).await;
149                continue;
150            }
151
152            tracing::debug!("Response status: {}", status);
153
154            if !status.is_success() {
155                let error = E::from_response(response).await;
156                tracing::error!("Request failed: {:?}", error);
157                return Err(error);
158            }
159
160            return Ok(response);
161        }
162    }
163}
164
165/// Type marker for deserializable responses
166pub struct TypedRequest<T> {
167    pub(crate) _marker: PhantomData<T>,
168}
169
170impl<T> TypedRequest<T> {
171    /// Create a new typed request marker.
172    pub fn new() -> Self {
173        Self {
174            _marker: PhantomData,
175        }
176    }
177}
178
179impl<T> Default for TypedRequest<T> {
180    fn default() -> Self {
181        Self::new()
182    }
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::HttpClientBuilder;
189
190    // ── QueryBuilder via Request<T, E> ──────────────────────────
191
192    /// Helper to build a Request and extract its query pairs for assertions.
193    fn make_request() -> Request<(), ApiError> {
194        let http = HttpClientBuilder::new("https://example.com")
195            .build()
196            .unwrap();
197        Request::new(http, "/test")
198    }
199
200    #[test]
201    fn test_query_adds_key_value() {
202        let req = make_request().query("limit", 10);
203        assert_eq!(req.query, vec![("limit".into(), "10".into())]);
204    }
205
206    #[test]
207    fn test_query_chaining_preserves_order() {
208        let req = make_request()
209            .query("limit", 10)
210            .query("offset", "abc")
211            .query("active", true);
212        assert_eq!(
213            req.query,
214            vec![
215                ("limit".into(), "10".into()),
216                ("offset".into(), "abc".into()),
217                ("active".into(), "true".into()),
218            ]
219        );
220    }
221
222    #[test]
223    fn test_query_opt_some_adds_parameter() {
224        let req = make_request().query_opt("tag", Some("politics"));
225        assert_eq!(req.query, vec![("tag".into(), "politics".into())]);
226    }
227
228    #[test]
229    fn test_query_opt_none_skips_parameter() {
230        let req = make_request().query_opt("tag", None::<&str>);
231        assert!(req.query.is_empty());
232    }
233
234    #[test]
235    fn test_query_opt_interleaved_with_query() {
236        let req = make_request()
237            .query("limit", 25)
238            .query_opt("cursor", None::<String>)
239            .query("active", true)
240            .query_opt("slug", Some("will-x-happen"));
241
242        assert_eq!(
243            req.query,
244            vec![
245                ("limit".into(), "25".into()),
246                ("active".into(), "true".into()),
247                ("slug".into(), "will-x-happen".into()),
248            ]
249        );
250    }
251
252    #[test]
253    fn test_query_many_adds_repeated_key() {
254        let req = make_request().query_many("id", vec!["abc", "def", "ghi"]);
255        assert_eq!(
256            req.query,
257            vec![
258                ("id".into(), "abc".into()),
259                ("id".into(), "def".into()),
260                ("id".into(), "ghi".into()),
261            ]
262        );
263    }
264
265    #[test]
266    fn test_query_many_empty_iterator() {
267        let req = make_request().query_many("id", Vec::<String>::new());
268        assert!(req.query.is_empty());
269    }
270
271    #[test]
272    fn test_query_many_opt_some_adds_values() {
273        let ids = vec![1u64, 2, 3];
274        let req = make_request().query_many_opt("id", Some(ids));
275        assert_eq!(
276            req.query,
277            vec![
278                ("id".into(), "1".into()),
279                ("id".into(), "2".into()),
280                ("id".into(), "3".into()),
281            ]
282        );
283    }
284
285    #[test]
286    fn test_query_many_opt_none_skips() {
287        let req = make_request().query_many_opt("id", None::<Vec<String>>);
288        assert!(req.query.is_empty());
289    }
290
291    #[test]
292    fn test_query_duplicate_keys_allowed() {
293        let req = make_request()
294            .query("sort", "price")
295            .query("sort", "volume");
296        assert_eq!(
297            req.query,
298            vec![
299                ("sort".into(), "price".into()),
300                ("sort".into(), "volume".into()),
301            ]
302        );
303    }
304
305    // ── Request::new ────────────────────────────────────────────
306
307    #[test]
308    fn test_request_new_stores_path() {
309        let req = make_request();
310        assert_eq!(req.path, "/test");
311        assert!(req.query.is_empty());
312    }
313
314    #[test]
315    fn test_request_new_with_string_path() {
316        let http = HttpClientBuilder::new("https://example.com")
317            .build()
318            .unwrap();
319        let req: Request<(), ApiError> = Request::new(http, String::from("/events"));
320        assert_eq!(req.path, "/events");
321    }
322
323    // ── TypedRequest ────────────────────────────────────────────
324
325    #[test]
326    fn test_typed_request_new_and_default() {
327        let _t1: TypedRequest<String> = TypedRequest::new();
328        let _t2: TypedRequest<String> = TypedRequest::default();
329        // Both should compile and create distinct instances — no state to verify
330    }
331}