http_cache_stream/
storage.rs

1//! Implementation of cache storage.
2
3use std::path::PathBuf;
4
5use anyhow::Result;
6use http::Response;
7use http::response::Parts;
8use http_cache_semantics::CachePolicy;
9
10use crate::HttpBody;
11use crate::body::Body;
12
13mod default;
14
15pub use default::*;
16
17/// Represents a response from storage.
18pub struct StoredResponse<B: HttpBody> {
19    /// The cached response.
20    pub response: Response<Body<B>>,
21    /// The current cache policy.
22    pub policy: CachePolicy,
23    /// The response content digest.
24    pub digest: String,
25}
26
27/// A trait implemented on cache storage.
28///
29/// Cache keys are strings of hexadecimal characters.
30pub trait CacheStorage: Send + Sync + 'static {
31    /// Gets a previously stored response for the given response key.
32    ///
33    /// Returns `Ok(None)` if a response does not exist in the storage for the
34    /// given response key.
35    fn get<B: HttpBody>(
36        &self,
37        key: &str,
38    ) -> impl Future<Output = Result<Option<StoredResponse<B>>>> + Send;
39
40    /// Puts a response with an existing content digest into the storage for the
41    /// given response key.
42    ///
43    /// The provided content digest must come from a previous call to
44    /// [`CacheStorage::get`].
45    fn put(
46        &self,
47        key: &str,
48        parts: &Parts,
49        policy: &CachePolicy,
50        digest: &str,
51    ) -> impl Future<Output = Result<()>> + Send;
52
53    /// Puts a response with supplied body into the storage for the given
54    /// response key.
55    ///
56    /// Returns the body from the cache along with its digest upon success.
57    fn put_with_body<B: HttpBody>(
58        &self,
59        key: &str,
60        parts: &Parts,
61        policy: &CachePolicy,
62        body: B,
63    ) -> impl Future<Output = Result<(Body<B>, String)>> + Send;
64
65    /// Deletes a previously cached response for the given response key.
66    ///
67    /// Deleting an unknown key is not considered an error.
68    fn delete(&self, key: &str) -> impl Future<Output = Result<()>> + Send;
69
70    /// Gets the path to a response body for the given content digest.
71    ///
72    /// This method does not verify the content's existence.
73    fn body_path(&self, digest: &str) -> PathBuf;
74}