volga 0.9.1

Easy & Fast Web Framework for Rust
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! Utilities for Cache-Control header

use crate::{
    error::Error,
    headers::{CACHE_CONTROL, ETag, FromHeaders, Header, HeaderMap, HeaderName, HeaderValue},
};
use std::{fmt, time::SystemTime};

#[cfg(feature = "static-files")]
use std::fs::Metadata;

#[cfg(feature = "middleware")]
use {
    crate::{
        App, HttpResponse, HttpResult,
        routing::{Route, RouteGroup},
    },
    std::future::Future,
};

#[cfg(feature = "static-files")]
const DEFAULT_MAX_AGE: u32 = 60 * 60 * 24; // 24 hours

/// "no-store" directive
pub const NO_STORE: &str = "no-store";
/// "no-cache" directive
pub const NO_CACHE: &str = "no-cache";
/// "max-age" directive
pub const MAX_AGE: &str = "max-age";
/// "s-maxage" directive
pub const S_MAX_AGE: &str = "s-maxage";
/// "must-revalidate" directive
pub const MUST_REVALIDATE: &str = "must-revalidate";
/// "proxy-revalidate" directive
pub const PROXY_REVALIDATE: &str = "proxy-revalidate";
/// "public" directive
pub const PUBLIC: &str = "public";
/// "private" directive
pub const PRIVATE: &str = "private";
/// "immutable" directive
pub const IMMUTABLE: &str = "immutable";
/// "stale-if-error" directive
pub const STALE_IF_ERROR: &str = "stale-if-error";
/// "stale-while-revalidate" directive
pub const STALE_WHILE_REVALIDATE: &str = "stale-while-revalidate";

/// Represents the HTTP [`Cache-Control`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
/// header holds directives (instructions) in both requests and responses that control caching
/// in browsers and shared caches (e.g., Proxies, CDNs).
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CacheControl {
    /// The `no-cache` response directive indicates that the response can be stored in caches,
    /// but the response must be validated with the origin server before each reuse,
    /// even when the cache is disconnected from the origin server.
    no_cache: bool,

    /// The `no-store` response directive indicates that any caches of any kind (private or shared)
    /// should not store this response.
    no_store: bool,

    /// The `max-age` response directive indicates that the response
    /// remains fresh until `N` seconds after the response is generated.
    max_age: Option<u32>,

    /// The `s-maxage` response directive indicates how long the response remains fresh
    /// in a shared cache. The `s-maxage` directive is ignored by private caches, and overrides
    /// the value specified by the `max-age` directive or
    /// the [`Expires`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Expires) header
    /// for shared caches, if they are present.
    s_max_age: Option<u32>,

    /// The `must-revalidate` response directive indicates that the response can be stored in caches
    /// and can be reused while fresh. If the response becomes stale, it must be validated
    /// with the origin server before reuse.
    ///
    /// Typically, must-revalidate is used with `max-age`.
    must_revalidate: bool,

    /// The `proxy-revalidate` response directive is the equivalent of `must-revalidate`,
    /// but specifically for shared caches only.
    proxy_revalidate: bool,

    /// The stale-while-revalidate response directive indicates that the cache could reuse
    /// a stale response while it revalidates it to a cache.
    stale_while_revalidate: Option<u32>,

    /// The stale-if-error response directive indicates that the cache can reuse a stale response
    /// when an upstream server generates an error or when the error is generated locally.
    ///
    /// Here, an error is considered any response with a status code of 500, 502, 503, or 504.
    stale_if_error: Option<u32>,

    /// The `public` response directive indicates that the response can be stored in a shared cache.
    /// Responses for requests with
    /// [`Authorization`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) header
    /// fields must not be stored in a shared cache; however, the `public` directive will cause such
    /// responses to be stored in a shared cache.
    public: bool,

    /// The `private` response directive indicates that the response can be stored only
    /// in a private cache (e.g. local caches in browsers).
    private: bool,

    /// The `immutable` response directive indicates that the response will not be updated
    /// while it's fresh.
    immutable: bool,
}

impl FromHeaders for CacheControl {
    const NAME: HeaderName = CACHE_CONTROL;

    #[inline]
    fn from_headers(headers: &HeaderMap) -> Option<&HeaderValue> {
        headers.get(Self::NAME)
    }
}

impl fmt::Display for CacheControl {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut directives = Vec::new();

        if self.no_cache {
            directives.push(NO_CACHE.to_string());
        }
        if self.no_store {
            directives.push(NO_STORE.to_string());
        }
        if let Some(max_age) = self.max_age {
            directives.push(format!("{MAX_AGE}={max_age}"));
        }
        if let Some(s_max_age) = self.s_max_age {
            directives.push(format!("{S_MAX_AGE}={s_max_age}"));
        }
        if self.must_revalidate {
            directives.push(MUST_REVALIDATE.to_string());
        }
        if self.proxy_revalidate {
            directives.push(PROXY_REVALIDATE.to_string());
        }
        if self.public {
            directives.push(PUBLIC.to_string());
        }
        if self.private {
            directives.push(PRIVATE.to_string());
        }
        if self.immutable {
            directives.push(IMMUTABLE.to_string());
        }
        if let Some(stale_while_revalidate) = self.stale_while_revalidate {
            directives.push(format!("{STALE_WHILE_REVALIDATE}={stale_while_revalidate}"));
        }
        if let Some(stale_if_error) = self.stale_if_error {
            directives.push(format!("{STALE_IF_ERROR}={stale_if_error}"));
        }

        f.write_str(directives.join(", ").as_str())
    }
}

impl From<CacheControl> for String {
    #[inline]
    fn from(cc: CacheControl) -> Self {
        cc.to_string()
    }
}

impl TryFrom<CacheControl> for HeaderValue {
    type Error = Error;

    #[inline]
    fn try_from(value: CacheControl) -> Result<Self, Self::Error> {
        HeaderValue::from_str(value.to_string().as_str()).map_err(Into::into)
    }
}

impl TryFrom<CacheControl> for Header<CacheControl> {
    type Error = Error;

    #[inline]
    fn try_from(value: CacheControl) -> Result<Self, Self::Error> {
        Ok(Self::new(value.try_into()?))
    }
}

impl CacheControl {
    /// Creates a new instance of [`Header<T>`] from a `static str`
    #[inline(always)]
    pub const fn from_static(value: &'static str) -> Header<Self> {
        Header::<Self>::from_static(value)
    }

    /// Construct a typed header from bytes (validated).
    #[inline]
    pub fn from_bytes(bytes: &[u8]) -> Result<Header<Self>, Error> {
        Header::<Self>::from_bytes(bytes)
    }

    /// Wrap an owned raw HeaderValue (validated elsewhere).
    #[inline]
    pub fn new(value: HeaderValue) -> Header<Self> {
        Header::<Self>::new(value)
    }

    /// Wrap a borrowed raw HeaderValue (validated elsewhere).
    #[inline]
    pub fn from_ref(value: &HeaderValue) -> Header<Self> {
        Header::<Self>::from_ref(value)
    }

    /// Enables `no-cache`: forces caches to validate with origin server before reuse.
    /// Disables `immutable`, since they contradict each other.
    pub fn with_no_cache(mut self) -> Self {
        self.no_cache = true;
        self.immutable = false;
        self
    }

    /// Enables `no-store`: disables any form of caching.
    /// Clears `max-age` and `s-maxage`, which would otherwise allow caching.
    pub fn with_no_store(mut self) -> Self {
        self.no_store = true;
        self.max_age = None;
        self.s_max_age = None;
        self.stale_if_error = None;
        self.stale_while_revalidate = None;
        self
    }

    /// Sets `max-age`: how long the response is fresh in seconds.
    /// Disables `no-store` to allow caching.
    pub fn with_max_age(mut self, max_age: u32) -> Self {
        self.max_age = Some(max_age);
        self.no_store = false;
        self
    }

    /// Sets `s-maxage`: max age for shared (e.g., proxy) caches.
    /// Disables `no-store`.
    pub fn with_s_max_age(mut self, s_max_age: u32) -> Self {
        self.s_max_age = Some(s_max_age);
        self.no_store = false;
        self
    }

    /// Enables `must-revalidate`: once stale, the cache must validate.
    /// Disables `immutable`, which implies no validation.
    pub fn with_must_revalidate(mut self) -> Self {
        self.must_revalidate = true;
        self.immutable = false;
        self
    }

    /// Enables `proxy-revalidate`: like `must-revalidate` but for shared caches.
    /// Disables `immutable`.
    pub fn with_proxy_revalidate(mut self) -> Self {
        self.proxy_revalidate = true;
        self.immutable = false;
        self
    }

    /// Enables `public`: allows shared caches to store response.
    /// Disables `private`, which restricts to client-only.
    pub fn with_public(mut self) -> Self {
        self.public = true;
        self.private = false;
        self
    }

    /// Enables `private`: only client (browser) may cache the response.
    /// Disables `public`.
    pub fn with_private(mut self) -> Self {
        self.private = true;
        self.public = false;
        self
    }

    /// Enables `immutable`: response is guaranteed not to change.
    /// Disables `no-cache`, `must-revalidate`, `proxy-revalidate`.
    pub fn with_immutable(mut self) -> Self {
        self.immutable = true;
        self.no_cache = false;
        self.proxy_revalidate = false;
        self.must_revalidate = false;
        self
    }

    /// Sets `stale-while-revalidate`: indicates that the cache could reuse a stale response
    /// while it revalidates it to a cache.
    /// Disables `no-store` to allow caching.
    pub fn with_stale_while_revalidate(mut self, age: u32) -> Self {
        self.stale_while_revalidate = Some(age);
        self.no_store = false;
        self
    }

    /// Sets `stale-if-error`: indicates that the cache can reuse a stale response
    /// when an upstream server generates an error or when the error is generated locally.
    /// Disables `no-store` to allow caching.
    ///
    /// Here, an error is considered any response with a status code of 500, 502, 503, or 504.
    pub fn with_stale_if_error(mut self, age: u32) -> Self {
        self.stale_if_error = Some(age);
        self.no_store = false;
        self
    }
}

/// Represents a response caching data that is a composition of:
/// [`ETag`](https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/ETag),
/// [`Last-Modified`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified) and
/// [`Cache-Control`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
#[derive(Debug)]
pub struct ResponseCaching {
    /// Represents
    /// [`ETag`](https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/ETag)
    pub(crate) etag: ETag,

    /// Represents
    /// [`Last-Modified`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified)
    pub(crate) last_modified: SystemTime,

    /// Represents
    /// [`Cache-Control`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
    pub(crate) cache_control: CacheControl,
}

#[cfg(feature = "static-files")]
impl TryFrom<&Metadata> for ResponseCaching {
    type Error = Error;

    #[inline]
    fn try_from(meta: &Metadata) -> Result<Self, Self::Error> {
        let last_modified = meta.modified()?;
        let etag: ETag = meta.try_into()?;
        let cache_control = CacheControl {
            public: true,
            immutable: true,
            max_age: Some(DEFAULT_MAX_AGE),
            ..Default::default()
        };

        let this = Self {
            cache_control,
            etag,
            last_modified,
        };
        Ok(this)
    }
}

impl ResponseCaching {
    /// Returns a [`ETag`](https://developer.mozilla.org/ru/docs/Web/HTTP/Headers/ETag) value as `&str`
    #[inline]
    pub fn etag(&self) -> &str {
        self.etag.as_ref()
    }

    /// Returns [`Last-Modified`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Last-Modified)
    /// as [`String`]
    #[inline]
    pub fn last_modified(&self) -> String {
        httpdate::fmt_http_date(self.last_modified)
    }

    /// Returns [`Cache-Control`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)
    /// as [`String`]
    #[inline]
    pub fn cache_control(&self) -> String {
        self.cache_control.into()
    }
}

#[cfg(feature = "middleware")]
impl App {
    /// Configures a `cache-control` header that will be added for all responses from this server
    /// if they are not explicitly configured for the route or route group.
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, headers::CacheControl};
    ///
    ///# #[tokio::main]
    ///# async fn main() -> std::io::Result<()> {
    /// let mut app = App::new()
    ///     .with_cache_control(|cache_control| cache_control
    ///         .with_max_age(60)
    ///         .with_immutable()
    ///         .with_public());
    ///
    /// app.map_get("/hello", || async move { "Hello, World!" });
    ///
    ///# app.run().await
    ///# }
    /// ```
    pub fn with_cache_control<F>(mut self, config: F) -> Self
    where
        F: Fn(CacheControl) -> CacheControl,
    {
        self.cache_control = Some(config(CacheControl::default()));
        self
    }
}

#[cfg(feature = "middleware")]
impl<'a> Route<'a> {
    /// Adds middleware that includes a configured `cache-control` header for all responses from this route.
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, headers::CacheControl};
    ///
    ///# #[tokio::main]
    ///# async fn main() -> std::io::Result<()> {
    /// let mut app = App::new();
    ///
    /// app.map_get("/hello", || async move { "Hello, World!" })
    ///     .cache_control(|cache_control| cache_control
    ///         .with_max_age(60)
    ///         .with_immutable()
    ///         .with_public());
    ///
    ///# app.run().await
    ///# }
    /// ```
    pub fn cache_control<F>(self, config: F) -> Self
    where
        F: Fn(CacheControl) -> CacheControl,
    {
        let hv: HeaderValue = config(CacheControl::default())
            .try_into()
            .expect("valid cache-control header");

        self.map_ok(move |resp: HttpResponse| {
            make_cache_control_fn(resp, hv.clone(), HeaderInsertMode::Override)
        })
    }
}

#[cfg(feature = "middleware")]
impl<'a> RouteGroup<'a> {
    /// Adds middleware that includes a configured `cache-control` header for all responses from this group of routes.
    ///
    /// # Example
    /// ```no_run
    /// use volga::{App, headers::CacheControl};
    ///
    ///# #[tokio::main]
    ///# async fn main() -> std::io::Result<()> {
    /// let mut app = App::new();
    ///
    /// app.group("/greeting", |api| {
    ///     api.cache_control(|cache_control| cache_control
    ///         .with_max_age(60)
    ///         .with_immutable()
    ///         .with_public());
    ///
    ///     api.map_get("/hello", || async move { "Hello, World!" });    
    /// });
    ///# app.run().await
    ///# }
    /// ```
    pub fn cache_control<F>(&mut self, config: F) -> &mut Self
    where
        F: Fn(CacheControl) -> CacheControl,
    {
        let hv: HeaderValue = config(CacheControl::default())
            .try_into()
            .expect("valid cache-control header");

        self.map_ok(move |resp: HttpResponse| {
            make_cache_control_fn(resp, hv.clone(), HeaderInsertMode::IfAbsent)
        })
    }
}

#[cfg(feature = "middleware")]
#[derive(Copy, Clone)]
enum HeaderInsertMode {
    Override,
    IfAbsent,
}

#[cfg(feature = "middleware")]
#[inline]
fn make_cache_control_fn(
    mut resp: HttpResponse,
    hv: HeaderValue,
    mode: HeaderInsertMode,
) -> impl Future<Output = HttpResult> {
    match mode {
        HeaderInsertMode::Override => {
            resp.headers_mut().insert(CACHE_CONTROL, hv);
        }
        HeaderInsertMode::IfAbsent => {
            if !resp.headers().contains_key(CACHE_CONTROL) {
                resp.headers_mut().insert(CACHE_CONTROL, hv);
            }
        }
    }

    futures_util::future::ready(Ok(resp))
}

#[cfg(test)]
mod tests {
    use crate::headers::{CacheControl, ETag, Header, ResponseCaching};
    use std::time::SystemTime;

    #[test]
    fn it_creates_cache_control_string() {
        let cache_control = CacheControl {
            max_age: 60.into(),
            public: true,
            must_revalidate: false,
            proxy_revalidate: true,
            no_store: true,
            no_cache: false,
            s_max_age: 60.into(),
            ..Default::default()
        };

        assert_eq!(
            "no-store, max-age=60, s-maxage=60, proxy-revalidate, public",
            cache_control.to_string()
        );
    }

    #[test]
    fn if_returns_etag() {
        let caching = ResponseCaching {
            etag: ETag::strong("123"),
            last_modified: SystemTime::now(),
            cache_control: Default::default(),
        };

        assert_eq!(caching.etag(), "\"123\"");
    }

    #[test]
    fn if_returns_last_modified_string() {
        let now = SystemTime::now();
        let caching = ResponseCaching {
            etag: ETag::strong("123"),
            last_modified: now,
            cache_control: Default::default(),
        };

        assert_eq!(caching.last_modified(), httpdate::fmt_http_date(now));
    }

    #[test]
    fn if_returns_cache_control_string() {
        let cache_control = CacheControl {
            max_age: 60.into(),
            private: true,
            immutable: true,
            ..Default::default()
        };

        let caching = ResponseCaching {
            etag: ETag::strong("123"),
            last_modified: SystemTime::now(),
            cache_control,
        };

        assert_eq!(caching.cache_control(), "max-age=60, private, immutable");
    }

    #[test]
    fn it_tests_no_store_clears_ages() {
        let cc = CacheControl::default()
            .with_max_age(300)
            .with_s_max_age(120)
            .with_no_store();

        assert!(cc.no_store);
        assert_eq!(cc.max_age, None);
        assert_eq!(cc.s_max_age, None);
        assert_eq!(cc.stale_if_error, None);
        assert_eq!(cc.stale_while_revalidate, None);
    }

    #[test]
    fn it_tests_public_private_conflict() {
        let cc = CacheControl::default().with_private().with_public();
        assert!(cc.public);
        assert!(!cc.private);
    }

    #[test]
    fn it_tests_immutable_conflicts() {
        let cc = CacheControl::default()
            .with_must_revalidate()
            .with_proxy_revalidate()
            .with_no_cache()
            .with_immutable();

        assert!(cc.immutable);
        assert!(!cc.no_cache);
        assert!(!cc.must_revalidate);
        assert!(!cc.proxy_revalidate);
    }

    #[test]
    fn it_tests_max_age_disables_no_store() {
        let cc = CacheControl::default().with_no_store().with_max_age(600);
        assert!(!cc.no_store);
        assert_eq!(cc.max_age, Some(600));
    }

    #[test]
    fn it_tests_combination() {
        let cc = CacheControl::default()
            .with_public()
            .with_max_age(3600)
            .with_immutable();

        assert!(cc.public);
        assert_eq!(cc.max_age, Some(3600));
        assert!(cc.immutable);
    }

    #[test]
    fn it_tests_stale_while_revalidate() {
        let cc = CacheControl::default().with_stale_while_revalidate(600);
        assert_eq!(cc.stale_while_revalidate, Some(600));
    }

    #[test]
    fn it_tests_stale_if_error() {
        let cc = CacheControl::default().with_stale_if_error(600);
        assert_eq!(cc.stale_if_error, Some(600));
    }

    #[test]
    fn it_converts_cache_control_to_header() {
        let cc = CacheControl::default()
            .with_no_cache()
            .with_must_revalidate()
            .with_max_age(0);

        let header = Header::<CacheControl>::try_from(cc).unwrap();

        assert_eq!(header.name(), "cache-control");
        assert_eq!(
            header.value().to_str().unwrap(),
            "no-cache, max-age=0, must-revalidate"
        )
    }
}