api-bones 4.0.1

Opinionated REST API types: errors (RFC 9457), pagination, health checks, and more
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
//! `Cache-Control` header builder and parser (RFC 7234).
//!
//! [`CacheControl`] represents the structured set of directives that can
//! appear in a `Cache-Control` HTTP header, with builder methods for the most
//! common request and response directives.
//!
//! # Example
//!
//! ```rust
//! use api_bones::cache::CacheControl;
//!
//! // Build a typical immutable public response.
//! let cc = CacheControl::new()
//!     .public()
//!     .max_age(31_536_000)
//!     .immutable();
//! assert_eq!(cc.to_string(), "public, immutable, max-age=31536000");
//!
//! // Parse a header value.
//! let cc: CacheControl = "no-store, no-cache".parse().unwrap();
//! assert!(cc.no_store);
//! assert!(cc.no_cache);
//! ```

#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::{format, string::String, vec::Vec};
use core::{fmt, str::FromStr};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// CacheControl
// ---------------------------------------------------------------------------

/// Structured `Cache-Control` header (RFC 7234 ยง5.2).
///
/// All boolean directives default to `false`; numeric directives default to
/// `None` (absent). Use the builder methods to set them.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[allow(clippy::struct_excessive_bools)]
#[non_exhaustive]
pub struct CacheControl {
    // -----------------------------------------------------------------------
    // Response directives
    // -----------------------------------------------------------------------
    /// `public` โ€” response may be stored by any cache.
    pub public: bool,
    /// `private` โ€” response is intended for a single user; must not be stored
    /// by a shared cache.
    pub private: bool,
    /// `no-cache` โ€” cache must revalidate with the origin before serving.
    pub no_cache: bool,
    /// `no-store` โ€” must not store any part of the request or response.
    pub no_store: bool,
    /// `no-transform` โ€” no transformations or conversions should be made.
    pub no_transform: bool,
    /// `must-revalidate` โ€” stale responses must not be used without revalidation.
    pub must_revalidate: bool,
    /// `proxy-revalidate` โ€” like `must-revalidate` but only for shared caches.
    pub proxy_revalidate: bool,
    /// `immutable` โ€” response body will not change over its lifetime.
    pub immutable: bool,
    /// `max-age=<seconds>` โ€” maximum time the response is considered fresh.
    pub max_age: Option<u64>,
    /// `s-maxage=<seconds>` โ€” overrides `max-age` for shared caches.
    pub s_maxage: Option<u64>,
    /// `stale-while-revalidate=<seconds>` โ€” serve stale while revalidating.
    pub stale_while_revalidate: Option<u64>,
    /// `stale-if-error=<seconds>` โ€” use stale response on error.
    pub stale_if_error: Option<u64>,

    // -----------------------------------------------------------------------
    // Request directives
    // -----------------------------------------------------------------------
    /// `only-if-cached` โ€” do not use the network; only return a cached response.
    pub only_if_cached: bool,
    /// `max-stale[=<seconds>]` โ€” accept a response up to this many seconds stale.
    /// `Some(0)` means any staleness is acceptable; `None` means the directive
    /// is absent.
    pub max_stale: Option<u64>,
    /// `min-fresh=<seconds>` โ€” require at least this much remaining freshness.
    pub min_fresh: Option<u64>,
}

impl CacheControl {
    /// Create an empty `CacheControl` with all directives absent.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    // -----------------------------------------------------------------------
    // Builder methods โ€” response directives
    // -----------------------------------------------------------------------

    /// Set the `public` directive.
    #[must_use]
    pub fn public(mut self) -> Self {
        self.public = true;
        self
    }

    /// Set the `private` directive.
    #[must_use]
    pub fn private(mut self) -> Self {
        self.private = true;
        self
    }

    /// Set the `no-cache` directive.
    #[must_use]
    pub fn no_cache(mut self) -> Self {
        self.no_cache = true;
        self
    }

    /// Set the `no-store` directive.
    #[must_use]
    pub fn no_store(mut self) -> Self {
        self.no_store = true;
        self
    }

    /// Set the `no-transform` directive.
    #[must_use]
    pub fn no_transform(mut self) -> Self {
        self.no_transform = true;
        self
    }

    /// Set the `must-revalidate` directive.
    #[must_use]
    pub fn must_revalidate(mut self) -> Self {
        self.must_revalidate = true;
        self
    }

    /// Set the `proxy-revalidate` directive.
    #[must_use]
    pub fn proxy_revalidate(mut self) -> Self {
        self.proxy_revalidate = true;
        self
    }

    /// Set the `immutable` directive.
    #[must_use]
    pub fn immutable(mut self) -> Self {
        self.immutable = true;
        self
    }

    /// Set `max-age=<seconds>`.
    #[must_use]
    pub fn max_age(mut self, seconds: u64) -> Self {
        self.max_age = Some(seconds);
        self
    }

    /// Set `s-maxage=<seconds>`.
    #[must_use]
    pub fn s_maxage(mut self, seconds: u64) -> Self {
        self.s_maxage = Some(seconds);
        self
    }

    /// Set `stale-while-revalidate=<seconds>`.
    #[must_use]
    pub fn stale_while_revalidate(mut self, seconds: u64) -> Self {
        self.stale_while_revalidate = Some(seconds);
        self
    }

    /// Set `stale-if-error=<seconds>`.
    #[must_use]
    pub fn stale_if_error(mut self, seconds: u64) -> Self {
        self.stale_if_error = Some(seconds);
        self
    }

    // -----------------------------------------------------------------------
    // Builder methods โ€” request directives
    // -----------------------------------------------------------------------

    /// Set the `only-if-cached` directive.
    #[must_use]
    pub fn only_if_cached(mut self) -> Self {
        self.only_if_cached = true;
        self
    }

    /// Set `max-stale[=<seconds>]`.  Pass `0` to accept any staleness.
    #[must_use]
    pub fn max_stale(mut self, seconds: u64) -> Self {
        self.max_stale = Some(seconds);
        self
    }

    /// Set `min-fresh=<seconds>`.
    #[must_use]
    pub fn min_fresh(mut self, seconds: u64) -> Self {
        self.min_fresh = Some(seconds);
        self
    }

    // -----------------------------------------------------------------------
    // Convenience constructors
    // -----------------------------------------------------------------------

    /// Convenience: `no-store` (disable all caching).
    ///
    /// ```
    /// use api_bones::cache::CacheControl;
    ///
    /// let cc = CacheControl::no_caching();
    /// assert!(cc.no_store);
    /// assert_eq!(cc.to_string(), "no-store");
    /// ```
    #[must_use]
    pub fn no_caching() -> Self {
        Self::new().no_store()
    }

    /// Convenience: `private, no-cache, no-store`.
    ///
    /// ```
    /// use api_bones::cache::CacheControl;
    ///
    /// let cc = CacheControl::private_no_cache();
    /// assert!(cc.private && cc.no_cache && cc.no_store);
    /// ```
    #[must_use]
    pub fn private_no_cache() -> Self {
        Self::new().private().no_cache().no_store()
    }
}

// ---------------------------------------------------------------------------
// Display
// ---------------------------------------------------------------------------

impl fmt::Display for CacheControl {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts: Vec<&str> = Vec::new();
        // We write variable-width entries inline; use a local buffer.
        // Collect fixed-string directives first, then emit numeric ones.

        // Boolean directives (response)
        if self.public {
            parts.push("public");
        }
        if self.private {
            parts.push("private");
        }
        if self.no_cache {
            parts.push("no-cache");
        }
        if self.no_store {
            parts.push("no-store");
        }
        if self.no_transform {
            parts.push("no-transform");
        }
        if self.must_revalidate {
            parts.push("must-revalidate");
        }
        if self.proxy_revalidate {
            parts.push("proxy-revalidate");
        }
        if self.immutable {
            parts.push("immutable");
        }
        // Boolean directives (request)
        if self.only_if_cached {
            parts.push("only-if-cached");
        }

        // Write fixed parts first
        for (i, p) in parts.iter().enumerate() {
            if i > 0 {
                f.write_str(", ")?;
            }
            f.write_str(p)?;
        }

        // Collect numeric directives.
        let numeric: [Option<(&str, u64)>; 6] = [
            self.max_age.map(|v| ("max-age", v)),
            self.s_maxage.map(|v| ("s-maxage", v)),
            self.stale_while_revalidate
                .map(|v| ("stale-while-revalidate", v)),
            self.stale_if_error.map(|v| ("stale-if-error", v)),
            self.max_stale.map(|v| ("max-stale", v)),
            self.min_fresh.map(|v| ("min-fresh", v)),
        ];

        let mut need_sep = !parts.is_empty();
        for (name, v) in numeric.iter().flatten() {
            if need_sep {
                f.write_str(", ")?;
            }
            write!(f, "{name}={v}")?;
            need_sep = true;
        }

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Parse error
// ---------------------------------------------------------------------------

/// Error returned when parsing a `Cache-Control` header fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseCacheControlError(String);

impl fmt::Display for ParseCacheControlError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid Cache-Control header: {}", self.0)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for ParseCacheControlError {}

// ---------------------------------------------------------------------------
// FromStr
// ---------------------------------------------------------------------------

impl FromStr for CacheControl {
    type Err = ParseCacheControlError;

    /// Parse a `Cache-Control` header value.
    ///
    /// Unknown directives are silently ignored, matching real-world HTTP
    /// caching behaviour.
    ///
    /// ```
    /// use api_bones::cache::CacheControl;
    ///
    /// let cc: CacheControl = "public, max-age=3600, must-revalidate".parse().unwrap();
    /// assert!(cc.public);
    /// assert_eq!(cc.max_age, Some(3600));
    /// assert!(cc.must_revalidate);
    /// ```
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut cc = Self::new();
        for token in s.split(',') {
            let token = token.trim();
            if token.is_empty() {
                continue;
            }
            let (name, value) = if let Some(eq) = token.find('=') {
                (&token[..eq], Some(token[eq + 1..].trim()))
            } else {
                (token, None)
            };
            let name = name.trim().to_lowercase();

            let parse_u64 = |v: Option<&str>| -> Result<u64, ParseCacheControlError> {
                v.ok_or_else(|| ParseCacheControlError(format!("{name} requires a value")))?
                    .parse::<u64>()
                    .map_err(|_| {
                        ParseCacheControlError(format!("{name} value is not a valid integer"))
                    })
            };

            match name.as_str() {
                "public" => cc.public = true,
                "private" => cc.private = true,
                "no-cache" => cc.no_cache = true,
                "no-store" => cc.no_store = true,
                "no-transform" => cc.no_transform = true,
                "must-revalidate" => cc.must_revalidate = true,
                "proxy-revalidate" => cc.proxy_revalidate = true,
                "immutable" => cc.immutable = true,
                "only-if-cached" => cc.only_if_cached = true,
                "max-age" => cc.max_age = Some(parse_u64(value)?),
                "s-maxage" => cc.s_maxage = Some(parse_u64(value)?),
                "stale-while-revalidate" => cc.stale_while_revalidate = Some(parse_u64(value)?),
                "stale-if-error" => cc.stale_if_error = Some(parse_u64(value)?),
                "max-stale" => cc.max_stale = Some(value.and_then(|v| v.parse().ok()).unwrap_or(0)),
                "min-fresh" => cc.min_fresh = Some(parse_u64(value)?),
                _ => {} // unknown directives are ignored per RFC
            }
        }
        Ok(cc)
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn default_is_empty() {
        let cc = CacheControl::new();
        assert_eq!(cc.to_string(), "");
    }

    #[test]
    fn builder_public_max_age_immutable() {
        let cc = CacheControl::new().public().max_age(31_536_000).immutable();
        // Boolean directives (public, immutable) appear before numeric ones (max-age).
        assert_eq!(cc.to_string(), "public, immutable, max-age=31536000");
    }

    #[test]
    fn builder_no_store() {
        let cc = CacheControl::no_caching();
        assert_eq!(cc.to_string(), "no-store");
    }

    #[test]
    fn builder_private_no_cache() {
        let cc = CacheControl::private_no_cache();
        assert!(cc.private);
        assert!(cc.no_cache);
        assert!(cc.no_store);
    }

    #[test]
    fn parse_simple_flags() {
        let cc: CacheControl = "no-store, no-cache".parse().unwrap();
        assert!(cc.no_store);
        assert!(cc.no_cache);
    }

    #[test]
    fn parse_numeric_directives() {
        let cc: CacheControl = "public, max-age=3600, s-maxage=7200".parse().unwrap();
        assert!(cc.public);
        assert_eq!(cc.max_age, Some(3600));
        assert_eq!(cc.s_maxage, Some(7200));
    }

    #[test]
    fn parse_unknown_directive_ignored() {
        let cc: CacheControl = "no-store, x-custom-thing=42".parse().unwrap();
        assert!(cc.no_store);
    }

    #[test]
    fn roundtrip_complex() {
        let original = CacheControl::new()
            .public()
            .max_age(600)
            .must_revalidate()
            .stale_if_error(86_400);
        let s = original.to_string();
        let parsed: CacheControl = s.parse().unwrap();
        assert_eq!(parsed.public, original.public);
        assert_eq!(parsed.max_age, original.max_age);
        assert_eq!(parsed.must_revalidate, original.must_revalidate);
        assert_eq!(parsed.stale_if_error, original.stale_if_error);
    }

    #[test]
    fn parse_case_insensitive() {
        let cc: CacheControl = "No-Store, Max-Age=60".parse().unwrap();
        assert!(cc.no_store);
        assert_eq!(cc.max_age, Some(60));
    }

    #[test]
    fn parse_max_stale_no_value() {
        let cc: CacheControl = "max-stale".parse().unwrap();
        assert_eq!(cc.max_stale, Some(0));
    }

    #[test]
    fn parse_max_stale_with_value() {
        let cc: CacheControl = "max-stale=300".parse().unwrap();
        assert_eq!(cc.max_stale, Some(300));
    }

    #[test]
    fn builder_private() {
        let cc = CacheControl::new().private();
        assert!(cc.private);
        assert_eq!(cc.to_string(), "private");
    }

    #[test]
    fn builder_no_cache() {
        let cc = CacheControl::new().no_cache();
        assert!(cc.no_cache);
        assert_eq!(cc.to_string(), "no-cache");
    }

    #[test]
    fn builder_no_transform() {
        let cc = CacheControl::new().no_transform();
        assert!(cc.no_transform);
        assert_eq!(cc.to_string(), "no-transform");
    }

    #[test]
    fn builder_must_revalidate() {
        let cc = CacheControl::new().must_revalidate();
        assert!(cc.must_revalidate);
        assert_eq!(cc.to_string(), "must-revalidate");
    }

    #[test]
    fn builder_proxy_revalidate() {
        let cc = CacheControl::new().proxy_revalidate();
        assert!(cc.proxy_revalidate);
        assert_eq!(cc.to_string(), "proxy-revalidate");
    }

    #[test]
    fn builder_s_maxage() {
        let cc = CacheControl::new().s_maxage(7200);
        assert_eq!(cc.s_maxage, Some(7200));
        assert_eq!(cc.to_string(), "s-maxage=7200");
    }

    #[test]
    fn builder_stale_while_revalidate() {
        let cc = CacheControl::new().stale_while_revalidate(60);
        assert_eq!(cc.stale_while_revalidate, Some(60));
        assert_eq!(cc.to_string(), "stale-while-revalidate=60");
    }

    #[test]
    fn builder_stale_if_error() {
        let cc = CacheControl::new().stale_if_error(86_400);
        assert_eq!(cc.stale_if_error, Some(86_400));
        assert_eq!(cc.to_string(), "stale-if-error=86400");
    }

    #[test]
    fn builder_only_if_cached() {
        let cc = CacheControl::new().only_if_cached();
        assert!(cc.only_if_cached);
        assert_eq!(cc.to_string(), "only-if-cached");
    }

    #[test]
    fn builder_max_stale() {
        let cc = CacheControl::new().max_stale(120);
        assert_eq!(cc.max_stale, Some(120));
        assert_eq!(cc.to_string(), "max-stale=120");
    }

    #[test]
    fn builder_min_fresh() {
        let cc = CacheControl::new().min_fresh(30);
        assert_eq!(cc.min_fresh, Some(30));
        assert_eq!(cc.to_string(), "min-fresh=30");
    }

    #[test]
    fn parse_cache_control_error_display() {
        let err = ParseCacheControlError("max-age requires a value".into());
        let s = err.to_string();
        assert!(s.contains("invalid Cache-Control header"));
        assert!(s.contains("max-age requires a value"));
    }

    #[test]
    fn parse_numeric_missing_value_is_error() {
        // max-age without a value should return an error
        let result = "max-age".parse::<CacheControl>();
        assert!(result.is_err());
    }

    #[test]
    fn parse_numeric_bad_integer_is_error() {
        let result = "max-age=abc".parse::<CacheControl>();
        assert!(result.is_err());
    }

    #[test]
    fn parse_all_boolean_directives() {
        let cc: CacheControl = "public, private, no-cache, no-store, no-transform, must-revalidate, proxy-revalidate, immutable, only-if-cached"
            .parse()
            .unwrap();
        assert!(cc.public);
        assert!(cc.private);
        assert!(cc.no_cache);
        assert!(cc.no_store);
        assert!(cc.no_transform);
        assert!(cc.must_revalidate);
        assert!(cc.proxy_revalidate);
        assert!(cc.immutable);
        assert!(cc.only_if_cached);
    }

    #[test]
    fn parse_all_numeric_directives() {
        let cc: CacheControl =
            "max-age=10, s-maxage=20, stale-while-revalidate=30, stale-if-error=40, max-stale=50, min-fresh=60"
                .parse()
                .unwrap();
        assert_eq!(cc.max_age, Some(10));
        assert_eq!(cc.s_maxage, Some(20));
        assert_eq!(cc.stale_while_revalidate, Some(30));
        assert_eq!(cc.stale_if_error, Some(40));
        assert_eq!(cc.max_stale, Some(50));
        assert_eq!(cc.min_fresh, Some(60));
    }

    #[test]
    fn display_mixed_boolean_and_numeric_with_only_if_cached() {
        let cc = CacheControl::new()
            .only_if_cached()
            .max_stale(0)
            .min_fresh(10);
        let s = cc.to_string();
        assert!(s.contains("only-if-cached"));
        assert!(s.contains("max-stale=0"));
        assert!(s.contains("min-fresh=10"));
    }
}