tower_http/follow_redirect/policy/
limited.rs

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
use super::{Action, Attempt, Policy};

/// A redirection [`Policy`] that limits the number of successive redirections.
#[derive(Clone, Copy, Debug)]
pub struct Limited {
    remaining: usize,
}

impl Limited {
    /// Create a new [`Limited`] with a limit of `max` redirections.
    pub fn new(max: usize) -> Self {
        Limited { remaining: max }
    }
}

impl Default for Limited {
    /// Returns the default [`Limited`] with a limit of `20` redirections.
    fn default() -> Self {
        // This is the (default) limit of Firefox and the Fetch API.
        // https://hg.mozilla.org/mozilla-central/file/6264f13d54a1caa4f5b60303617a819efd91b8ee/modules/libpref/init/all.js#l1371
        // https://fetch.spec.whatwg.org/#http-redirect-fetch
        Limited::new(20)
    }
}

impl<B, E> Policy<B, E> for Limited {
    fn redirect(&mut self, _: &Attempt<'_>) -> Result<Action, E> {
        if self.remaining > 0 {
            self.remaining -= 1;
            Ok(Action::Follow)
        } else {
            Ok(Action::Stop)
        }
    }
}

#[cfg(test)]
mod tests {
    use http::{Request, Uri};

    use super::*;

    #[test]
    fn works() {
        let uri = Uri::from_static("https://example.com/");
        let mut policy = Limited::new(2);

        for _ in 0..2 {
            let mut request = Request::builder().uri(uri.clone()).body(()).unwrap();
            Policy::<(), ()>::on_request(&mut policy, &mut request);

            let attempt = Attempt {
                status: Default::default(),
                location: &uri,
                previous: &uri,
            };
            assert!(Policy::<(), ()>::redirect(&mut policy, &attempt)
                .unwrap()
                .is_follow());
        }

        let mut request = Request::builder().uri(uri.clone()).body(()).unwrap();
        Policy::<(), ()>::on_request(&mut policy, &mut request);

        let attempt = Attempt {
            status: Default::default(),
            location: &uri,
            previous: &uri,
        };
        assert!(Policy::<(), ()>::redirect(&mut policy, &attempt)
            .unwrap()
            .is_stop());
    }
}