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

use crate::into::IntoResponse;

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

use http::header::{RequestHeader, ResponseHeader, StatusCode};
use http::Response;

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
	}
}


// max-age
// 
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Caching {
	max_age: Duration,
	etag: Etag,
	// only_if_status_ok: bool
}

impl Caching {

	pub fn new(max_age: Duration) -> Self {
		Self {
			max_age,
			etag: Etag::new(),
			// only_if_status_ok: false
		}
	}

	// pub fn new_if_status_ok(max_age: Duration) -> Self {
	// 	Self {
	// 		max_age,
	// 		etag: Etag::new(),
	// 		only_if_status_ok: true
	// 	}
	// }

	// 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)
	}

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

	pub fn complete_header(self, header: &mut ResponseHeader) {
		// if self.only_if_status_ok {
		// 	if &header.status_code != &StatusCode::Ok { // only if status ok
		// 		return
		// 	}
		// }

		header.values.insert("Cache-Control", self.cache_control_string());
		header.values.insert("ETag", String::from(self.etag));
	}

}

impl IntoResponse for Caching {
	fn into_response(self) -> Response {
		Response::builder()
			.status_code(StatusCode::NotModified)
			.header("Cache-Control", self.cache_control_string())
			.header("ETag", String::from(self.etag))
			.build()
	}
}

/*
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EtagMatchRequest {
	IfNoneMatch(Etag),
	IfMatch(Etag), // if present with a range
	None
}
*/