polyoxide-core 0.48.0

Core utilities and shared types for the polyoxide venue clients: the HTTP send loop and its hooks, window quotas, capacity buckets and holds, errors and macros
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use std::marker::PhantomData;
use std::sync::Arc;

use bytes::Bytes;
use http::header::{HeaderValue, CONTENT_TYPE};
use http::Method;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::client::HttpClient;
use crate::hooks::{Cost, DynAuthenticator, RequestParts};
use crate::response::Response;
use crate::ApiError;

/// Query parameter builder
pub trait QueryBuilder: Sized {
    /// Append a query parameter in place. Implementor hook for the builder methods below.
    fn add_query(&mut self, key: String, value: String);

    /// Append a query parameter and return `self` for chaining.
    fn query(mut self, key: impl Into<String>, value: impl ToString) -> Self {
        self.add_query(key.into(), value.to_string());
        self
    }

    /// Add optional query parameter (only if Some)
    fn query_opt(mut self, key: impl Into<String>, value: Option<impl ToString>) -> Self {
        if let Some(v) = value {
            self.add_query(key.into(), v.to_string());
        }
        self
    }

    /// Add multiple query parameters with the same key
    fn query_many<I, V>(self, key: impl Into<String>, values: I) -> Self
    where
        I: IntoIterator<Item = V>,
        V: ToString,
    {
        let key = key.into();
        let mut result = self;
        for value in values {
            result.add_query(key.clone(), value.to_string());
        }
        result
    }

    /// Add multiple optional query parameters with the same key
    fn query_many_opt<I, V>(self, key: impl Into<String>, values: Option<I>) -> Self
    where
        I: IntoIterator<Item = V>,
        V: ToString,
    {
        if let Some(values) = values {
            self.query_many(key, values)
        } else {
            self
        }
    }
}

/// An error a [`Request`] can return: any type core's [`ApiError`] converts
/// into.
///
/// The conversion is the type's one decode function. An unsuccessful response
/// reaches it as [`ApiError::Response`], carrying the status, headers and body,
/// so a venue reads its own body shape there, and a `?` on core's error
/// anywhere decodes the same way.
pub trait RequestError: From<ApiError> + std::fmt::Debug {}

impl<E: From<ApiError> + std::fmt::Debug> RequestError for E {}

/// The one request builder: a method, a path and its query, an optional JSON
/// body, the [`Authenticator`](crate::Authenticator) that signs it and the
/// [`Cost`]s it charges the client's throttle.
///
/// [`send`](Self::send) runs it on [`HttpClient::send`], decodes the body as
/// `T`, and turns an unsuccessful response into `E`.
pub struct Request<T, E> {
    pub(crate) http_client: HttpClient,
    pub(crate) method: Method,
    pub(crate) path: String,
    pub(crate) query: Vec<(String, String)>,
    pub(crate) body: Option<Bytes>,
    pub(crate) authenticator: Option<Arc<DynAuthenticator<'static>>>,
    pub(crate) costs: Vec<Cost>,
    pub(crate) _marker: PhantomData<(T, E)>,
}

impl<T, E> Request<T, E> {
    /// Create a new `GET` request
    pub fn new(http_client: HttpClient, path: impl Into<String>) -> Self {
        Self {
            http_client,
            method: Method::GET,
            path: path.into(),
            query: Vec::new(),
            body: None,
            authenticator: None,
            costs: Vec::new(),
            _marker: PhantomData,
        }
    }

    /// Send with `method` instead of `GET`.
    pub fn method(mut self, method: Method) -> Self {
        self.method = method;
        self
    }

    /// Sign every attempt with `auth`.
    pub fn authenticator(mut self, auth: Arc<DynAuthenticator<'static>>) -> Self {
        self.authenticator = Some(auth);
        self
    }

    /// Charge the client's throttle `cost` for every attempt, as well as
    /// whatever its request-counting layers charge.
    pub fn with_cost(mut self, cost: Cost) -> Self {
        self.costs.push(cost);
        self
    }
}

impl<T, E: From<ApiError>> Request<T, E> {
    /// Send `body` as JSON, with `Content-Type: application/json`.
    ///
    /// The body is serialised once, here, through [`serde_json::Value`], so
    /// every attempt sends, and an authenticator signs, the same bytes. A
    /// `Value` sorts an object's keys, so those bytes need not follow the
    /// struct's field order.
    ///
    /// # Errors
    ///
    /// [`ApiError::Serialization`] when `body` does not serialise.
    pub fn body<B: Serialize + ?Sized>(mut self, body: &B) -> Result<Self, E> {
        let value = serde_json::to_value(body).map_err(ApiError::from)?;
        self.body = Some(Bytes::from(value.to_string()));
        Ok(self)
    }
}

// Written by hand: `#[derive(Clone)]` would require `T: Clone` and `E: Clone`
// through `PhantomData<(T, E)>`, but both are only type markers. Cloning a
// request copies its client handle, method, path, query, body, authenticator
// and costs, which is what lets a paginated walk re-send identical filters on
// every page.
impl<T, E> Clone for Request<T, E> {
    fn clone(&self) -> Self {
        Self {
            http_client: self.http_client.clone(),
            method: self.method.clone(),
            path: self.path.clone(),
            query: self.query.clone(),
            body: self.body.clone(),
            authenticator: self.authenticator.clone(),
            costs: self.costs.clone(),
            _marker: PhantomData,
        }
    }
}

impl<T, E> QueryBuilder for Request<T, E> {
    fn add_query(&mut self, key: String, value: String) {
        self.query.push((key, value));
    }
}

impl<T: DeserializeOwned, E: RequestError> Request<T, E> {
    /// Execute the request and deserialize response
    pub async fn send(self) -> Result<T, E> {
        let path = self.path.clone();
        let response = self.send_raw().await?;

        let text = response.text().await.map_err(E::from)?;

        crate::decode_json(&path, &text).map_err(|e| E::from(ApiError::from(e)))
    }

    /// Execute the request and return raw response
    ///
    /// It runs on [`HttpClient::send`], so it is throttled, gated, signed,
    /// retried and held by the client's hooks. A response that is not a 2xx
    /// is never returned: it reaches `E` as [`ApiError::Response`].
    pub async fn send_raw(self) -> Result<Response, E> {
        let mut parts = RequestParts::new(self.method, self.path);
        parts.query = self.query;
        if let Some(body) = self.body {
            parts
                .headers
                .insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
            parts.body = Some(body);
        }
        let failure = match self
            .http_client
            .send(parts, &self.costs, self.authenticator.as_deref())
            .await
        {
            Ok(response) if response.status().is_success() => {
                tracing::debug!("Response status: {}", response.status());
                return Ok(response);
            }
            // Only a policy that is `Done` with a failed response gets here:
            // core's and the venues' fail it, and the loop returns the error.
            Ok(response) => ApiError::from_response(response).await,
            Err(err) => err,
        };
        let answered = matches!(failure, ApiError::Response(_));
        let error = E::from(failure);
        if answered {
            tracing::error!("Request failed: {:?}", error);
        }
        Err(error)
    }
}

/// Type marker for deserializable responses
pub struct TypedRequest<T> {
    pub(crate) _marker: PhantomData<T>,
}

impl<T> TypedRequest<T> {
    /// Create a new typed request marker.
    pub fn new() -> Self {
        Self {
            _marker: PhantomData,
        }
    }
}

impl<T> Default for TypedRequest<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::HttpClientBuilder;

    // ── QueryBuilder via Request<T, E> ──────────────────────────

    /// Helper to build a Request and extract its query pairs for assertions.
    fn make_request() -> Request<(), ApiError> {
        let http = HttpClientBuilder::new("https://example.com")
            .build()
            .unwrap();
        Request::new(http, "/test")
    }

    #[test]
    fn test_query_adds_key_value() {
        let req = make_request().query("limit", 10);
        assert_eq!(req.query, vec![("limit".into(), "10".into())]);
    }

    #[test]
    fn test_query_chaining_preserves_order() {
        let req = make_request()
            .query("limit", 10)
            .query("offset", "abc")
            .query("active", true);
        assert_eq!(
            req.query,
            vec![
                ("limit".into(), "10".into()),
                ("offset".into(), "abc".into()),
                ("active".into(), "true".into()),
            ]
        );
    }

    #[test]
    fn test_query_opt_some_adds_parameter() {
        let req = make_request().query_opt("tag", Some("politics"));
        assert_eq!(req.query, vec![("tag".into(), "politics".into())]);
    }

    #[test]
    fn test_query_opt_none_skips_parameter() {
        let req = make_request().query_opt("tag", None::<&str>);
        assert!(req.query.is_empty());
    }

    #[test]
    fn test_query_opt_interleaved_with_query() {
        let req = make_request()
            .query("limit", 25)
            .query_opt("cursor", None::<String>)
            .query("active", true)
            .query_opt("slug", Some("will-x-happen"));

        assert_eq!(
            req.query,
            vec![
                ("limit".into(), "25".into()),
                ("active".into(), "true".into()),
                ("slug".into(), "will-x-happen".into()),
            ]
        );
    }

    #[test]
    fn test_query_many_adds_repeated_key() {
        let req = make_request().query_many("id", vec!["abc", "def", "ghi"]);
        assert_eq!(
            req.query,
            vec![
                ("id".into(), "abc".into()),
                ("id".into(), "def".into()),
                ("id".into(), "ghi".into()),
            ]
        );
    }

    #[test]
    fn test_query_many_empty_iterator() {
        let req = make_request().query_many("id", Vec::<String>::new());
        assert!(req.query.is_empty());
    }

    #[test]
    fn test_query_many_opt_some_adds_values() {
        let ids = vec![1u64, 2, 3];
        let req = make_request().query_many_opt("id", Some(ids));
        assert_eq!(
            req.query,
            vec![
                ("id".into(), "1".into()),
                ("id".into(), "2".into()),
                ("id".into(), "3".into()),
            ]
        );
    }

    #[test]
    fn test_query_many_opt_none_skips() {
        let req = make_request().query_many_opt("id", None::<Vec<String>>);
        assert!(req.query.is_empty());
    }

    #[test]
    fn test_query_duplicate_keys_allowed() {
        let req = make_request()
            .query("sort", "price")
            .query("sort", "volume");
        assert_eq!(
            req.query,
            vec![
                ("sort".into(), "price".into()),
                ("sort".into(), "volume".into()),
            ]
        );
    }

    // ── Request::new ────────────────────────────────────────────

    #[test]
    fn test_request_new_stores_path() {
        let req = make_request();
        assert_eq!(req.path, "/test");
        assert!(req.query.is_empty());
    }

    #[test]
    fn test_request_new_with_string_path() {
        let http = HttpClientBuilder::new("https://example.com")
            .build()
            .unwrap();
        let req: Request<(), ApiError> = Request::new(http, String::from("/events"));
        assert_eq!(req.path, "/events");
    }

    // ── Clone ───────────────────────────────────────────────────

    #[test]
    fn test_request_clone_does_not_require_clone_markers() {
        // Neither marker implements `Clone`; a derived impl would not compile here.
        struct NotClone;
        struct NotCloneError;

        let http = HttpClientBuilder::new("https://example.com")
            .build()
            .unwrap();
        let original: Request<NotClone, NotCloneError> =
            Request::new(http, "/feed").query("user", "0xabc");
        let extended = original.clone().query("cursor", "c1");

        assert_eq!(original.path, "/feed");
        assert_eq!(original.query, vec![("user".into(), "0xabc".into())]);
        assert_eq!(extended.path, "/feed");
        assert_eq!(
            extended.query,
            vec![
                ("user".into(), "0xabc".into()),
                ("cursor".into(), "c1".into()),
            ]
        );
    }

    // ── TypedRequest ────────────────────────────────────────────

    #[test]
    fn test_typed_request_new_and_default() {
        let _t1: TypedRequest<String> = TypedRequest::new();
        let _t2: TypedRequest<String> = TypedRequest::default();
        // Both should compile and create distinct instances — no state to verify
    }
}