1use std::{
3 collections::VecDeque, fmt, future::Future, io, pin::Pin, rc::Rc, task::Context, task::Poll,
4};
5
6use flate2::{Compress, Compression, Crc, FlushCompress, Status};
7use zstd::zstd_safe::{CCtx, CParameter, InBuffer, OutBuffer, zstd_sys::ZSTD_EndDirective};
8
9use crate::http::body::{Body, BodySize, MessageBody, ResponseBody};
10use crate::http::header::{CONTENT_ENCODING, ContentEncoding, HeaderValue};
11use crate::http::{ResponseHead, StatusCode};
12use crate::rt::BlockingResult;
13use crate::util::{BufMut, BytePageSize, Bytes, BytesMut, dyn_rc_err};
14
15use super::{Spare, offload, zstd_error};
16
17const MIN_SIZE: u64 = 1024;
21
22const ZSTD_WINDOW_LOG: u32 = 19;
27
28const ZSTD_HASH_LOG: u32 = 15;
33const ZSTD_CHAIN_LOG: u32 = 15;
34
35pub struct Encoder<B> {
39 eof: bool,
40 body: EncoderBody<B>,
41 pending: Bytes,
43 inner: Option<ContentEncoder>,
44 fut: Option<BlockingResult<Result<ContentEncoder, io::Error>>>,
45}
46
47impl<B: MessageBody> Encoder<B> {
48 pub fn response(
57 encoding: ContentEncoding,
58 head: &mut ResponseHead,
59 body: ResponseBody<B>,
60 ) -> ResponseBody<B> {
61 let size = match body.size() {
62 BodySize::None | BodySize::Empty => return body,
63 BodySize::Sized(size) if size < MIN_SIZE => return body,
64 BodySize::Sized(size) => Some(size),
65 BodySize::Stream => None,
66 };
67 if head.headers().contains_key(&CONTENT_ENCODING)
68 || head.status == StatusCode::SWITCHING_PROTOCOLS
69 || head.status == StatusCode::NO_CONTENT
70 {
71 return body;
72 }
73 let Some(encoder) = ContentEncoder::new(encoding, size) else {
74 return body;
75 };
76
77 let body = match body {
78 ResponseBody::Other(b) => match b {
79 Body::None | Body::Empty => unreachable!(),
80 Body::Bytes(buf) => EncoderBody::Bytes(buf),
81 Body::Message(stream) => EncoderBody::BoxedStream(stream),
82 },
83 ResponseBody::Body(stream) => EncoderBody::Stream(stream),
84 };
85 head.headers_mut().insert(
86 CONTENT_ENCODING,
87 HeaderValue::from_static(encoding.as_str()),
88 );
89 head.no_chunking(false);
90 ResponseBody::Other(Body::from_message(Encoder {
91 body,
92 eof: false,
93 pending: Bytes::new(),
94 fut: None,
95 inner: Some(encoder),
96 }))
97 }
98}
99
100impl Encoder<()> {
101 pub(crate) fn can_encode(encoding: ContentEncoding) -> bool {
103 matches!(
104 encoding,
105 ContentEncoding::Deflate | ContentEncoding::Gzip | ContentEncoding::Zstd
106 )
107 }
108}
109
110impl<B: fmt::Debug> fmt::Debug for Encoder<B> {
111 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112 f.debug_struct("Encoder")
113 .field("eof", &self.eof)
114 .field("body", &self.body)
115 .field("pending", &self.pending.len())
116 .field("encoder", &self.inner)
117 .field("fut", &self.fut.as_ref().map(|_| "JoinHandle(_)"))
118 .finish()
119 }
120}
121
122enum EncoderBody<B> {
123 Bytes(Bytes),
124 Stream(B),
125 BoxedStream(Box<dyn MessageBody>),
126}
127
128impl<B> fmt::Debug for EncoderBody<B> {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 match self {
131 EncoderBody::Bytes(b) => write!(f, "EncoderBody::Bytes({b:?})"),
132 EncoderBody::Stream(_) => write!(f, "EncoderBody::Stream(_)"),
133 EncoderBody::BoxedStream(_) => write!(f, "EncoderBody::BoxedStream(_)"),
134 }
135 }
136}
137
138impl<B: MessageBody> MessageBody for Encoder<B> {
139 fn size(&self) -> BodySize {
140 BodySize::Stream
141 }
142
143 fn poll_next_chunk(
144 &mut self,
145 cx: &mut Context<'_>,
146 ) -> Poll<Option<Result<Bytes, Rc<dyn std::error::Error>>>> {
147 let result = self.poll_encoded(cx);
148 if let Poll::Ready(Some(Err(_))) = result {
149 self.eof = true;
151 self.inner = None;
152 self.fut = None;
153 self.pending = Bytes::new();
154 }
155 result
156 }
157}
158
159impl<B: MessageBody> Encoder<B> {
160 fn poll_encoded(
161 &mut self,
162 cx: &mut Context<'_>,
163 ) -> Poll<Option<Result<Bytes, Rc<dyn std::error::Error>>>> {
164 loop {
165 if let Some(chunk) = self.inner.as_mut().and_then(ContentEncoder::take) {
166 return Poll::Ready(Some(Ok(chunk)));
167 }
168
169 if self.eof {
170 self.inner = None;
171 return Poll::Ready(None);
172 }
173
174 if let Some(ref mut fut) = self.fut {
175 let encoder = match Pin::new(fut).poll(cx) {
176 Poll::Ready(Ok(Ok(item))) => item,
177 Poll::Ready(Ok(Err(e))) => return Poll::Ready(Some(Err(Rc::new(e)))),
178 Poll::Ready(Err(_)) => {
179 return Poll::Ready(Some(Err(Rc::new(io::Error::new(
180 io::ErrorKind::Interrupted,
181 "Canceled",
182 )))));
183 }
184 Poll::Pending => return Poll::Pending,
185 };
186 self.inner = Some(encoder);
187 self.fut = None;
188 continue;
189 }
190
191 if !self.pending.is_empty() {
192 let chunk = std::mem::take(&mut self.pending);
193 self.encode(chunk)?;
194 continue;
195 }
196
197 let result = match self.body {
198 EncoderBody::Bytes(ref mut b) => {
199 if b.is_empty() {
200 Poll::Ready(None)
201 } else {
202 Poll::Ready(Some(Ok(std::mem::take(b))))
203 }
204 }
205 EncoderBody::Stream(ref mut b) => b.poll_next_chunk(cx),
206 EncoderBody::BoxedStream(ref mut b) => b.poll_next_chunk(cx),
207 };
208 match result {
209 Poll::Ready(Some(Ok(chunk))) => self.encode(chunk)?,
210 Poll::Ready(None) => {
211 self.eof = true;
212 if let Some(encoder) = self.inner.as_mut() {
213 encoder.finish().map_err(dyn_rc_err)?;
214 }
215 }
216 Poll::Pending => {
219 if let Some(encoder) = self.inner.as_mut() {
220 encoder.flush().map_err(dyn_rc_err)?;
221 if let Some(chunk) = encoder.take() {
222 return Poll::Ready(Some(Ok(chunk)));
223 }
224 }
225 return Poll::Pending;
226 }
227 Poll::Ready(Some(Err(e))) => return Poll::Ready(Some(Err(e))),
228 }
229 }
230 }
231}
232
233impl<B> Encoder<B> {
234 fn encode(&mut self, mut chunk: Bytes) -> Result<(), Rc<dyn std::error::Error>> {
239 let Some(mut encoder) = self.inner.take() else {
240 return Ok(());
241 };
242 if chunk.len() < encoder.limit() {
243 encoder.write(&chunk).map_err(dyn_rc_err)?;
244 self.inner = Some(encoder);
245 } else {
246 let part = chunk.split_to(chunk.len().min(encoder.task_size()));
247 self.pending = chunk;
248 self.fut = Some(offload(move || {
249 encoder.write(&part)?;
250 Ok(encoder)
251 }));
252 }
253 Ok(())
254 }
255}
256
257const GZIP_HEADER: [u8; 10] = [0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 4, 255];
260
261struct ContentEncoder {
263 codec: Codec,
264 buf: BytesMut,
265 chunks: VecDeque<Bytes>,
266 unflushed: bool,
268}
269
270#[derive(Copy, Clone, PartialEq, Eq)]
271enum Op {
272 Write,
273 Flush,
275 Finish,
277}
278
279enum Codec {
280 Deflate(Compress),
281 Gzip(Compress, Crc),
283 Zstd(CCtx<'static>),
284 Done,
286}
287
288impl ContentEncoder {
289 const fn limit(&self) -> usize {
294 match self.codec {
295 Codec::Deflate(_) | Codec::Gzip(..) => 16 * 1024,
296 Codec::Zstd(_) | Codec::Done => 128 * 1024,
297 }
298 }
299
300 const fn task_size(&self) -> usize {
302 match self.codec {
303 Codec::Deflate(_) | Codec::Gzip(..) => 256 * 1024,
304 Codec::Zstd(_) | Codec::Done => 384 * 1024,
305 }
306 }
307
308 fn new(encoding: ContentEncoding, size: Option<u64>) -> Option<Self> {
310 let mut buf = BytesMut::with_page_size(BytePageSize::Size32);
311 let codec = match encoding {
312 ContentEncoding::Deflate => Codec::Deflate(Compress::new(Compression::fast(), true)),
313 ContentEncoding::Gzip => {
314 buf.extend_from_slice(&GZIP_HEADER);
315 Codec::Gzip(Compress::new(Compression::fast(), false), Crc::new())
316 }
317 ContentEncoding::Zstd => {
319 let mut ctx = CCtx::try_create()?;
320 ctx.set_parameter(CParameter::CompressionLevel(0)).ok()?;
321 ctx.set_parameter(CParameter::WindowLog(ZSTD_WINDOW_LOG))
322 .ok()?;
323 ctx.set_parameter(CParameter::HashLog(ZSTD_HASH_LOG)).ok()?;
324 ctx.set_parameter(CParameter::ChainLog(ZSTD_CHAIN_LOG))
325 .ok()?;
326 ctx.set_pledged_src_size(size).ok()?;
327 Codec::Zstd(ctx)
328 }
329 _ => return None,
330 };
331 Some(ContentEncoder {
332 codec,
333 buf,
334 chunks: VecDeque::new(),
335 unflushed: false,
336 })
337 }
338
339 fn take(&mut self) -> Option<Bytes> {
341 self.chunks
342 .pop_front()
343 .or_else(|| (!self.buf.is_empty()).then(|| self.buf.take()))
344 }
345
346 fn reserve(&mut self) {
350 if self.buf.remaining_mut() == 0 {
351 if !self.buf.is_empty() {
352 self.chunks.push_back(self.buf.take());
353 }
354 self.buf.reserve_more();
355 }
356 }
357
358 fn compress(&mut self, data: &mut &[u8], op: Op) -> io::Result<bool> {
361 self.reserve();
362 match &mut self.codec {
363 Codec::Deflate(inner) | Codec::Gzip(inner, _) => {
364 let flush = match op {
365 Op::Write => FlushCompress::None,
366 Op::Flush => FlushCompress::Sync,
367 Op::Finish => FlushCompress::Finish,
368 };
369 let (total_in, total_out) = (inner.total_in(), inner.total_out());
370 let status = unsafe {
373 let spare = self.buf.chunk_mut().as_uninit_slice_mut();
374 inner
375 .compress_uninit(data, spare, flush)
376 .map_err(io::Error::other)?
377 };
378 let read = usize::try_from(inner.total_in() - total_in).unwrap();
379 let written = usize::try_from(inner.total_out() - total_out).unwrap();
380 unsafe { self.buf.advance_mut(written) };
382 *data = &data[read..];
383
384 if status == Status::StreamEnd {
385 Ok(true)
386 } else if read == 0 && written == 0 {
387 Err(io::ErrorKind::WriteZero.into())
388 } else {
389 Ok(op == Op::Flush && self.buf.remaining_mut() > 0)
391 }
392 }
393 Codec::Zstd(ctx) => {
394 let end = match op {
395 Op::Write => ZSTD_EndDirective::ZSTD_e_continue,
396 Op::Flush => ZSTD_EndDirective::ZSTD_e_flush,
397 Op::Finish => ZSTD_EndDirective::ZSTD_e_end,
398 };
399 let mut src = InBuffer::around(data);
400 let mut spare = Spare::new(&mut self.buf);
401 let mut dst = OutBuffer::around(&mut spare);
402 let left = ctx
404 .compress_stream2(&mut dst, &mut src, end)
405 .map_err(zstd_error)?;
406 let read = src.pos();
407 *data = &data[read..];
408 Ok(op != Op::Write && left == 0)
409 }
410 Codec::Done => Err(io::Error::other("the stream is finished")),
411 }
412 }
413
414 fn put(&mut self, mut data: &[u8]) {
416 while !data.is_empty() {
417 self.reserve();
418 let size = data.len().min(self.buf.remaining_mut());
419 self.buf.extend_from_slice(&data[..size]);
420 data = &data[size..];
421 }
422 }
423
424 fn finish(&mut self) -> io::Result<()> {
426 while !self.compress(&mut &[][..], Op::Finish)? {}
427 if let Codec::Gzip(_, crc) = &self.codec {
428 let (sum, amount) = (crc.sum(), crc.amount());
429 self.put(&sum.to_le_bytes());
430 self.put(&amount.to_le_bytes());
431 }
432 self.codec = Codec::Done;
434 Ok(())
435 }
436
437 fn flush(&mut self) -> io::Result<()> {
441 if self.unflushed {
442 self.unflushed = false;
443 while !self.compress(&mut &[][..], Op::Flush)? {}
444 }
445 Ok(())
446 }
447
448 fn write(&mut self, mut data: &[u8]) -> io::Result<()> {
449 self.unflushed |= !data.is_empty();
450 if let Codec::Gzip(_, crc) = &mut self.codec {
451 crc.update(data);
452 }
453 while !data.is_empty() {
454 self.compress(&mut data, Op::Write)
455 .inspect_err(|err| log::trace!("Failed to encode to {self:?}: {err}"))?;
456 }
457 Ok(())
458 }
459}
460
461impl fmt::Debug for ContentEncoder {
462 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
463 match self.codec {
464 Codec::Deflate(_) => write!(f, "ContentEncoder::Deflate"),
465 Codec::Gzip(..) => write!(f, "ContentEncoder::Gzip"),
466 Codec::Zstd(_) => write!(f, "ContentEncoder::Zstd"),
467 Codec::Done => write!(f, "ContentEncoder::Done"),
468 }
469 }
470}
471
472#[cfg(test)]
473mod tests {
474 use std::future::poll_fn;
475
476 use super::*;
477 use crate::http::body::BodyStream;
478 use crate::rt::spawn_blocking;
479
480 #[crate::rt_test]
485 async fn encoder_is_fused_after_error() {
486 let mut enc = Encoder::<Body> {
487 eof: false,
488 pending: Bytes::new(),
489 body: EncoderBody::Bytes(Bytes::from_static(b"raw data")),
490 inner: None,
491 fut: Some(spawn_blocking(|| Err(io::Error::other("encode failed")))),
492 };
493 assert_eq!(enc.size(), BodySize::Stream);
494
495 let res = poll_fn(|cx| enc.poll_next_chunk(cx)).await;
496 assert!(matches!(res, Some(Err(_))));
497 assert_eq!(enc.size(), BodySize::Stream);
498 assert!(poll_fn(|cx| enc.poll_next_chunk(cx)).await.is_none());
499 }
500
501 struct EndOnce(bool);
502
503 impl MessageBody for EndOnce {
504 fn size(&self) -> BodySize {
505 BodySize::Stream
506 }
507
508 fn poll_next_chunk(
509 &mut self,
510 _: &mut Context<'_>,
511 ) -> Poll<Option<Result<Bytes, Rc<dyn std::error::Error>>>> {
512 assert!(!self.0, "body polled after end of stream");
513 self.0 = true;
514 Poll::Ready(None)
515 }
516 }
517
518 #[crate::rt_test]
523 async fn encoder_is_fused_after_end_of_stream() {
524 let mut enc = Encoder::<EndOnce> {
525 eof: false,
526 pending: Bytes::new(),
527 body: EncoderBody::Stream(EndOnce(false)),
528 inner: None,
529 fut: None,
530 };
531 assert!(poll_fn(|cx| enc.poll_next_chunk(cx)).await.is_none());
532 assert!(poll_fn(|cx| enc.poll_next_chunk(cx)).await.is_none());
533 }
534
535 #[crate::rt_test]
541 async fn encoder_source_error() {
542 for encoding in [
543 ContentEncoding::Gzip,
544 ContentEncoding::Deflate,
545 ContentEncoding::Zstd,
546 ] {
547 for boxed in [false, true] {
548 let source = BodyStream::new(futures_util::stream::iter([
549 Err(io::Error::other("body failed")),
550 Ok(Bytes::from_static(b"must not be emitted")),
551 ]));
552 let body = if boxed {
553 ResponseBody::Other(source.into())
554 } else {
555 ResponseBody::Body(source)
556 };
557 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
558 let mut body = Encoder::response(encoding, &mut head, body);
559 loop {
560 let chunk = poll_fn(|cx| body.poll_next_chunk(cx))
561 .await
562 .expect("source error was lost");
563 if let Err(err) = chunk {
564 assert_eq!(err.to_string(), "body failed");
565 break;
566 }
567 }
568 assert!(poll_fn(|cx| body.poll_next_chunk(cx)).await.is_none());
569 }
570 }
571 }
572
573 async fn collect(body: &mut ResponseBody<Body>) -> Vec<u8> {
574 let mut buf = Vec::new();
575 while let Some(chunk) = poll_fn(|cx| body.poll_next_chunk(cx)).await {
576 buf.extend_from_slice(&chunk.unwrap());
577 }
578 buf
579 }
580
581 fn gunzip(data: &[u8]) -> Vec<u8> {
582 use std::io::Read;
583
584 let mut buf = Vec::new();
585 flate2::read::GzDecoder::new(data)
586 .read_to_end(&mut buf)
587 .unwrap();
588 buf
589 }
590
591 #[crate::rt_test]
597 async fn encoder_response_bodies() {
598 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
599 let body = Encoder::<Body>::response(ContentEncoding::Gzip, &mut head, Body::None.into());
600 assert!(matches!(body, ResponseBody::Other(Body::None)));
601 let body = Encoder::<Body>::response(ContentEncoding::Gzip, &mut head, Body::Empty.into());
602 assert!(matches!(body, ResponseBody::Other(Body::Empty)));
603
604 let body = Encoder::<Body>::response(
606 ContentEncoding::Identity,
607 &mut head,
608 Body::from("data").into(),
609 );
610 assert!(matches!(body, ResponseBody::Other(Body::Bytes(_))));
611 assert!(!head.headers().contains_key(CONTENT_ENCODING));
612
613 let data = "data".repeat(256);
615 let body = Encoder::<Body>::response(
616 ContentEncoding::Auto,
617 &mut head,
618 Body::from(data.clone()).into(),
619 );
620 assert!(matches!(body, ResponseBody::Other(Body::Bytes(_))));
621 assert!(!head.headers().contains_key(CONTENT_ENCODING));
622 for status in [StatusCode::SWITCHING_PROTOCOLS, StatusCode::NO_CONTENT] {
623 let mut head = ResponseHead::new(status, crate::http::Version::HTTP_11);
624 let body = Encoder::<Body>::response(
625 ContentEncoding::Gzip,
626 &mut head,
627 Body::from(data.clone()).into(),
628 );
629 assert!(matches!(body, ResponseBody::Other(Body::Bytes(_))));
630 assert!(!head.headers().contains_key(CONTENT_ENCODING));
631 }
632 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
633 head.headers_mut()
634 .insert(CONTENT_ENCODING, HeaderValue::from_static("br"));
635 let body =
636 Encoder::<Body>::response(ContentEncoding::Gzip, &mut head, Body::from(data).into());
637 assert!(matches!(body, ResponseBody::Other(Body::Bytes(_))));
638 assert_eq!(head.headers().get(CONTENT_ENCODING).unwrap(), "br");
639
640 let data = "data".repeat(256);
642 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
643 let inner = Body::from_message(Body::from(data.clone()));
644 let mut body = Encoder::<Body>::response(ContentEncoding::Gzip, &mut head, inner.into());
645 assert_eq!(head.headers().get(CONTENT_ENCODING).unwrap(), "gzip");
646 assert_eq!(gunzip(&collect(&mut body).await), data.as_bytes());
647
648 let typed = "typed".repeat(205);
650 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
651 let body = Encoder::<Body>::response(
652 ContentEncoding::Gzip,
653 &mut head,
654 ResponseBody::Body(Body::from(typed.clone())),
655 );
656 let ResponseBody::Other(Body::Message(mut msg)) = body else {
657 panic!("expected encoded body")
658 };
659 let mut buf = Vec::new();
660 while let Some(chunk) = poll_fn(|cx| msg.poll_next_chunk(cx)).await {
661 buf.extend_from_slice(&chunk.unwrap());
662 }
663 assert_eq!(gunzip(&buf), typed.as_bytes());
664 }
665
666 struct Chunks(Vec<Bytes>, BodySize);
667
668 impl MessageBody for Chunks {
669 fn size(&self) -> BodySize {
670 self.1
671 }
672
673 fn poll_next_chunk(
674 &mut self,
675 _: &mut Context<'_>,
676 ) -> Poll<Option<Result<Bytes, Rc<dyn std::error::Error>>>> {
677 Poll::Ready(self.0.pop().map(Ok))
678 }
679 }
680
681 #[crate::rt_test]
687 async fn encoder_skips_small_bodies() {
688 for encoding in [
689 ContentEncoding::Gzip,
690 ContentEncoding::Deflate,
691 ContentEncoding::Zstd,
692 ] {
693 let small = Bytes::from(vec![b'x'; 1023]);
694 let large = Bytes::from(vec![b'x'; 1024]);
695
696 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
697 let body =
698 Encoder::<Body>::response(encoding, &mut head, Body::from(small.clone()).into());
699 assert!(matches!(body, ResponseBody::Other(Body::Bytes(ref b)) if *b == small));
700 assert!(!head.headers().contains_key(CONTENT_ENCODING));
701
702 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
703 let stream = Chunks(vec![small.clone()], BodySize::Sized(1023));
704 let body = Encoder::response(encoding, &mut head, ResponseBody::Body(stream));
705 assert!(matches!(body, ResponseBody::Body(_)));
706 assert!(!head.headers().contains_key(CONTENT_ENCODING));
707
708 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
709 let mut body =
710 Encoder::<Body>::response(encoding, &mut head, Body::from(large.clone()).into());
711 assert_eq!(
712 head.headers().get(CONTENT_ENCODING).unwrap(),
713 encoding.as_str()
714 );
715 assert_eq!(decompress(encoding, &collect(&mut body).await), large);
716
717 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
719 let stream = Chunks(vec![Bytes::from_static(b"x")], BodySize::Stream);
720 let mut body =
721 Encoder::<Body>::response(encoding, &mut head, Body::from_message(stream).into());
722 assert_eq!(
723 head.headers().get(CONTENT_ENCODING).unwrap(),
724 encoding.as_str()
725 );
726 assert_eq!(decompress(encoding, &collect(&mut body).await), b"x");
727 }
728 }
729
730 fn zstd_content_size(data: &[u8]) -> Option<u64> {
731 zstd::zstd_safe::get_frame_content_size(data).unwrap()
732 }
733
734 #[crate::rt_test]
740 async fn encoder_zstd_known_size() {
741 let data = Bytes::from(vec![b'x'; 4096]);
742
743 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
745 let mut body = Encoder::<Body>::response(
746 ContentEncoding::Zstd,
747 &mut head,
748 Body::from(data.clone()).into(),
749 );
750 let frame = collect(&mut body).await;
751 assert_eq!(zstd_content_size(&frame), Some(4096));
752 assert_eq!(decompress(ContentEncoding::Zstd, &frame), data);
753
754 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
755 let chunks = vec![data.slice(2048..), data.slice(..2048)];
756 let stream = Body::from_message(Chunks(chunks, BodySize::Sized(4096)));
757 let mut body = Encoder::<Body>::response(ContentEncoding::Zstd, &mut head, stream.into());
758 let frame = collect(&mut body).await;
759 assert_eq!(zstd_content_size(&frame), Some(4096));
760 assert_eq!(decompress(ContentEncoding::Zstd, &frame), data);
761
762 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
764 let stream = Body::from_message(Chunks(vec![data.clone()], BodySize::Stream));
765 let mut body = Encoder::<Body>::response(ContentEncoding::Zstd, &mut head, stream.into());
766 let frame = collect(&mut body).await;
767 assert_eq!(zstd_content_size(&frame), None);
768 assert_eq!(decompress(ContentEncoding::Zstd, &frame), data);
769
770 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
772 let stream = Body::from_message(Chunks(vec![data.clone()], BodySize::Sized(2048)));
773 let mut body = Encoder::<Body>::response(ContentEncoding::Zstd, &mut head, stream.into());
774 assert!(matches!(
775 poll_fn(|cx| body.poll_next_chunk(cx)).await,
776 Some(Err(_))
777 ));
778 }
779
780 #[crate::rt_test]
786 async fn encoder_zstd_short_body() {
787 let source = Chunks(vec![Bytes::from(vec![b'x'; 4096])], BodySize::Sized(8192));
788 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
789 let body = Body::from_message(source);
790 let mut body = Encoder::<Body>::response(ContentEncoding::Zstd, &mut head, body.into());
791 loop {
792 let chunk = poll_fn(|cx| body.poll_next_chunk(cx))
793 .await
794 .expect("short body was accepted");
795 if chunk.is_err() {
796 break;
797 }
798 }
799 assert!(poll_fn(|cx| body.poll_next_chunk(cx)).await.is_none());
800 }
801
802 fn decompress(encoding: ContentEncoding, data: &[u8]) -> Vec<u8> {
803 use std::io::Read;
804
805 let mut buf = Vec::new();
806 match encoding {
807 ContentEncoding::Gzip => return gunzip(data),
808 ContentEncoding::Deflate => {
809 flate2::read::ZlibDecoder::new(data)
810 .read_to_end(&mut buf)
811 .unwrap();
812 }
813 ContentEncoding::Zstd => buf = zstd::decode_all(data).unwrap(),
814 _ => unreachable!(),
815 }
816 buf
817 }
818
819 #[crate::rt_test]
824 async fn encoder_offloads_large_chunks() {
825 for (encoding, limit) in [
826 (ContentEncoding::Gzip, 16 * 1024),
827 (ContentEncoding::Deflate, 16 * 1024),
828 (ContentEncoding::Zstd, 128 * 1024),
829 ] {
830 for (len, offloaded) in [(limit - 1, 0), (limit, 1)] {
831 let data: Vec<u8> = (0..len).map(|i: usize| (i % 251) as u8).collect();
832 let before = super::super::offloaded();
833 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
834 let mut body =
835 Encoder::<Body>::response(encoding, &mut head, Body::from(data.clone()).into());
836 assert_eq!(
837 head.headers().get(CONTENT_ENCODING).unwrap(),
838 encoding.as_str()
839 );
840 assert_eq!(decompress(encoding, &collect(&mut body).await), data);
841 assert_eq!(
842 super::super::offloaded() - before,
843 offloaded,
844 "{encoding:?} {len}"
845 );
846 }
847 }
848 }
849
850 fn random(len: usize) -> Vec<u8> {
852 let mut x = 0x2545_f491_4f6c_dd1d_u64;
853 (0..len)
854 .map(|_| {
855 x ^= x << 13;
856 x ^= x >> 7;
857 x ^= x << 17;
858 x as u8
859 })
860 .collect()
861 }
862
863 #[crate::rt_test]
869 async fn encoder_splits_large_chunks() {
870 for (encoding, task, limit) in [
871 (ContentEncoding::Gzip, 256 * 1024, 16 * 1024),
872 (ContentEncoding::Deflate, 256 * 1024, 16 * 1024),
873 (ContentEncoding::Zstd, 384 * 1024, 128 * 1024),
874 ] {
875 let data = random(2 * task + limit / 2);
877 let before = super::super::offloaded();
878 let mut head = ResponseHead::new(StatusCode::OK, crate::http::Version::HTTP_11);
879 let mut body =
880 Encoder::<Body>::response(encoding, &mut head, Body::from(data.clone()).into());
881
882 let mut encoded = Vec::new();
883 let mut chunks = 0;
884 while let Some(chunk) = poll_fn(|cx| body.poll_next_chunk(cx)).await {
885 let chunk = chunk.unwrap();
886 assert!(chunk.len() <= 32 * 1024, "{encoding:?} {}", chunk.len());
887 encoded.extend_from_slice(&chunk);
888 chunks += 1;
889 }
890 assert!(
891 chunks > encoded.len() / (32 * 1024),
892 "{encoding:?} {chunks}"
893 );
894 assert_eq!(decompress(encoding, &encoded), data);
895 assert_eq!(super::super::offloaded() - before, 2, "{encoding:?}");
896 }
897 }
898
899 #[crate::rt_test]
904 async fn encoder_drops_pending_on_error() {
905 let mut enc = Encoder::<Body> {
906 eof: false,
907 pending: Bytes::from_static(b"rest"),
908 body: EncoderBody::Bytes(Bytes::new()),
909 inner: None,
910 fut: Some(spawn_blocking(|| Err(io::Error::other("encode failed")))),
911 };
912 assert!(matches!(
913 poll_fn(|cx| enc.poll_next_chunk(cx)).await,
914 Some(Err(_))
915 ));
916 assert!(enc.pending.is_empty());
917 assert!(poll_fn(|cx| enc.poll_next_chunk(cx)).await.is_none());
918 }
919
920 #[crate::rt_test]
925 async fn encoder_blocking_task_canceled() {
926 let mut enc = Encoder::<Body> {
927 eof: false,
928 pending: Bytes::new(),
929 body: EncoderBody::Bytes(Bytes::new()),
930 inner: None,
931 fut: Some(spawn_blocking(|| panic!("encoder panic"))),
932 };
933 let res = poll_fn(|cx| enc.poll_next_chunk(cx)).await;
934 assert!(matches!(res, Some(Err(ref e)) if e.to_string() == "Canceled"));
935 assert!(poll_fn(|cx| enc.poll_next_chunk(cx)).await.is_none());
936 }
937
938 #[crate::rt_test]
943 async fn encoder_without_content_encoder() {
944 let mut enc = Encoder::<Body> {
945 eof: false,
946 pending: Bytes::new(),
947 body: EncoderBody::Bytes(Bytes::from_static(b"data")),
948 inner: None,
949 fut: None,
950 };
951 assert!(poll_fn(|cx| enc.poll_next_chunk(cx)).await.is_none());
952 }
953
954 #[test]
960 fn encoder_debug() {
961 assert!(ContentEncoder::new(ContentEncoding::Identity, None).is_none());
962 for (encoding, name) in [
963 (ContentEncoding::Gzip, "ContentEncoder::Gzip"),
964 (ContentEncoding::Deflate, "ContentEncoder::Deflate"),
965 (ContentEncoding::Zstd, "ContentEncoder::Zstd"),
966 ] {
967 let enc = Encoder::<Body> {
968 eof: false,
969 pending: Bytes::new(),
970 body: EncoderBody::Bytes(Bytes::from_static(b"data")),
971 inner: ContentEncoder::new(encoding, None),
972 fut: None,
973 };
974 let s = format!("{enc:?}");
975 assert!(s.contains(name) && s.contains("EncoderBody::Bytes"), "{s}");
976 }
977
978 let s = format!("{:?}", EncoderBody::Stream(Body::Empty));
979 assert_eq!(s, "EncoderBody::Stream(_)");
980 let s = format!(
981 "{:?}",
982 EncoderBody::<Body>::BoxedStream(Box::new(Body::Empty))
983 );
984 assert_eq!(s, "EncoderBody::BoxedStream(_)");
985 }
986
987 fn encode_all(encoding: ContentEncoding, data: &[u8]) -> Vec<Bytes> {
988 let mut enc = ContentEncoder::new(encoding, None).unwrap();
989 enc.write(data).unwrap();
990 enc.finish().unwrap();
991 std::iter::from_fn(|| enc.take()).collect()
992 }
993
994 #[test]
1000 fn encoder_writes_pages() {
1001 for encoding in [
1003 ContentEncoding::Gzip,
1004 ContentEncoding::Deflate,
1005 ContentEncoding::Zstd,
1006 ] {
1007 let data = random(200 * 1024);
1008 let chunks = encode_all(encoding, &data);
1009 assert!(chunks.len() > 6, "{encoding:?} {}", chunks.len());
1010 assert!(chunks.iter().all(|c| c.len() <= 32 * 1024 && !c.is_empty()));
1011 assert_eq!(decompress(encoding, &chunks.concat()), data);
1012 }
1013
1014 let chunks = encode_all(ContentEncoding::Gzip, b"data");
1016 let mut e = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
1017 std::io::Write::write_all(&mut e, b"data").unwrap();
1018 assert_eq!(chunks[0][..10], e.finish().unwrap()[..10]);
1019 }
1020
1021 #[test]
1027 fn encoder_finish_across_pages() {
1028 let data = random(33 * 1024);
1031 for encoding in [
1032 ContentEncoding::Gzip,
1033 ContentEncoding::Deflate,
1034 ContentEncoding::Zstd,
1035 ] {
1036 let sizes: Vec<usize> = (16 * 1024..33 * 1024).collect();
1038 let first =
1039 sizes[sizes.partition_point(|&len| encode_all(encoding, &data[..len]).len() < 2)];
1040 let mut split = 0;
1041 for len in first - 64..first + 64 {
1042 let chunks = encode_all(encoding, &data[..len]);
1043 assert!(chunks.iter().all(|c| c.len() <= 32 * 1024));
1044 if chunks.len() > 1 && chunks.last().unwrap().len() < 8 {
1045 split += 1;
1046 }
1047 assert_eq!(decompress(encoding, &chunks.concat()), &data[..len]);
1048 }
1049 assert!(split > 0, "{encoding:?}");
1050 }
1051 }
1052
1053 #[test]
1058 fn encoder_zstd_window() {
1059 let data = random(4096);
1060 let mut window = Vec::new();
1061 for size in [None, Some(4096)] {
1062 let mut enc = ContentEncoder::new(ContentEncoding::Zstd, size).unwrap();
1063 enc.write(&data).unwrap();
1064 let Codec::Zstd(ctx) = &enc.codec else {
1065 unreachable!()
1066 };
1067 window.push(ctx.sizeof());
1068 enc.finish().unwrap();
1069 let frame = std::iter::from_fn(|| enc.take())
1070 .collect::<Vec<_>>()
1071 .concat();
1072 assert_eq!(decompress(ContentEncoding::Zstd, &frame), data);
1073 }
1074 assert!(window[0] < 1600 * 1024, "{}", window[0]);
1076 assert!(window[1] < 256 * 1024, "{}", window[1]);
1078 }
1079
1080 #[test]
1086 fn encoder_releases_state_on_finish() {
1087 for encoding in [
1088 ContentEncoding::Gzip,
1089 ContentEncoding::Deflate,
1090 ContentEncoding::Zstd,
1091 ] {
1092 let data = random(64 * 1024);
1093 let mut enc = ContentEncoder::new(encoding, None).unwrap();
1094 enc.write(&data).unwrap();
1095 enc.finish().unwrap();
1096 assert!(matches!(enc.codec, Codec::Done), "{encoding:?}");
1097 assert_eq!(format!("{enc:?}"), "ContentEncoder::Done");
1098 assert!(enc.write(b"more").is_err());
1099 assert!(enc.finish().is_err());
1100
1101 let chunks: Vec<_> = std::iter::from_fn(|| enc.take()).collect();
1102 assert!(chunks.len() > 1);
1103 assert_eq!(decompress(encoding, &chunks.concat()), data);
1104 }
1105 }
1106
1107 #[test]
1112 fn encoder_put_across_pages() {
1113 let mut enc = ContentEncoder::new(ContentEncoding::Deflate, None).unwrap();
1114 enc.reserve();
1115 let room = enc.buf.remaining_mut();
1116 enc.put(&vec![1; room - 3]);
1117 enc.put(&[2; 8]);
1118 let page = enc.take().unwrap();
1119 assert_eq!(page.len(), room);
1120 assert_eq!(page[room - 3..], [2; 3]);
1121 assert_eq!(enc.take().unwrap(), [2; 5][..]);
1122 assert!(enc.take().is_none());
1123 }
1124
1125 #[test]
1131 fn encoder_write_after_full_page() {
1132 let mut full = 0;
1135 for encoding in [
1136 ContentEncoding::Gzip,
1137 ContentEncoding::Deflate,
1138 ContentEncoding::Zstd,
1139 ] {
1140 let data = random(256 * 1024);
1141 let mut enc = ContentEncoder::new(encoding, None).unwrap();
1142 let mut out = Vec::new();
1143 for part in data.chunks(16 * 1024) {
1144 enc.write(part).unwrap();
1145 full += usize::from(enc.buf.remaining_mut() == 0);
1146 while let Some(chunk) = enc.take() {
1147 assert!(!chunk.is_empty(), "{encoding:?}");
1148 out.extend_from_slice(&chunk);
1149 }
1150 }
1151 enc.finish().unwrap();
1152 while let Some(chunk) = enc.take() {
1153 assert!(!chunk.is_empty(), "{encoding:?}");
1154 out.extend_from_slice(&chunk);
1155 }
1156 assert_eq!(decompress(encoding, &out), data);
1157 }
1158 assert!(full > 0);
1159 }
1160
1161 struct Parts(Rc<std::cell::RefCell<VecDeque<Option<Bytes>>>>);
1163
1164 impl MessageBody for Parts {
1165 fn size(&self) -> BodySize {
1166 BodySize::Stream
1167 }
1168
1169 fn poll_next_chunk(
1170 &mut self,
1171 _: &mut Context<'_>,
1172 ) -> Poll<Option<Result<Bytes, Rc<dyn std::error::Error>>>> {
1173 let mut parts = self.0.borrow_mut();
1174 match parts.front() {
1175 Some(None) => Poll::Pending,
1176 Some(Some(_)) => Poll::Ready(parts.pop_front().unwrap().map(Ok)),
1177 None => Poll::Ready(None),
1178 }
1179 }
1180 }
1181
1182 fn decompress_prefix(encoding: ContentEncoding, data: &[u8]) -> Vec<u8> {
1184 use std::io::Write;
1185
1186 match encoding {
1187 ContentEncoding::Gzip => {
1188 let mut d = flate2::write::GzDecoder::new(Vec::new());
1189 d.write_all(data).unwrap();
1190 d.flush().unwrap();
1191 d.get_ref().clone()
1192 }
1193 ContentEncoding::Deflate => {
1194 let mut d = flate2::write::ZlibDecoder::new(Vec::new());
1195 d.write_all(data).unwrap();
1196 d.flush().unwrap();
1197 d.get_ref().clone()
1198 }
1199 ContentEncoding::Zstd => {
1200 let mut d = zstd::stream::write::Decoder::new(Vec::new()).unwrap();
1201 d.write_all(data).unwrap();
1202 d.flush().unwrap();
1203 d.get_ref().clone()
1204 }
1205 _ => unreachable!(),
1206 }
1207 }
1208
1209 #[test]
1215 fn encoder_flushes_when_body_is_pending() {
1216 let mut cx = Context::from_waker(std::task::Waker::noop());
1217 let small = Bytes::from_static(b"event: one\n\n");
1218 let large = Bytes::from(random(48 * 1024));
1220
1221 for encoding in [
1222 ContentEncoding::Gzip,
1223 ContentEncoding::Deflate,
1224 ContentEncoding::Zstd,
1225 ] {
1226 let parts = Rc::new(std::cell::RefCell::new(VecDeque::new()));
1227 parts
1228 .borrow_mut()
1229 .extend([Some(small.clone()), None, Some(Bytes::new()), None]);
1230 parts
1231 .borrow_mut()
1232 .extend(large.chunks(12 * 1024).map(|c| Some(large.slice_ref(c))));
1233 parts.borrow_mut().push_back(None);
1234 let mut enc = Encoder {
1235 eof: false,
1236 pending: Bytes::new(),
1237 body: EncoderBody::Stream(Parts(parts.clone())),
1238 inner: ContentEncoder::new(encoding, None),
1239 fut: None,
1240 };
1241 let mut out = Vec::new();
1242 let mut poll = |out: &mut Vec<u8>| {
1243 let mut chunks = 0;
1244 loop {
1245 match enc.poll_next_chunk(&mut cx) {
1246 Poll::Ready(Some(chunk)) => {
1247 chunks += 1;
1248 out.extend_from_slice(&chunk.unwrap());
1249 }
1250 Poll::Ready(None) => return None,
1251 Poll::Pending => return Some(chunks),
1252 }
1253 }
1254 };
1255
1256 assert!(poll(&mut out).unwrap() > 0, "{encoding:?}");
1258 assert_eq!(decompress_prefix(encoding, &out), small, "{encoding:?}");
1259
1260 assert_eq!(poll(&mut out), Some(0), "{encoding:?}");
1262 parts.borrow_mut().pop_front();
1263 assert_eq!(poll(&mut out), Some(0), "{encoding:?}");
1264
1265 parts.borrow_mut().pop_front();
1266 assert!(poll(&mut out).unwrap() > 1, "{encoding:?}");
1267 let data = [&small[..], &large[..]].concat();
1268 assert_eq!(decompress_prefix(encoding, &out), data, "{encoding:?}");
1269
1270 parts.borrow_mut().pop_front();
1271 assert_eq!(poll(&mut out), None);
1272 assert_eq!(decompress(encoding, &out), data, "{encoding:?}");
1273 }
1274 }
1275}