yaiko_core/
compression_policy.rs1#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum CompressionEncoding {
5 Brotli,
6 Gzip,
7 Identity,
8}
9
10impl CompressionEncoding {
11 pub fn as_str(self) -> &'static str {
12 match self {
13 Self::Brotli => "br",
14 Self::Gzip => "gzip",
15 Self::Identity => "identity",
16 }
17 }
18}
19
20#[derive(Debug, Clone, PartialEq)]
21pub struct CompressionPolicy {
22 pub min_size: usize,
23 pub compressible_types: Vec<String>,
24}
25
26impl Default for CompressionPolicy {
27 fn default() -> Self {
28 Self {
29 min_size: 1024,
30 compressible_types: vec![
31 "text/".into(),
32 "application/json".into(),
33 "application/javascript".into(),
34 "image/svg+xml".into(),
35 ],
36 }
37 }
38}
39
40impl CompressionPolicy {
41 pub fn min_size(mut self, min_size: usize) -> Self {
42 self.min_size = min_size;
43 self
44 }
45
46 pub fn should_compress(&self, content_type: Option<&str>, body_len: usize) -> bool {
47 body_len >= self.min_size
48 && content_type
49 .map(|content_type| {
50 self.compressible_types
51 .iter()
52 .any(|allowed| content_type.starts_with(allowed))
53 })
54 .unwrap_or(false)
55 }
56
57 pub fn negotiate(
58 &self,
59 accept_encoding: &str,
60 content_type: Option<&str>,
61 body_len: usize,
62 ) -> CompressionDecision {
63 if !self.should_compress(content_type, body_len) {
64 return CompressionDecision {
65 encoding: CompressionEncoding::Identity,
66 vary_accept_encoding: false,
67 };
68 }
69 let mut br = 0.0;
70 let mut gzip = 0.0;
71 let mut wildcard = 0.0;
72 for item in accept_encoding.split(',') {
73 let mut parts = item.trim().split(';');
74 let name = parts.next().unwrap_or_default().trim();
75 let quality = parts
76 .find_map(|part| {
77 part.trim()
78 .strip_prefix("q=")
79 .and_then(|value| value.parse::<f32>().ok())
80 })
81 .unwrap_or(1.0);
82 match name {
83 "br" => br = quality,
84 "gzip" => gzip = quality,
85 "*" => wildcard = quality,
86 _ => {}
87 }
88 }
89 let br = if br == 0.0 { wildcard } else { br };
90 let gzip = if gzip == 0.0 { wildcard } else { gzip };
91 let encoding = if br > 0.0 && br >= gzip {
92 CompressionEncoding::Brotli
93 } else if gzip > 0.0 {
94 CompressionEncoding::Gzip
95 } else {
96 CompressionEncoding::Identity
97 };
98 CompressionDecision {
99 encoding,
100 vary_accept_encoding: true,
101 }
102 }
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub struct CompressionDecision {
107 pub encoding: CompressionEncoding,
108 pub vary_accept_encoding: bool,
109}
110
111impl CompressionDecision {
112 pub fn response_headers(self) -> Vec<(&'static str, String)> {
113 let mut headers = vec![("Vary", "Accept-Encoding".to_string())];
114 if self.encoding != CompressionEncoding::Identity {
115 headers.push(("Content-Encoding", self.encoding.as_str().to_string()));
116 }
117 headers
118 }
119}
120
121#[cfg(test)]
122mod tests {
123 use super::*;
124
125 #[test]
126 fn negotiates_quality_values_and_prefers_brotli_on_tie() {
127 let policy = CompressionPolicy::default().min_size(10);
128 let decision = policy.negotiate("gzip;q=0.8, br;q=1.0", Some("application/json"), 100);
129 assert_eq!(decision.encoding, CompressionEncoding::Brotli);
130 let gzip = policy.negotiate("gzip;q=1, br;q=0", Some("application/json"), 100);
131 assert_eq!(gzip.encoding, CompressionEncoding::Gzip);
132 }
133
134 #[test]
135 fn honors_wildcard_and_rejects_unaccepted_encodings() {
136 let policy = CompressionPolicy::default().min_size(10);
137 assert_eq!(
138 policy
139 .negotiate("*;q=0.5", Some("text/plain"), 100)
140 .encoding,
141 CompressionEncoding::Brotli
142 );
143 assert_eq!(
144 policy
145 .negotiate("identity", Some("text/plain"), 100)
146 .encoding,
147 CompressionEncoding::Identity
148 );
149 }
150
151 #[test]
152 fn skips_small_and_incompressible_payloads() {
153 let policy = CompressionPolicy::default().min_size(100);
154 assert_eq!(
155 policy
156 .negotiate("br, gzip", Some("image/png"), 1000)
157 .encoding,
158 CompressionEncoding::Identity
159 );
160 assert!(!policy.should_compress(Some("application/octet-stream"), 1000));
161 assert!(!policy.should_compress(Some("text/plain"), 99));
162 }
163
164 #[test]
165 fn emits_vary_and_content_encoding_headers() {
166 let headers = CompressionDecision {
167 encoding: CompressionEncoding::Gzip,
168 vary_accept_encoding: true,
169 }
170 .response_headers();
171 assert_eq!(headers[0], ("Vary", "Accept-Encoding".to_string()));
172 assert_eq!(headers[1], ("Content-Encoding", "gzip".to_string()));
173 }
174}