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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use crate::{Handler, MiddleWareHandler, Next, Request, Response, Result};
use async_trait::async_trait;
use http::header::{ACCEPT_ENCODING, CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TYPE, VARY};

use async_compression::futures::bufread::{BrotliEncoder, GzipEncoder};
use bytes::Bytes;
use futures::io::{AsyncRead, AsyncReadExt, BufReader};
use futures_util::stream::{self, BoxStream};
use futures_util::{StreamExt, TryStreamExt};

use crate::core::res_body::stream_body;

/// 压缩算法
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Algorithm {
    Brotli,
    Gzip,
}

/// Compression 中间件
///
/// 根据客户端 `Accept-Encoding` 头自动压缩响应体(gzip / brotli)。
///
/// # 行为
///
/// 1. 解析请求的 `Accept-Encoding` 头,协商压缩算法(优先 brotli > gzip)
/// 2. 调用下游 handler 获取响应
/// 3. 检查响应 `Content-Type` 是否为可压缩类型(text/*、application/json 等)
/// 4. 跳过已设置 `Content-Encoding` 的响应(避免二次压缩)
/// 5. 将响应体通过流式压缩编码器包装,设置 `Content-Encoding` 和 `Vary` 头
///
/// # 示例
///
/// ```rust
/// use silent::prelude::*;
/// use silent::middlewares::Compression;
///
/// let route = Route::new("/")
///     .hook(Compression::new())
///     .get(|_req: Request| async { Ok("hello") });
/// ```
///
/// 仅启用 gzip:
///
/// ```rust
/// use silent::prelude::*;
/// use silent::middlewares::Compression;
///
/// let route = Route::new("/")
///     .hook(Compression::gzip_only())
///     .get(|_req: Request| async { Ok("hello") });
/// ```
#[derive(Clone)]
pub struct Compression {
    enable_brotli: bool,
    enable_gzip: bool,
    /// 最小压缩阈值(字节),小于此大小的响应不压缩
    min_size: usize,
}

impl Default for Compression {
    fn default() -> Self {
        Self::new()
    }
}

impl Compression {
    /// 创建默认中间件,同时启用 brotli 和 gzip。
    pub fn new() -> Self {
        Self {
            enable_brotli: true,
            enable_gzip: true,
            min_size: 128,
        }
    }

    /// 仅启用 gzip 压缩。
    pub fn gzip_only() -> Self {
        Self {
            enable_brotli: false,
            enable_gzip: true,
            min_size: 128,
        }
    }

    /// 仅启用 brotli 压缩。
    pub fn brotli_only() -> Self {
        Self {
            enable_brotli: true,
            enable_gzip: false,
            min_size: 128,
        }
    }

    /// 设置最小压缩阈值(字节)。
    pub fn min_size(mut self, size: usize) -> Self {
        self.min_size = size;
        self
    }

    /// 根据 Accept-Encoding 协商压缩算法
    fn negotiate(&self, accept: &str) -> Option<Algorithm> {
        let mut brotli_ok = false;
        let mut gzip_ok = false;

        for item in accept.split(',') {
            let item = item.trim();
            let mut parts = item.split(';');
            let encoding = parts.next().map(str::trim).unwrap_or("");

            let mut quality = 1.0_f32;
            for param in parts {
                let mut kv = param.splitn(2, '=');
                if kv.next().map(str::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" if self.enable_brotli => brotli_ok = true,
                "gzip" | "x-gzip" if self.enable_gzip => gzip_ok = true,
                "*" if self.enable_brotli => brotli_ok = true,
                "*" if self.enable_gzip => gzip_ok = true,
                _ => {}
            }
        }

        if brotli_ok {
            Some(Algorithm::Brotli)
        } else if gzip_ok {
            Some(Algorithm::Gzip)
        } else {
            None
        }
    }
}

/// 判断 Content-Type 是否适合压缩
fn is_compressible(content_type: &str) -> bool {
    let ct = content_type.to_ascii_lowercase();
    // 提取 MIME 主类型/子类型(忽略参数)
    let mime_part = ct.split(';').next().unwrap_or("").trim();

    if mime_part.starts_with("text/") {
        return true;
    }

    matches!(
        mime_part,
        "application/json"
            | "application/xml"
            | "application/javascript"
            | "application/ecmascript"
            | "application/x-javascript"
            | "application/xhtml+xml"
            | "application/rss+xml"
            | "application/svg+xml"
            | "image/svg+xml"
    )
}

/// 将 AsyncRead 转换为 BoxStream<Result<Bytes, std::io::Error>>
fn to_stream<R>(reader: R) -> BoxStream<'static, std::result::Result<Bytes, std::io::Error>>
where
    R: AsyncRead + Unpin + Send + 'static,
{
    const CHUNK_SIZE: usize = 16 * 1024;
    let buf = vec![0u8; CHUNK_SIZE];
    stream::try_unfold((reader, buf), |(mut reader, mut buf)| async move {
        let n = reader.read(&mut buf).await?;
        if n == 0 {
            Ok(None)
        } else {
            let bytes = Bytes::copy_from_slice(&buf[..n]);
            Ok(Some((bytes, (reader, buf))))
        }
    })
    .boxed()
}

#[async_trait]
impl MiddleWareHandler for Compression {
    async fn handle(&self, req: Request, next: &Next) -> Result<Response> {
        // 提取 Accept-Encoding 并协商算法
        let algorithm = req
            .headers()
            .get(ACCEPT_ENCODING)
            .and_then(|v| v.to_str().ok())
            .and_then(|accept| self.negotiate(accept));

        let mut res = next.call(req).await?;

        let algorithm = match algorithm {
            Some(a) => a,
            None => return Ok(res),
        };

        // 跳过已压缩的响应
        if res.headers().contains_key(CONTENT_ENCODING) {
            return Ok(res);
        }

        // 检查 Content-Type 是否可压缩
        let compressible = res
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|v| v.to_str().ok())
            .map(is_compressible)
            .unwrap_or(false);

        if !compressible {
            return Ok(res);
        }

        // 检查最小大小阈值(仅对已知大小的响应体生效)
        if self.min_size > 0 {
            use http_body::Body;
            let hint = res.body.size_hint();
            if let Some(upper) = hint.upper() {
                if (upper as usize) < self.min_size {
                    return Ok(res);
                }
            }
        }

        // 取出响应体,转换为压缩流
        let body = res.take_body();
        let body_stream = body.map(|result| result.map_err(std::io::Error::other));
        let reader = body_stream.into_async_read();

        let compressed_stream = match algorithm {
            Algorithm::Brotli => {
                let encoder = BrotliEncoder::new(BufReader::new(reader));
                to_stream(encoder)
            }
            Algorithm::Gzip => {
                let encoder = GzipEncoder::new(BufReader::new(reader));
                to_stream(encoder)
            }
        };

        let encoding = match algorithm {
            Algorithm::Brotli => "br",
            Algorithm::Gzip => "gzip",
        };
        res.headers_mut()
            .insert(CONTENT_ENCODING, encoding.parse().unwrap());
        res.headers_mut()
            .insert(VARY, "Accept-Encoding".parse().unwrap());
        // 压缩后大小未知,移除 Content-Length
        res.headers_mut().remove(CONTENT_LENGTH);
        res.set_body(stream_body(compressed_stream));

        Ok(res)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::res_body::ResBody;

    // ==================== 构造函数测试 ====================

    #[test]
    fn test_compression_new() {
        let mid = Compression::new();
        assert!(mid.enable_brotli);
        assert!(mid.enable_gzip);
        assert_eq!(mid.min_size, 128);
    }

    #[test]
    fn test_compression_default() {
        let mid = Compression::default();
        assert!(mid.enable_brotli);
        assert!(mid.enable_gzip);
    }

    #[test]
    fn test_compression_gzip_only() {
        let mid = Compression::gzip_only();
        assert!(!mid.enable_brotli);
        assert!(mid.enable_gzip);
    }

    #[test]
    fn test_compression_brotli_only() {
        let mid = Compression::brotli_only();
        assert!(mid.enable_brotli);
        assert!(!mid.enable_gzip);
    }

    #[test]
    fn test_compression_min_size() {
        let mid = Compression::new().min_size(1024);
        assert_eq!(mid.min_size, 1024);
    }

    #[test]
    fn test_compression_clone() {
        let mid1 = Compression::new();
        let mid2 = mid1.clone();
        assert_eq!(mid1.enable_brotli, mid2.enable_brotli);
        assert_eq!(mid1.enable_gzip, mid2.enable_gzip);
        assert_eq!(mid1.min_size, mid2.min_size);
    }

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

    #[test]
    fn test_negotiate_brotli() {
        let mid = Compression::new();
        assert_eq!(mid.negotiate("br"), Some(Algorithm::Brotli));
    }

    #[test]
    fn test_negotiate_gzip() {
        let mid = Compression::new();
        assert_eq!(mid.negotiate("gzip"), Some(Algorithm::Gzip));
        assert_eq!(mid.negotiate("x-gzip"), Some(Algorithm::Gzip));
    }

    #[test]
    fn test_negotiate_prefers_brotli() {
        let mid = Compression::new();
        assert_eq!(mid.negotiate("gzip, br"), Some(Algorithm::Brotli));
        assert_eq!(mid.negotiate("br, gzip"), Some(Algorithm::Brotli));
    }

    #[test]
    fn test_negotiate_wildcard() {
        let mid = Compression::new();
        assert_eq!(mid.negotiate("*"), Some(Algorithm::Brotli));
    }

    #[test]
    fn test_negotiate_wildcard_gzip_only() {
        let mid = Compression::gzip_only();
        assert_eq!(mid.negotiate("*"), Some(Algorithm::Gzip));
    }

    #[test]
    fn test_negotiate_zero_quality() {
        let mid = Compression::new();
        assert_eq!(mid.negotiate("br;q=0, gzip"), Some(Algorithm::Gzip));
        assert_eq!(mid.negotiate("br;q=0, gzip;q=0"), None);
    }

    #[test]
    fn test_negotiate_no_match() {
        let mid = Compression::new();
        assert_eq!(mid.negotiate("identity"), None);
        assert_eq!(mid.negotiate("deflate"), None);
        assert_eq!(mid.negotiate(""), None);
    }

    #[test]
    fn test_negotiate_gzip_only_rejects_br() {
        let mid = Compression::gzip_only();
        assert_eq!(mid.negotiate("br"), None);
        assert_eq!(mid.negotiate("gzip"), Some(Algorithm::Gzip));
    }

    #[test]
    fn test_negotiate_brotli_only_rejects_gzip() {
        let mid = Compression::brotli_only();
        assert_eq!(mid.negotiate("gzip"), None);
        assert_eq!(mid.negotiate("br"), Some(Algorithm::Brotli));
    }

    // ==================== is_compressible 测试 ====================

    #[test]
    fn test_is_compressible_text() {
        assert!(is_compressible("text/plain"));
        assert!(is_compressible("text/html"));
        assert!(is_compressible("text/css"));
        assert!(is_compressible("text/javascript"));
        assert!(is_compressible("text/html; charset=utf-8"));
    }

    #[test]
    fn test_is_compressible_application() {
        assert!(is_compressible("application/json"));
        assert!(is_compressible("application/xml"));
        assert!(is_compressible("application/javascript"));
        assert!(is_compressible("application/xhtml+xml"));
        assert!(is_compressible("application/svg+xml"));
    }

    #[test]
    fn test_is_compressible_image_svg() {
        assert!(is_compressible("image/svg+xml"));
    }

    #[test]
    fn test_not_compressible() {
        assert!(!is_compressible("image/png"));
        assert!(!is_compressible("image/jpeg"));
        assert!(!is_compressible("video/mp4"));
        assert!(!is_compressible("application/octet-stream"));
        assert!(!is_compressible("audio/mpeg"));
    }

    // ==================== 集成测试 ====================

    #[cfg(feature = "server")]
    #[tokio::test]
    async fn test_compression_gzip_response() {
        use crate::route::Route;

        let mid = Compression::new().min_size(0);
        let route = Route::new("/").hook(mid).get(|_req: Request| async {
            let mut resp = Response::empty();
            resp.headers_mut()
                .insert(CONTENT_TYPE, "text/plain".parse().unwrap());
            resp.set_body(ResBody::Once(Bytes::from("hello world")));
            Ok(resp)
        });
        let route = Route::new_root().append(route);

        let mut req = Request::empty();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, "gzip".parse().unwrap());

        let res: Result<Response> = crate::Handler::call(&route, req).await;
        assert!(res.is_ok());
        let resp = res.unwrap();
        assert_eq!(
            resp.headers()
                .get(CONTENT_ENCODING)
                .unwrap()
                .to_str()
                .unwrap(),
            "gzip"
        );
        assert_eq!(
            resp.headers().get(VARY).unwrap().to_str().unwrap(),
            "Accept-Encoding"
        );
        assert!(!resp.headers().contains_key(CONTENT_LENGTH));
    }

    #[cfg(feature = "server")]
    #[tokio::test]
    async fn test_compression_brotli_response() {
        use crate::route::Route;

        let mid = Compression::new().min_size(0);
        let route = Route::new("/").hook(mid).get(|_req: Request| async {
            let mut resp = Response::empty();
            resp.headers_mut()
                .insert(CONTENT_TYPE, "application/json".parse().unwrap());
            resp.set_body(ResBody::Once(Bytes::from("{\"key\":\"value\"}")));
            Ok(resp)
        });
        let route = Route::new_root().append(route);

        let mut req = Request::empty();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, "br, gzip".parse().unwrap());

        let res: Result<Response> = crate::Handler::call(&route, req).await;
        assert!(res.is_ok());
        let resp = res.unwrap();
        assert_eq!(
            resp.headers()
                .get(CONTENT_ENCODING)
                .unwrap()
                .to_str()
                .unwrap(),
            "br"
        );
    }

    #[cfg(feature = "server")]
    #[tokio::test]
    async fn test_compression_skip_non_compressible() {
        use crate::route::Route;

        let mid = Compression::new().min_size(0);
        let route = Route::new("/").hook(mid).get(|_req: Request| async {
            let mut resp = Response::empty();
            resp.headers_mut()
                .insert(CONTENT_TYPE, "image/png".parse().unwrap());
            resp.set_body(ResBody::Once(Bytes::from(vec![0u8; 100])));
            Ok(resp)
        });
        let route = Route::new_root().append(route);

        let mut req = Request::empty();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, "gzip".parse().unwrap());

        let res: Result<Response> = crate::Handler::call(&route, req).await;
        assert!(res.is_ok());
        let resp = res.unwrap();
        // 不应压缩图片
        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
    }

    #[cfg(feature = "server")]
    #[tokio::test]
    async fn test_compression_skip_already_encoded() {
        use crate::route::Route;

        let mid = Compression::new().min_size(0);
        let route = Route::new("/").hook(mid).get(|_req: Request| async {
            let mut resp = Response::empty();
            resp.headers_mut()
                .insert(CONTENT_TYPE, "text/plain".parse().unwrap());
            resp.headers_mut()
                .insert(CONTENT_ENCODING, "br".parse().unwrap());
            resp.set_body(ResBody::Once(Bytes::from("already compressed")));
            Ok(resp)
        });
        let route = Route::new_root().append(route);

        let mut req = Request::empty();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, "gzip".parse().unwrap());

        let res: Result<Response> = crate::Handler::call(&route, req).await;
        assert!(res.is_ok());
        let resp = res.unwrap();
        // 保持原有的 Content-Encoding
        assert_eq!(
            resp.headers()
                .get(CONTENT_ENCODING)
                .unwrap()
                .to_str()
                .unwrap(),
            "br"
        );
    }

    #[cfg(feature = "server")]
    #[tokio::test]
    async fn test_compression_skip_no_accept_encoding() {
        use crate::route::Route;

        let mid = Compression::new().min_size(0);
        let route = Route::new("/").hook(mid).get(|_req: Request| async {
            let mut resp = Response::empty();
            resp.headers_mut()
                .insert(CONTENT_TYPE, "text/plain".parse().unwrap());
            resp.set_body(ResBody::Once(Bytes::from("no compression")));
            Ok(resp)
        });
        let route = Route::new_root().append(route);

        let req = Request::empty();
        let res: Result<Response> = crate::Handler::call(&route, req).await;
        assert!(res.is_ok());
        let resp = res.unwrap();
        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
    }

    #[cfg(feature = "server")]
    #[tokio::test]
    async fn test_compression_skip_small_body() {
        use crate::route::Route;

        // min_size 默认 128,10 字节应跳过
        let mid = Compression::new();
        let route = Route::new("/").hook(mid).get(|_req: Request| async {
            let mut resp = Response::empty();
            resp.headers_mut()
                .insert(CONTENT_TYPE, "text/plain".parse().unwrap());
            resp.set_body(ResBody::Once(Bytes::from("small")));
            Ok(resp)
        });
        let route = Route::new_root().append(route);

        let mut req = Request::empty();
        req.headers_mut()
            .insert(ACCEPT_ENCODING, "gzip".parse().unwrap());

        let res: Result<Response> = crate::Handler::call(&route, req).await;
        assert!(res.is_ok());
        let resp = res.unwrap();
        // 小于 min_size,不压缩
        assert!(resp.headers().get(CONTENT_ENCODING).is_none());
    }
}