Skip to main content

tower_http_cache_plus/cache/middleware/
hooks.rs

1use {http::request::*, http::*, kutil::transcoding::*, std::sync::*};
2
3/// Hook to check if a request or a response is cacheable.
4pub type CacheableHook = Arc<Box<dyn Fn(CacheableHookContext) -> bool + Send + Sync>>;
5
6/// Hook to check if a request or a response is encodable.
7pub type EncodableHook = Arc<Box<dyn Fn(EncodableHookContext) -> bool + Send + Sync>>;
8
9/// Hook to update a request's cache key.
10pub type CacheKeyHook<CacheKeyT, RequestBodyT> =
11    Arc<Box<dyn Fn(CacheKeyHookContext<CacheKeyT, RequestBodyT>) + Send + Sync>>;
12
13//
14// CacheableHookContext
15//
16
17/// Context for [CacheableHook].
18#[derive(Clone, Debug)]
19pub struct CacheableHookContext<'this> {
20    /// URI.
21    pub uri: &'this Uri,
22
23    /// Headers.
24    pub headers: &'this HeaderMap,
25}
26
27impl<'this> CacheableHookContext<'this> {
28    /// Constructor.
29    pub fn new(uri: &'this Uri, headers: &'this HeaderMap) -> Self {
30        Self { uri, headers }
31    }
32}
33
34//
35// EncodableHookContext
36//
37
38/// Context for [EncodableHook].
39#[derive(Clone, Debug)]
40pub struct EncodableHookContext<'this> {
41    /// Encoding.
42    pub encoding: &'this Encoding,
43
44    /// URI.
45    pub uri: &'this Uri,
46
47    /// Headers.
48    pub headers: &'this HeaderMap,
49}
50
51impl<'this> EncodableHookContext<'this> {
52    /// Constructor.
53    pub fn new(encoding: &'this Encoding, uri: &'this Uri, headers: &'this HeaderMap) -> Self {
54        Self {
55            encoding,
56            uri,
57            headers,
58        }
59    }
60}
61
62//
63// CacheKeyHookContext
64//
65
66/// Context for [CacheKeyHook].
67#[derive(Debug)]
68pub struct CacheKeyHookContext<'this, CacheKeyT, RequestBodyT> {
69    /// Cache key.
70    pub cache_key: &'this mut CacheKeyT,
71
72    /// Request.
73    pub request: &'this Request<RequestBodyT>,
74}
75
76impl<'this, CacheKeyT, RequestBodyT> CacheKeyHookContext<'this, CacheKeyT, RequestBodyT> {
77    /// Constructor.
78    pub fn new(cache_key: &'this mut CacheKeyT, request: &'this Request<RequestBodyT>) -> Self {
79        Self { cache_key, request }
80    }
81}