webserver_base/assets/
cache_buster.rs1use std::collections::BTreeMap;
8use std::fmt::{self, Display, Formatter};
9use std::path::{Path, PathBuf};
10
11use axum::body::Body;
12use axum::extract::Request;
13use axum::http::header::{
14 CACHE_CONTROL, ETAG, EXPIRES, IF_MATCH, IF_MODIFIED_SINCE, IF_NONE_MATCH, IF_RANGE,
15 IF_UNMODIFIED_SINCE, PRAGMA,
16};
17use axum::http::{HeaderMap, HeaderValue, StatusCode};
18use axum::middleware::Next;
19use axum::response::Response;
20use jiff::{SignedDuration, Timestamp};
21use tracing::instrument;
22
23use super::error::CacheBusterError;
24use super::generate::STATIC_DIRECTORY;
25use super::manifest::{MANIFEST_PATH, Manifest};
26
27#[derive(Debug, Clone, Default)]
29pub struct CacheBuster {
30 manifest: Manifest,
31 root: PathBuf,
34}
35
36impl CacheBuster {
37 #[must_use]
40 pub fn empty() -> Self {
41 Self::default()
42 }
43
44 #[instrument(skip_all)]
56 pub fn load() -> Result<Self, CacheBusterError> {
57 Self::load_in(Path::new(""))
58 }
59
60 pub(crate) fn load_in(root: &Path) -> Result<Self, CacheBusterError> {
62 let root: PathBuf = root.to_path_buf();
63 if !root.join(STATIC_DIRECTORY).is_dir() {
64 return Ok(Self {
65 manifest: Manifest::default(),
66 root,
67 });
68 }
69 let manifest_path: PathBuf = root.join(MANIFEST_PATH);
70 if !manifest_path.is_file() {
71 return Err(CacheBusterError::MissingManifest {
72 path: manifest_path,
73 });
74 }
75 Ok(Self {
76 manifest: Manifest::load_in(&root)?,
77 root,
78 })
79 }
80
81 pub(crate) fn root(&self) -> &Path {
83 &self.root
84 }
85
86 pub(crate) fn file(&self, original: &str) -> PathBuf {
91 self.root
92 .join(self.get_file(original).trim_start_matches('/'))
93 }
94
95 #[must_use]
101 pub fn get_file(&self, original: &str) -> String {
102 self.manifest.resolve(original).to_string()
103 }
104
105 #[must_use]
112 pub fn is_hashed(&self, original: &str) -> bool {
113 self.manifest.contains(original)
114 }
115
116 #[must_use]
118 pub const fn manifest(&self) -> &Manifest {
119 &self.manifest
120 }
121
122 #[must_use]
124 pub const fn cache(&self) -> &BTreeMap<String, String> {
125 self.manifest.entries()
126 }
127
128 #[must_use]
130 pub fn is_empty(&self) -> bool {
131 self.manifest.is_empty()
132 }
133
134 #[instrument(skip_all)]
148 pub async fn never_cache_middleware(
149 request: Request,
150 next: Next,
151 ) -> Result<Response, StatusCode> {
152 let mut response: Response<Body> = next.run(request).await;
153 if !response.headers().contains_key(CACHE_CONTROL) {
154 mark_never_cached(response.headers_mut());
155 }
156
157 Ok(response)
158 }
159
160 #[instrument(skip_all)]
176 pub async fn forever_cache_middleware(
177 request: Request,
178 next: Next,
179 ) -> Result<Response, StatusCode> {
180 let mut response: Response<Body> = next.run(request).await;
181 let status: StatusCode = response.status();
182 let headers: &mut HeaderMap = response.headers_mut();
183
184 if !status.is_success() && status != StatusCode::NOT_MODIFIED {
185 mark_never_cached(headers);
186 return Ok(response);
187 }
188
189 remove_conditional_headers(headers);
190
191 let one_year: SignedDuration = SignedDuration::from_hours(24 * 365);
192 let expires: Option<Timestamp> = Timestamp::now().checked_add(one_year).ok();
193 if let Some(expires) = expires
194 && let Ok(expires) = HeaderValue::from_str(&expires_date(expires))
195 {
196 headers.insert(EXPIRES, expires);
197 }
198 headers.insert(
199 CACHE_CONTROL,
200 HeaderValue::from_static("public, max-age=31536000, must-revalidate, immutable"),
201 );
202
203 Ok(response)
204 }
205}
206
207impl Display for CacheBuster {
208 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
209 write!(f, "CacheBuster ({} entries):", self.manifest.len())?;
210 for (original, hashed) in self.manifest.entries() {
211 write!(f, "\n\t`{original}` -> `{hashed}`")?;
212 }
213 Ok(())
214 }
215}
216
217pub(crate) fn mark_never_cached(headers: &mut HeaderMap) {
221 remove_conditional_headers(headers);
222 headers.insert(
223 EXPIRES,
224 HeaderValue::from_static("Thu, 01 Jan 1970 00:00:00 GMT"),
225 );
226 headers.insert(
227 CACHE_CONTROL,
228 HeaderValue::from_static("no-cache, no-store, must-revalidate, private, max-age=0"),
229 );
230 headers.insert(PRAGMA, HeaderValue::from_static("no-cache"));
231}
232
233fn remove_conditional_headers(headers: &mut HeaderMap) {
234 headers.remove(ETAG);
235 headers.remove(IF_MODIFIED_SINCE);
236 headers.remove(IF_MATCH);
237 headers.remove(IF_NONE_MATCH);
238 headers.remove(IF_RANGE);
239 headers.remove(IF_UNMODIFIED_SINCE);
240}
241
242fn expires_date(moment: Timestamp) -> String {
244 moment.strftime("%a, %d %b %Y %H:%M:%S +0000").to_string()
245}
246
247#[cfg(test)]
248mod tests {
249 use jiff::Timestamp;
250
251 use super::{CacheBuster, expires_date};
252
253 #[test]
254 fn the_expires_header_is_rfc_2822_in_utc() {
255 let moment: Timestamp = "2027-03-05T04:05:06Z".parse().expect("a real instant");
256
257 assert_eq!("Fri, 05 Mar 2027 04:05:06 +0000", expires_date(moment));
258 }
259
260 #[test]
261 fn an_empty_cache_buster_returns_paths_unchanged() {
262 let cache_buster: CacheBuster = CacheBuster::empty();
263
264 let expected: String = String::from("static/stylesheet/main.css");
265 let actual: String = cache_buster.get_file("static/stylesheet/main.css");
266 assert_eq!(expected, actual);
267
268 let expected: bool = true;
269 let actual: bool = cache_buster.is_empty();
270 assert_eq!(expected, actual);
271 }
272}