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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
use crate::Response;
use crate::into::IntoResponse;
use crate::header::{
	RequestHeader, ResponseHeader, StatusCode,
	IF_NONE_MATCH, CACHE_CONTROL, ETAG
};

use std::fmt;
use std::time::Duration;

use rand::{thread_rng, Rng};
use rand::distributions::Alphanumeric;


// == 1day
const DEFAULT_MAX_AGE: Duration = Duration::from_secs(60 * 60 * 24);


#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Etag(String);

impl Etag {
	pub fn new() -> Self {
		let rand_str: String = thread_rng()
			.sample_iter(&Alphanumeric)
			.map(char::from)
			.take(30)
			.collect();

		Self(rand_str)
	}

	pub fn as_str(&self) -> &str {
		self.0.as_str()
	}
}

impl fmt::Display for Etag {
	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
		self.0.fmt(f)
	}
}

impl From<Etag> for String {
	fn from(e: Etag) -> Self {
		e.0
	}
}

impl PartialEq<&str> for Etag {
	fn eq(&self, other: &&str) -> bool {
		self.as_str() == *other
	}
}


/// Controls if caching information should be sent.
/// 
/// The Caching struct contains an Etag which stores a random tag which
/// indentifies a specific file. The Etag gets generated when the struct gets
/// created.
/// 
/// ## Example
/// ```ignore
/// # use fire_http as fire;
/// use fire::{get, Request};
/// use fire::fs::Caching;
/// use fire::into::IntoResponse;
/// use std::cell::LazyCell;
/// 
/// 
/// const INDEX_CACHE: LazyCell<Caching> = LazyCell::new(|| {
/// 	Caching::default()
/// });
/// 
/// #[get("/")]
/// fn index(req: &mut Request) -> Response {
/// 	let cache = INDEX_CACHE.clone();
/// 	if cache.if_none_match(req.header()) {
/// 		return cache.into_response()
/// 	}
/// 
/// 	let mut resp = Response::html("<h1>Hello, World!</h1>");
/// 	cache.complete_header(&mut resp.header);
/// 	
/// 	resp
/// }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Caching {
	max_age: Duration,
	etag: Etag
}

impl Caching {
	pub fn new(max_age: Duration) -> Self {
		Self {
			max_age,
			etag: Etag::new()
		}
	}

	// defaults to 1 day
	pub fn default() -> Self {
		Self::new(DEFAULT_MAX_AGE)
	}

	pub fn if_none_match(&self, header: &RequestHeader) -> bool {
		header.value(IF_NONE_MATCH)
			.map(|none_match| {
				none_match.len() == 30 &&
				self.etag == none_match
			})
			.unwrap_or(false)
	}

	fn cache_control_string(&self) -> String {
		format!("max-age={}, public", self.max_age.as_secs())
	}

	pub fn complete_header(self, header: &mut ResponseHeader) {
		header.values.insert(CACHE_CONTROL, self.cache_control_string());

		// etag makes only sense with files not 404
		if header.status_code == StatusCode::OK {
			header.values.insert(ETAG, String::from(self.etag));
		}
	}
}

impl IntoResponse for Caching {
	fn into_response(self) -> Response {
		Response::builder()
			.status_code(StatusCode::NOT_MODIFIED)
			.header(CACHE_CONTROL, self.cache_control_string())
			.header(ETAG, String::from(self.etag))
			.build()
	}
}