silent 2.16.1

Silent Web Framework
Documentation
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use http::header::{ACCEPT_ENCODING, CONTENT_ENCODING, VARY};

use crate::{Request, Response};

use super::StaticOptions;

pub(super) enum Compression {
    Brotli,
    Gzip,
}

pub(super) fn negotiate(
    options: &StaticOptions,
    req: &Request,
    content_type: Option<&mime::Mime>,
) -> Option<Compression> {
    if !options.enable_compression {
        return None;
    }
    let content_type = content_type?;
    if !is_mime_compressible(content_type) {
        return None;
    }
    let header = req.headers().get(ACCEPT_ENCODING)?;
    let value = header.to_str().ok()?;
    parse_accept_encoding(value)
}

pub(super) fn apply_headers(res: &mut Response, compression: &Compression) {
    let (encoding, vary) = match compression {
        Compression::Brotli => ("br", "Accept-Encoding"),
        Compression::Gzip => ("gzip", "Accept-Encoding"),
    };
    res.headers_mut()
        .insert(CONTENT_ENCODING, encoding.parse().unwrap());
    res.headers_mut().insert(VARY, vary.parse().unwrap());
}

fn parse_accept_encoding(header: &str) -> Option<Compression> {
    let mut brotli = None;
    let mut gzip = None;
    for (index, item) in header.split(',').enumerate() {
        let item = item.trim();
        let mut parts = item.split(';');
        let encoding = parts.next()?.trim();
        let mut quality = 1.0_f32;
        for param in parts {
            let mut kv = param.splitn(2, '=');
            if kv.next().map(|p| p.trim()) == Some("q")
                && let Some(v) = kv.next()
                && let Ok(parsed) = v.trim().parse::<f32>()
            {
                quality = parsed;
            }
        }
        if quality == 0.0 {
            continue;
        }
        match encoding {
            "br" => {
                brotli.get_or_insert(index);
            }
            "gzip" | "x-gzip" => {
                gzip.get_or_insert(index);
            }
            "*" => {
                gzip.get_or_insert(index + 1000);
            }
            _ => {}
        }
    }
    if brotli.is_some() {
        Some(Compression::Brotli)
    } else if gzip.is_some() {
        Some(Compression::Gzip)
    } else {
        None
    }
}

fn is_mime_compressible(mime: &mime::Mime) -> bool {
    matches!(
        (mime.type_(), mime.subtype().as_str()),
        (mime::TEXT, _)
            | (mime::APPLICATION, "json")
            | (mime::APPLICATION, "xml")
            | (mime::APPLICATION, "javascript")
            | (mime::APPLICATION, "ecmascript")
            | (mime::APPLICATION, "x-javascript")
            | (mime::APPLICATION, "xhtml+xml")
            | (mime::APPLICATION, "rss+xml")
            | (mime::APPLICATION, "svg+xml")
            | (mime::IMAGE, "svg+xml")
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::header::{ACCEPT_ENCODING, CONTENT_ENCODING, HeaderValue, VARY};

    // ==================== is_mime_compressible 测试 ====================

    #[test]
    fn test_is_mime_compressible_text_types() {
        // 测试各种 TEXT 类型
        assert!(is_mime_compressible(&mime::TEXT_PLAIN));
        assert!(is_mime_compressible(&mime::TEXT_HTML));
        assert!(is_mime_compressible(&mime::TEXT_CSS));
        assert!(is_mime_compressible(&mime::TEXT_JAVASCRIPT));
    }

    #[test]
    fn test_is_mime_compressible_application_json() {
        // 测试 APPLICATION 类型
        assert!(is_mime_compressible(&mime::APPLICATION_JSON));
        assert!(is_mime_compressible(&"application/xml".parse().unwrap()));
        assert!(is_mime_compressible(&mime::APPLICATION_JAVASCRIPT));
        assert!(is_mime_compressible(
            &"application/ecmascript".parse().unwrap()
        ));
        assert!(is_mime_compressible(
            &"application/x-javascript".parse().unwrap()
        ));
    }

    #[test]
    fn test_is_mime_compressible_xml_types() {
        // 测试 XML 相关类型
        // 注意:application/xhtml+xml 解析后 subtype 是 "xhtml"(不是 "xhtml+xml")
        // 当前函数的匹配模式 (APPLICATION, "xhtml+xml") 不会匹配这个类型
        // 所以这个测试反映了当前的行为,不是期望的行为
        let xhtml: mime::Mime = "application/xhtml+xml".parse().unwrap();
        assert_eq!(xhtml.type_(), mime::APPLICATION);
        assert_eq!(xhtml.subtype().as_str(), "xhtml"); // subtype 是 "xhtml",不是 "xhtml+xml"
        // 当前实现不会匹配,因为模式是 "xhtml+xml" 但实际 subtype 是 "xhtml"
        assert!(
            !is_mime_compressible(&xhtml),
            "当前实现不匹配 application/xhtml+xml"
        );

        // 同样的问题
        let rss: mime::Mime = "application/rss+xml".parse().unwrap();
        assert!(
            !is_mime_compressible(&rss),
            "当前实现不匹配 application/rss+xml"
        );

        let svg_app: mime::Mime = "application/svg+xml".parse().unwrap();
        assert!(
            !is_mime_compressible(&svg_app),
            "当前实现不匹配 application/svg+xml"
        );
    }

    #[test]
    fn test_is_mime_compressible_image_svg() {
        // 测试 IMAGE 类型
        // image/svg+xml 解析后 subtype 是 "svg"(不是 "svg+xml")
        let svg: mime::Mime = "image/svg+xml".parse().unwrap();
        assert_eq!(svg.type_(), mime::IMAGE);
        assert_eq!(svg.subtype().as_str(), "svg");
        // 当前实现不会匹配,因为模式是 "svg+xml" 但实际 subtype 是 "svg"
        assert!(!is_mime_compressible(&svg), "当前实现不匹配 image/svg+xml");

        // IMAGE_SVG 常量是 "image/svg"
        assert_eq!(mime::IMAGE_SVG.subtype().as_str(), "svg");
        assert!(
            !is_mime_compressible(&mime::IMAGE_SVG),
            "当前实现不匹配 image/svg"
        );
    }

    #[test]
    fn test_is_mime_compressible_non_compressible() {
        // 测试不可压缩的类型
        assert!(!is_mime_compressible(&mime::IMAGE_PNG));
        assert!(!is_mime_compressible(&mime::IMAGE_JPEG));
        assert!(!is_mime_compressible(&"video/mp4".parse().unwrap()));
        assert!(!is_mime_compressible(&"audio/mp3".parse().unwrap()));
        assert!(!is_mime_compressible(&mime::APPLICATION_OCTET_STREAM));
    }

    // ==================== parse_accept_encoding 测试 ====================

    #[test]
    fn test_parse_accept_encoding_brotli() {
        // 测试 Brotli 编码
        assert!(parse_accept_encoding("br").is_some());
        assert!(matches!(
            parse_accept_encoding("br"),
            Some(Compression::Brotli)
        ));
    }

    #[test]
    fn test_parse_accept_encoding_gzip() {
        // 测试 Gzip 编码
        assert!(parse_accept_encoding("gzip").is_some());
        assert!(matches!(
            parse_accept_encoding("gzip"),
            Some(Compression::Gzip)
        ));
        assert!(matches!(
            parse_accept_encoding("x-gzip"),
            Some(Compression::Gzip)
        ));
    }

    #[test]
    fn test_parse_accept_encoding_wildcard() {
        // 测试通配符
        assert!(parse_accept_encoding("*").is_some());
        assert!(matches!(
            parse_accept_encoding("*"),
            Some(Compression::Gzip)
        ));
    }

    #[test]
    fn test_parse_accept_encoding_multiple() {
        // 测试多个编码(优先级)
        assert!(matches!(
            parse_accept_encoding("br, gzip"),
            Some(Compression::Brotli)
        ));
        assert!(matches!(
            parse_accept_encoding("gzip, br"),
            Some(Compression::Brotli)
        ));
    }

    #[test]
    fn test_parse_accept_encoding_with_quality() {
        // 测试质量值
        // br 质量为 0,应该被跳过,选择 gzip
        assert!(parse_accept_encoding("br;q=0, gzip").is_some());
        assert!(matches!(
            parse_accept_encoding("br;q=0, gzip"),
            Some(Compression::Gzip)
        ));

        // 质量值非 0,即使 gzip 质量更高,也会优先选择 br(br 优先级高于 gzip)
        // 注意:函数不比较质量值,只跳过 q=0 的编码
        assert!(matches!(
            parse_accept_encoding("br;q=0.5, gzip;q=0.8"),
            Some(Compression::Brotli)
        ));

        // br 质量为 0,gzip 质量为 0,都不被选择
        assert!(parse_accept_encoding("br;q=0, gzip;q=0").is_none());
    }

    #[test]
    fn test_parse_accept_encoding_invalid() {
        // 测试无效的编码
        assert!(parse_accept_encoding("").is_none());
        assert!(parse_accept_encoding("identity").is_none());
        assert!(parse_accept_encoding("deflate").is_none());
    }

    #[test]
    fn test_parse_accept_encoding_whitespace() {
        // 测试空格处理
        assert!(parse_accept_encoding("br, gzip").is_some());
        assert!(parse_accept_encoding(" br , gzip ").is_some());
    }

    #[test]
    fn test_parse_accept_encoding_priority() {
        // 测试优先级:br > gzip > *
        // 当多个编码都有相同质量时,优先选择靠前的
        assert!(matches!(
            parse_accept_encoding("gzip, br"),
            Some(Compression::Brotli)
        ));
    }

    // ==================== negotiate 测试 ====================

    #[test]
    fn test_negotiate_compression_disabled() {
        // 测试压缩功能被禁用
        let req = Request::default();
        let options = StaticOptions {
            enable_compression: false,
            ..Default::default()
        };

        assert!(negotiate(&options, &req, Some(&mime::TEXT_PLAIN)).is_none());
    }

    #[test]
    fn test_negotiate_no_content_type() {
        // 测试无 Content-Type
        let req = Request::default();
        let options = StaticOptions {
            enable_compression: true,
            ..Default::default()
        };

        assert!(negotiate(&options, &req, None).is_none());
    }

    #[test]
    fn test_negotiate_uncompressible_mime() {
        // 测试不可压缩的 MIME 类型
        let mut req = Request::default();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, HeaderValue::from_static("br"));
        let options = StaticOptions {
            enable_compression: true,
            ..Default::default()
        };

        assert!(negotiate(&options, &req, Some(&mime::IMAGE_PNG)).is_none());
    }

    #[test]
    fn test_negotiate_no_accept_encoding() {
        // 测试没有 Accept-Encoding 头
        let req = Request::default();
        let options = StaticOptions {
            enable_compression: true,
            ..Default::default()
        };

        assert!(negotiate(&options, &req, Some(&mime::TEXT_PLAIN)).is_none());
    }

    #[test]
    fn test_negotiate_brotli() {
        // 测试 Brotli 协商
        let mut req = Request::default();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, HeaderValue::from_static("br"));
        let options = StaticOptions {
            enable_compression: true,
            ..Default::default()
        };

        assert!(matches!(
            negotiate(&options, &req, Some(&mime::TEXT_PLAIN)),
            Some(Compression::Brotli)
        ));
    }

    #[test]
    fn test_negotiate_gzip() {
        // 测试 Gzip 协商
        let mut req = Request::default();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, HeaderValue::from_static("gzip"));
        let options = StaticOptions {
            enable_compression: true,
            ..Default::default()
        };

        assert!(matches!(
            negotiate(&options, &req, Some(&mime::TEXT_PLAIN)),
            Some(Compression::Gzip)
        ));
    }

    #[test]
    fn test_negotiate_invalid_accept_encoding() {
        // 测试无效的 Accept-Encoding 头
        let mut req = Request::default();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, HeaderValue::from_static("invalid"));
        let options = StaticOptions {
            enable_compression: true,
            ..Default::default()
        };

        assert!(negotiate(&options, &req, Some(&mime::TEXT_PLAIN)).is_none());
    }

    #[test]
    fn test_negotiate_multiple_text_types() {
        // 测试不同的可压缩文本类型
        let mut req = Request::default();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, HeaderValue::from_static("br, gzip"));
        let options = StaticOptions {
            enable_compression: true,
            ..Default::default()
        };

        assert!(negotiate(&options, &req, Some(&mime::TEXT_HTML)).is_some());
        assert!(negotiate(&options, &req, Some(&mime::APPLICATION_JSON)).is_some());
        assert!(negotiate(&options, &req, Some(&mime::TEXT_CSS)).is_some());
    }

    // ==================== apply_headers 测试 ====================

    #[test]
    fn test_apply_headers_brotli() {
        // 测试应用 Brotli 压缩头
        let mut res = Response::empty();

        apply_headers(&mut res, &Compression::Brotli);

        assert_eq!(res.headers().get(CONTENT_ENCODING).unwrap(), "br");
        assert_eq!(res.headers().get(VARY).unwrap(), "Accept-Encoding");
    }

    #[test]
    fn test_apply_headers_gzip() {
        // 测试应用 Gzip 压缩头
        let mut res = Response::empty();

        apply_headers(&mut res, &Compression::Gzip);

        assert_eq!(res.headers().get(CONTENT_ENCODING).unwrap(), "gzip");
        assert_eq!(res.headers().get(VARY).unwrap(), "Accept-Encoding");
    }

    #[test]
    fn test_apply_headers_preserves_other_headers() {
        // 测试应用压缩头时保留其他头
        let mut res = Response::empty();
        res.headers_mut()
            .insert("custom-header", "value".parse().unwrap());

        apply_headers(&mut res, &Compression::Brotli);

        assert_eq!(res.headers().get("custom-header").unwrap(), "value");
    }
}