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    /// Stores a new response body in the cache.
54    ///
55    /// Returns a response with a body streaming to the cache.
56    fn store<B: HttpBody>(
57        &self,
58        key: String,
59        parts: Parts,
60        body: B,
61        policy: CachePolicy,
62    ) -> impl Future<Output = Result<Response<Body<B>>>> + Send;
63
64    /// Deletes a previously cached response for the given response key.
65    ///
66    /// Deleting an unknown key is not considered an error.
67    fn delete(&self, key: &str) -> impl Future<Output = Result<()>> + Send;
68
69    /// Gets the path to a response body for the given content digest.
70    ///
71    /// This method does not verify the content's existence.
72    fn body_path(&self, digest: &str) -> PathBuf;
73}