ddapi-rs 2.0.0

A simple Rust library to get data from DDNet and DDStats APIs
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
411
use crate::error::{Error, Result};
#[cfg(feature = "cache")]
use moka::future::Cache;
use reqwest::header;
use reqwest::Client;
use serde::de::DeserializeOwned;
#[allow(unused_imports)]
use std::time::Duration;

#[cfg(feature = "cache")]
const DEFAULT_CACHE_TTL: Duration = Duration::from_mins(10);
#[cfg(feature = "cache")]
const DEFAULT_CACHE_CAPACITY: u64 = 10_000;

#[derive(Clone, Default)]
pub(crate) struct ApiCore {
    client: Client,
    #[cfg(feature = "cache")]
    cache: Option<Cache<String, Vec<u8>>>,
}

impl ApiCore {
    #[cfg(feature = "cache")]
    fn default_cache() -> Cache<String, Vec<u8>> {
        Cache::builder()
            .max_capacity(DEFAULT_CACHE_CAPACITY)
            .time_to_live(DEFAULT_CACHE_TTL)
            .build()
    }

    fn new() -> Self {
        let client = Client::builder()
            .user_agent(concat!(
                env!("CARGO_PKG_NAME"),
                "/",
                env!("CARGO_PKG_VERSION")
            ))
            .default_headers({
                let mut h = header::HeaderMap::new();
                h.insert(
                    header::ACCEPT,
                    header::HeaderValue::from_static("application/json"),
                );
                h
            })
            .build()
            .unwrap_or_else(|_| Client::new());
        Self {
            client,
            #[cfg(feature = "cache")]
            cache: Some(Self::default_cache()),
        }
    }

    fn new_with_client(client: Client) -> Self {
        Self {
            client,
            #[cfg(feature = "cache")]
            cache: Some(Self::default_cache()),
        }
    }

    #[cfg(feature = "cache")]
    fn set_cache(&mut self, capacity: u64, time_to_live: Duration) {
        self.cache = Some(
            Cache::builder()
                .max_capacity(capacity)
                .time_to_live(time_to_live)
                .build(),
        );
    }

    /// Sends an HTTP GET request to the specified URL and returns the raw response body.
    async fn send_request(&self, url: &str) -> Result<Vec<u8>> {
        let response = self
            .client
            .get(url)
            // Avoid hanging forever on large responses while still being generous.
            .timeout(Duration::from_secs(30))
            .send()
            .await?;

        let status = response.status();
        let body = response.bytes().await?.to_vec();

        if body.is_empty() {
            return Err(Error::EmptyBody);
        }

        if !status.is_success() {
            let msg = String::from_utf8_lossy(&body).chars().take(2048).collect();
            return Err(Error::HttpStatus { status, body: msg });
        }

        Ok(body)
    }

    pub async fn generator<T>(&self, url: &str) -> Result<T>
    where
        T: DeserializeOwned + Send + Sync + 'static,
    {
        #[cfg(feature = "cache")]
        {
            self.generator_cached(url).await
        }
        #[cfg(not(feature = "cache"))]
        {
            self.generator_no_cache(url).await
        }
    }

    #[cfg(feature = "cache")]
    async fn generator_cached<T>(&self, url: &str) -> Result<T>
    where
        T: DeserializeOwned + Send + Sync + 'static,
    {
        let type_name = std::any::type_name::<T>();
        let cache_key = format!("{type_name}:{url}");

        match &self.cache {
            Some(cache) => {
                if let Some(value) = cache.get(&cache_key).await {
                    Self::parse_response::<T>(value.as_slice())
                } else {
                    let body = self.send_request(url).await?;
                    cache.insert(cache_key, body.clone()).await;
                    Self::parse_response::<T>(body.as_slice())
                }
            }
            None => self.generator_no_cache(url).await,
        }
    }

    pub async fn generator_no_cache<T>(&self, url: &str) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let body = self.send_request(url).await?;
        Self::parse_response::<T>(body.as_slice())
    }

    fn parse_response<T>(body: &[u8]) -> Result<T>
    where
        T: DeserializeOwned,
    {
        // ddnet "not found" convention: empty JSON object.
        #[cfg(feature = "ddnet")]
        {
            let trimmed = trim_ascii(body);
            if trimmed == b"{}" {
                return Err(Error::NotFound);
            }
        }

        // ddstats sometimes returns HTTP 200 with { "error": "..." }.
        #[cfg(feature = "ddstats")]
        {
            #[derive(serde::Deserialize)]
            #[serde(untagged)]
            enum MaybeError<T> {
                Err { error: String },
                Ok(T),
            }

            // Single-pass parse: either error envelope or expected payload.
            match serde_json::from_slice::<MaybeError<T>>(body)? {
                MaybeError::Err { error } => {
                    if error.eq_ignore_ascii_case("player not found") {
                        Err(Error::NotFound)
                    } else {
                        Err(Error::RemoteMessage(error))
                    }
                }
                MaybeError::Ok(v) => Ok(v),
            }
        }

        #[cfg(not(feature = "ddstats"))]
        {
            Ok(serde_json::from_slice(body)?)
        }
    }
}

fn trim_ascii(mut s: &[u8]) -> &[u8] {
    while let Some((&b, rest)) = s.split_first() {
        if !b.is_ascii_whitespace() {
            break;
        }
        s = rest;
    }
    while let Some((&b, rest)) = s.split_last() {
        if !b.is_ascii_whitespace() {
            break;
        }
        s = rest;
    }
    s
}

pub trait HasApiCore {
    fn core(&self) -> &ApiCore;
}

#[derive(Clone, Default)]
pub struct DDApi {
    core: ApiCore,
}

impl HasApiCore for DDApi {
    fn core(&self) -> &ApiCore {
        &self.core
    }
}

impl DDApi {
    /// Creates a new `DDApi` instance with default settings
    ///
    /// # Examples
    ///
    /// ```
    /// use ddapi_rs::prelude::*;
    ///
    /// let api = DDApi::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        DDApi {
            core: ApiCore::new(),
        }
    }

    /// Creates a new `DDApi` instance with a custom HTTP client
    ///
    /// This allows you to configure your own client with custom timeouts,
    /// headers, or other settings.
    ///
    /// # Arguments
    ///
    /// * `client` - A pre-configured `reqwest::Client` instance
    ///
    /// # Examples
    ///
    /// ```
    /// use ddapi_rs::prelude::*;
    /// use reqwest::Client;
    ///
    /// let client = Client::builder()
    ///     .timeout(std::time::Duration::from_secs(10))
    ///     .build()
    ///     .unwrap();
    /// let api = DDApi::new_with_client(client);
    /// ```
    #[must_use]
    pub fn new_with_client(client: Client) -> Self {
        DDApi {
            core: ApiCore::new_with_client(client),
        }
    }

    /// Configures caching for API responses
    ///
    /// When the `cache` feature is enabled, this method allows you to set up
    /// an in-memory cache to reduce API calls and improve performance.
    ///
    /// # Arguments
    ///
    /// * `capacity` - Maximum number of entries to store in the cache
    /// * `time_to_live` - Time in seconds before cached entries expire
    ///
    /// # Examples
    ///
    ///
    /// ```ignore
    /// use ddapi_rs::prelude::*;
    /// use std::time::Duration;
    ///
    /// let mut api = DDApi::new();
    /// api.set_cache(1000, Duration::from_secs(60 * 5)); // Cache 1000 items for 5 minutes
    /// ```
    #[cfg(feature = "cache")]
    pub fn set_cache(&mut self, capacity: u64, time_to_live: Duration) {
        self.core.set_cache(capacity, time_to_live);
    }

    /// Executes an API request and deserializes the JSON response
    ///
    /// This method handles API requests and automatically deserializes the JSON response
    /// into the specified type. The caching behavior is determined by the `cache` feature flag.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The type to deserialize the response into. Must implement
    ///   `DeserializeOwned + Send + Sync + 'static`
    ///
    /// # Arguments
    ///
    /// * `url` - The API endpoint URL to request
    ///
    /// # Returns
    ///
    /// `Result<T>` containing the deserialized data on success, or an error on failure
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails, the response is empty or has a
    /// non-success status, or the body cannot be deserialized into `T`.
    pub async fn generator<T>(&self, url: &str) -> Result<T>
    where
        T: DeserializeOwned + Send + Sync + 'static,
    {
        self.core.generator(url).await
    }

    /// Executes an API request without caching
    ///
    /// Always fetches fresh data from the API, bypassing any cache.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The type to deserialize the response into
    ///
    /// # Arguments
    ///
    /// * `url` - The API endpoint URL to request
    ///
    /// # Returns
    ///
    /// Returns `Result<T>` with freshly fetched deserialized data
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails, the response is empty or has a
    /// non-success status, or the body cannot be deserialized into `T`.
    pub async fn generator_no_cache<T>(&self, url: &str) -> Result<T>
    where
        T: DeserializeOwned,
    {
        self.core.generator_no_cache(url).await
    }
}

#[derive(Clone, Default)]
pub struct DDnetClient {
    core: ApiCore,
}

impl HasApiCore for DDnetClient {
    fn core(&self) -> &ApiCore {
        &self.core
    }
}

impl DDnetClient {
    #[must_use]
    pub fn new() -> Self {
        Self {
            core: ApiCore::new(),
        }
    }

    #[must_use]
    pub fn new_with_client(client: Client) -> Self {
        Self {
            core: ApiCore::new_with_client(client),
        }
    }

    #[cfg(feature = "cache")]
    pub fn set_cache(&mut self, capacity: u64, time_to_live: Duration) {
        self.core.set_cache(capacity, time_to_live);
    }
}

#[derive(Clone, Default)]
pub struct DDstatsClient {
    core: ApiCore,
}

impl HasApiCore for DDstatsClient {
    fn core(&self) -> &ApiCore {
        &self.core
    }
}

impl DDstatsClient {
    #[must_use]
    pub fn new() -> Self {
        Self {
            core: ApiCore::new(),
        }
    }

    #[must_use]
    pub fn new_with_client(client: Client) -> Self {
        Self {
            core: ApiCore::new_with_client(client),
        }
    }

    #[cfg(feature = "cache")]
    pub fn set_cache(&mut self, capacity: u64, time_to_live: Duration) {
        self.core.set_cache(capacity, time_to_live);
    }
}

#[cfg(feature = "ddnet")]
pub mod ddnet;

#[cfg(feature = "ddstats")]
pub mod ddstats;