Skip to main content

ntex/http/h1/
codec.rs

1use std::{cell::Cell, fmt};
2
3use bitflags::bitflags;
4
5use crate::codec::{Decoder, Encoder};
6use crate::http::body::BodySize;
7use crate::http::config::{DateService, HttpServiceConfig};
8use crate::http::error::{DecodeError, EncodeError};
9use crate::http::message::ConnectionType;
10use crate::http::{Method, StatusCode, Version, request::Request, response::Response};
11use crate::{Cfg, util::BytePages, util::BytesMut};
12
13use super::{Message, decoder, decoder::PayloadType, encoder};
14
15bitflags! {
16    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
17    struct Flags: u8 {
18        const HEAD              = 0b0000_0001;
19        const STREAM            = 0b0000_0010;
20        const KEEPALIVE_ENABLED = 0b0000_0100;
21    }
22}
23
24/// Stateful HTTP/1 request decoder and response encoder.
25///
26/// The codec tracks the version, connection behavior, request method, and
27/// streaming state of the most recently decoded request.
28///
29/// # Decoding
30///
31/// [`Decoder::decode`] incrementally consumes one request head and returns its
32/// [`Request`] together with a [`PayloadType`]. For
33/// [`PayloadType::Payload`], pass subsequent bytes to the returned payload
34/// decoder until framing completes before decoding another request head. Bytes
35/// for a pipelined request can already remain in the input buffer.
36/// [`PayloadType::Stream`] ends HTTP message framing; transfer the connection
37/// and any buffered bytes to the upgraded protocol instead of decoding another
38/// HTTP request.
39///
40/// `Ok(None)` means that more bytes are required. A [`DecodeError`] indicates
41/// invalid framing or a configured request-head limit and should be treated as
42/// a connection-level protocol failure.
43///
44/// # Encoding
45///
46/// [`Encoder::encode`] accepts a
47/// [`Message<(Response<()>, BodySize)>`](Message). Encode the response head
48/// first, followed by body chunks and a final `Message::Chunk(None)` when the
49/// response has a body. The codec selects fixed-length, chunked, or
50/// connection-close framing from the response, request method, version, and
51/// supplied [`BodySize`]. An [`EncodeError`] indicates invalid response
52/// encoding or an incomplete fixed-length body.
53///
54/// The codec only transforms buffers; it does not perform I/O, flush output,
55/// or apply transport backpressure.
56pub struct Codec {
57    con_id: usize,
58    decoder: decoder::MessageDecoder<Request>,
59    version: Cell<Version>,
60    ctype: Cell<ConnectionType>,
61    pub(super) cfg: Cfg<HttpServiceConfig>,
62
63    // encoder part
64    flags: Cell<Flags>,
65    encoder: encoder::MessageEncoder<Response<()>>,
66}
67
68impl Clone for Codec {
69    fn clone(&self) -> Self {
70        Codec {
71            con_id: self.con_id,
72            decoder: self.decoder.clone(),
73            version: self.version.clone(),
74            cfg: self.cfg.clone(),
75            ctype: self.ctype.clone(),
76            flags: self.flags.clone(),
77            encoder: self.encoder.clone(),
78        }
79    }
80}
81
82impl fmt::Debug for Codec {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.debug_struct("h1::Codec")
85            .field("con_id", &self.con_id)
86            .field("version", &self.version)
87            .field("flags", &self.flags)
88            .field("ctype", &self.ctype)
89            .field("encoder", &self.encoder)
90            .field("decoder", &self.decoder)
91            .finish()
92    }
93}
94
95impl Codec {
96    /// Creates an HTTP/1 codec.
97    ///
98    /// `con_id` identifies the connection in decoded request heads. Protocol
99    /// limits and keep-alive behavior are read from `cfg`.
100    pub fn new(con_id: usize, cfg: Cfg<HttpServiceConfig>) -> Self {
101        let flags = if cfg.ka_enabled {
102            Flags::KEEPALIVE_ENABLED
103        } else {
104            Flags::empty()
105        };
106        let ctype = if cfg.ka_enabled {
107            ConnectionType::KeepAlive
108        } else {
109            ConnectionType::Close
110        };
111        let decoder = decoder::MessageDecoder::new(cfg.clone());
112
113        Codec {
114            cfg,
115            con_id,
116            decoder,
117            flags: Cell::new(flags),
118            version: Cell::new(Version::HTTP_11),
119            ctype: Cell::new(ctype),
120            encoder: encoder::MessageEncoder::default(),
121        }
122    }
123
124    pub(super) fn is_reading_hdrs(&self) -> bool {
125        self.decoder.is_reading_hdrs()
126    }
127
128    /// Returns `true` if the response body accepts no more data.
129    pub(super) fn is_body_complete(&self) -> bool {
130        self.encoder.is_body_complete()
131    }
132
133    #[inline]
134    /// Returns whether the current HTTP connection state is persistent.
135    ///
136    /// Before the first request is decoded, this reflects whether keep-alive
137    /// is enabled in the service configuration. Decoding a request or encoding
138    /// a response can update the value.
139    pub fn keepalive(&self) -> bool {
140        self.ctype.get() == ConnectionType::KeepAlive
141    }
142
143    #[inline]
144    #[doc(hidden)]
145    pub fn set_date_header(&self, dst: &mut BytesMut) {
146        DateService.set_date_header(dst);
147    }
148
149    fn insert_flags(&self, f: Flags) {
150        let mut flags = self.flags.get();
151        flags.insert(f);
152        self.flags.set(flags);
153    }
154
155    pub(super) fn reset_upgrade(&self) {
156        let mut flags = self.flags.get();
157        flags.remove(Flags::STREAM);
158        self.flags.set(flags);
159        self.ctype.set(ConnectionType::Close);
160    }
161}
162
163impl Decoder for Codec {
164    type Item = (Request, PayloadType);
165    type Error = DecodeError;
166
167    #[inline]
168    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
169        if let Some((mut req, payload)) = self.decoder.decode(src)? {
170            let head = req.head_mut();
171            head.id = self.con_id;
172            let mut flags = self.flags.get();
173            flags.set(Flags::HEAD, head.method == Method::HEAD);
174            self.flags.set(flags);
175            self.version.set(head.version);
176
177            let ctype = head.connection_type();
178            if ctype == ConnectionType::KeepAlive && !flags.contains(Flags::KEEPALIVE_ENABLED) {
179                self.ctype.set(ConnectionType::Close);
180            } else {
181                self.ctype.set(ctype);
182            }
183
184            if let PayloadType::Stream(_) = payload {
185                self.insert_flags(Flags::STREAM);
186            }
187            Ok(Some((req, payload)))
188        } else {
189            Ok(None)
190        }
191    }
192}
193
194impl Encoder for Codec {
195    type Item = Message<(Response<()>, BodySize)>;
196    type Error = EncodeError;
197
198    fn encode(&self, item: Self::Item, dst: &mut BytePages) -> Result<(), Self::Error> {
199        match item {
200            Message::Item((mut res, length)) => {
201                // set response version
202                res.head_mut().version = self.version.get();
203
204                // connection status, http/1 cannot continue after 101
205                if res.status() == StatusCode::SWITCHING_PROTOCOLS {
206                    self.ctype.set(ConnectionType::Upgrade);
207                } else if let Some(ct) = res.head().ctype()
208                    && ct != ConnectionType::KeepAlive
209                {
210                    self.ctype.set(ct);
211                }
212
213                // encode message
214                let ctype = self.encoder.encode(
215                    dst,
216                    &res,
217                    self.flags.get().contains(Flags::HEAD),
218                    self.flags.get().contains(Flags::STREAM),
219                    self.version.get(),
220                    length,
221                    self.ctype.get(),
222                    None,
223                )?;
224                self.ctype.set(ctype);
225            }
226            Message::Chunk(Some(bytes)) => {
227                self.encoder.encode_chunk(bytes, dst);
228            }
229            Message::Chunk(None) => {
230                self.encoder.encode_eof(dst)?;
231            }
232        }
233        Ok(())
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240    use crate::{
241        SharedCfg,
242        http::{HttpMessage, KeepAlive, h1::PayloadItem},
243        time::Seconds,
244        util::Bytes,
245    };
246
247    /// STATEMENT: Unknown status codes use an empty reason unless the response supplies a custom phrase.
248    ///
249    /// HOW:
250    /// - Encode status 599 with default and custom reasons and compare the wire status lines.
251    #[crate::rt_test]
252    async fn test_unknown_status_reason() {
253        use crate::http::StatusCode;
254
255        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
256        let codec = Codec::new(0, cfg.get());
257        let mut buf = BytesMut::from("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
258        codec.decode(&mut buf).unwrap().unwrap();
259
260        let status = StatusCode::from_u16(599).unwrap();
261        let res = Response::with_body(status, ());
262        assert_eq!(res.head().reason(), "");
263        let mut out = BytePages::default();
264        codec
265            .encode(Message::Item((res, BodySize::Empty)), &mut out)
266            .unwrap();
267        let data = out.take().unwrap();
268        assert!(data.starts_with(b"HTTP/1.1 599 \r\n"), "{data:?}");
269
270        let mut res = Response::with_body(status, ());
271        res.head_mut().reason = Some("Custom");
272        let mut out = BytePages::default();
273        codec
274            .encode(Message::Item((res, BodySize::Empty)), &mut out)
275            .unwrap();
276        let data = out.take().unwrap();
277        assert!(data.starts_with(b"HTTP/1.1 599 Custom\r\n"), "{data:?}");
278    }
279
280    /// STATEMENT: Bodyless response statuses suppress payload bytes and framing headers.
281    ///
282    /// HOW:
283    /// - Encode informational, no-content, and not-modified responses with sized and streaming payloads.
284    /// - Check output ends after headers and contains neither length nor transfer encoding.
285    #[crate::rt_test]
286    async fn test_bodyless_status_has_no_body() {
287        use crate::http::StatusCode;
288
289        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
290        for status in [
291            StatusCode::CONTINUE,
292            StatusCode::from_u16(103).unwrap(),
293            StatusCode::NO_CONTENT,
294            StatusCode::NOT_MODIFIED,
295        ] {
296            for size in [BodySize::Sized(3), BodySize::Stream] {
297                let codec = Codec::new(0, cfg.get());
298                let mut buf = BytesMut::from("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n");
299                codec.decode(&mut buf).unwrap().unwrap();
300
301                let mut out = BytePages::default();
302                let res = Response::with_body(status, ());
303                codec.encode(Message::Item((res, size)), &mut out).unwrap();
304                codec
305                    .encode(Message::Chunk(Some(Bytes::from_static(b"abc"))), &mut out)
306                    .unwrap();
307                codec.encode(Message::Chunk(None), &mut out).unwrap();
308
309                let mut data = Vec::new();
310                while let Some(chunk) = out.take() {
311                    data.extend_from_slice(&chunk);
312                }
313                let data = String::from_utf8(data).unwrap();
314                assert!(data.ends_with("\r\n\r\n"), "{status} {size:?}: {data:?}");
315                assert!(
316                    !data.contains("content-length"),
317                    "{status} {size:?}: {data:?}"
318                );
319                assert!(
320                    !data.contains("transfer-encoding"),
321                    "{status} {size:?}: {data:?}"
322                );
323            }
324        }
325    }
326
327    /// STATEMENT: Switching protocols ends HTTP/1 persistence even without an explicit response upgrade setting.
328    ///
329    /// HOW:
330    /// - Decode an ordinary persistent request, encode a `101` response, and check upgrade output and disabled keepalive.
331    #[crate::rt_test]
332    async fn test_switching_protocols_ends_http1() {
333        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
334        let codec = Codec::new(0, cfg.get());
335        let mut buf = BytesMut::from("GET / HTTP/1.1\r\nhost: a\r\n\r\n");
336        codec.decode(&mut buf).unwrap().unwrap();
337        assert!(codec.keepalive());
338
339        // no `.upgrade()` on the response
340        let mut out = BytePages::default();
341        codec
342            .encode(
343                Message::Item((
344                    Response::with_body(StatusCode::SWITCHING_PROTOCOLS, ()),
345                    BodySize::None,
346                )),
347                &mut out,
348            )
349            .unwrap();
350        let mut data = Vec::new();
351        while let Some(chunk) = out.take() {
352            data.extend_from_slice(&chunk);
353        }
354        let data = String::from_utf8(data).unwrap();
355        assert!(data.contains("connection: upgrade\r\n"), "{data:?}");
356        assert!(!codec.keepalive());
357    }
358
359    /// STATEMENT: Protocol-switching response bodies are sent unframed as new-protocol data.
360    ///
361    /// HOW:
362    /// - Encode sized and streaming `101` responses with multiple chunks.
363    /// - Compare concatenated wire data and verify no HTTP body-framing headers are emitted.
364    #[crate::rt_test]
365    async fn test_switching_protocols_body_is_not_framed() {
366        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
367        for size in [BodySize::Sized(3), BodySize::Stream] {
368            // not an upgrade request, the body is not a stream
369            let codec = Codec::new(0, cfg.get());
370            let mut buf = BytesMut::from("GET / HTTP/1.1\r\nhost: a\r\n\r\n");
371            codec.decode(&mut buf).unwrap().unwrap();
372
373            let mut out = BytePages::default();
374            let res = Response::with_body(StatusCode::SWITCHING_PROTOCOLS, ());
375            codec.encode(Message::Item((res, size)), &mut out).unwrap();
376            for chunk in [&b"abc"[..], b"defg"] {
377                codec
378                    .encode(
379                        Message::Chunk(Some(Bytes::copy_from_slice(chunk))),
380                        &mut out,
381                    )
382                    .unwrap();
383            }
384            codec.encode(Message::Chunk(None), &mut out).unwrap();
385
386            let mut data = Vec::new();
387            while let Some(chunk) = out.take() {
388                data.extend_from_slice(&chunk);
389            }
390            let data = String::from_utf8(data).unwrap();
391            assert!(data.ends_with("\r\n\r\nabcdefg"), "{size:?}: {data:?}");
392            assert!(!data.contains("content-length"), "{size:?}: {data:?}");
393            assert!(!data.contains("transfer-encoding"), "{size:?}: {data:?}");
394        }
395    }
396
397    /// STATEMENT: Responses without a body use zero-length framing unless the method or status forbids it.
398    ///
399    /// HOW:
400    /// - Encode ordinary HTTP/1.0 and HTTP/1.1 responses, including an overridden service length.
401    /// - Compare length/persistence headers and verify HEAD, bodyless, and upgrade responses omit framing.
402    #[crate::rt_test]
403    async fn test_response_without_body_has_length() {
404        use crate::http::{StatusCode, header};
405
406        let encode = |req: &str, res: Response<()>| {
407            let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
408            let codec = Codec::new(0, cfg.get());
409            let mut buf = BytesMut::from(req);
410            codec.decode(&mut buf).unwrap().unwrap();
411
412            let mut out = BytePages::default();
413            codec
414                .encode(Message::Item((res, BodySize::None)), &mut out)
415                .unwrap();
416            let mut data = Vec::new();
417            while let Some(chunk) = out.take() {
418                data.extend_from_slice(&chunk);
419            }
420            (String::from_utf8(data).unwrap(), codec.keepalive())
421        };
422        let get = "GET / HTTP/1.1\r\nhost: a\r\n\r\n";
423
424        let (data, keepalive) = encode(get, Response::with_body(StatusCode::OK, ()));
425        assert!(data.contains("\r\ncontent-length: 0\r\n"), "{data:?}");
426        assert!(keepalive);
427
428        // a length set by the service is replaced
429        let mut res = Response::with_body(StatusCode::NOT_FOUND, ());
430        res.headers_mut().insert(
431            header::CONTENT_LENGTH,
432            header::HeaderValue::from_static("10"),
433        );
434        let (data, _) = encode(get, res);
435        assert_eq!(data.matches("content-length").count(), 1, "{data:?}");
436        assert!(data.contains("\r\ncontent-length: 0\r\n"), "{data:?}");
437
438        let (data, keepalive) = encode(
439            "GET / HTTP/1.0\r\nconnection: keep-alive\r\n\r\n",
440            Response::with_body(StatusCode::OK, ()),
441        );
442        assert!(data.contains("\r\ncontent-length: 0\r\n"), "{data:?}");
443        assert!(data.contains("connection: keep-alive\r\n"), "{data:?}");
444        assert!(keepalive);
445
446        // no body is expected
447        for (req, status) in [
448            ("HEAD / HTTP/1.1\r\nhost: a\r\n\r\n", StatusCode::OK),
449            (get, StatusCode::NO_CONTENT),
450            (get, StatusCode::NOT_MODIFIED),
451            (
452                "GET / HTTP/1.1\r\nhost: a\r\nconnection: upgrade\r\nupgrade: websocket\r\n\r\n",
453                StatusCode::SWITCHING_PROTOCOLS,
454            ),
455        ] {
456            let (data, _) = encode(req, Response::with_body(status, ()));
457            assert!(!data.contains("content-length"), "{status} {data:?}");
458            assert!(!data.contains("transfer-encoding"), "{status} {data:?}");
459        }
460    }
461
462    fn encode_stream(req: &str, res: Response<()>) -> (String, bool) {
463        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
464        let codec = Codec::new(0, cfg.get());
465        let mut buf = BytesMut::from(req);
466        codec.decode(&mut buf).unwrap().unwrap();
467
468        let mut out = BytePages::default();
469        codec
470            .encode(Message::Item((res, BodySize::Stream)), &mut out)
471            .unwrap();
472        codec
473            .encode(Message::Chunk(Some(Bytes::from_static(b"abc"))), &mut out)
474            .unwrap();
475        codec.encode(Message::Chunk(None), &mut out).unwrap();
476
477        let mut data = Vec::new();
478        while let Some(chunk) = out.take() {
479            data.extend_from_slice(&chunk);
480        }
481        (String::from_utf8(data).unwrap(), codec.keepalive())
482    }
483
484    /// STATEMENT: Streaming responses use chunked framing only when supported and enabled, otherwise closing the connection.
485    ///
486    /// HOW:
487    /// - Encode HTTP/1.0, ordinary HTTP/1.1, and no-chunking HTTP/1.1 streams.
488    /// - Compare raw/chunked payloads, connection headers, and codec persistence.
489    #[crate::rt_test]
490    async fn test_http10_stream_response_is_not_chunked() {
491        use crate::http::StatusCode;
492
493        let (data, keepalive) = encode_stream(
494            "GET / HTTP/1.0\r\nconnection: keep-alive\r\n\r\n",
495            Response::with_body(StatusCode::OK, ()),
496        );
497        assert!(data.starts_with("HTTP/1.1 200 OK\r\n"), "{data:?}");
498        assert!(!data.contains("transfer-encoding"), "{data:?}");
499        assert!(!data.contains("keep-alive"), "{data:?}");
500        assert!(data.contains("connection: close\r\n"), "{data:?}");
501        assert!(data.ends_with("\r\n\r\nabc"), "{data:?}");
502        assert!(!keepalive);
503
504        let (data, keepalive) = encode_stream(
505            "GET / HTTP/1.1\r\nhost: localhost\r\n\r\n",
506            Response::with_body(StatusCode::OK, ()),
507        );
508        assert!(data.contains("transfer-encoding: chunked\r\n"), "{data:?}");
509        assert!(data.ends_with("3\r\nabc\r\n0\r\n\r\n"), "{data:?}");
510        assert!(keepalive);
511
512        let mut res = Response::with_body(StatusCode::OK, ());
513        res.head_mut().no_chunking(true);
514        let (data, keepalive) = encode_stream("GET / HTTP/1.1\r\nhost: localhost\r\n\r\n", res);
515        assert!(data.contains("connection: close\r\n"), "{data:?}");
516        assert!(data.ends_with("\r\n\r\nabc"), "{data:?}");
517        assert!(!keepalive);
518    }
519
520    /// STATEMENT: Chunked request decoding preserves pipeline boundaries and upgrade requests disable reuse.
521    ///
522    /// HOW:
523    /// - Decode merged small chunks, EOF, and a following request from one buffer.
524    /// - Exercise upgrade token combinations and disabled keepalive configuration, inspecting request and codec state.
525    #[test]
526    fn test_http_request_chunked_payload_and_next_message() {
527        let cfg: SharedCfg = SharedCfg::new("DBG").add(HttpServiceConfig::new()).into();
528
529        let codec = Codec::new(0, cfg.get());
530        assert!(format!("{codec:?}").contains("h1::Codec"));
531
532        let mut buf = BytesMut::from(
533            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
534             transfer-encoding: chunked\r\n\r\n",
535        );
536        let (req, pl) = codec.decode(&mut buf).unwrap().unwrap();
537        let PayloadType::Payload(pl) = pl else { panic!() };
538
539        assert_eq!(req.method(), Method::GET);
540        assert!(req.chunked().unwrap());
541
542        buf.extend(
543            b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n\
544               POST /test2 HTTP/1.1\r\nhost: localhost\r\n\
545               transfer-encoding: chunked\r\n\r\n"
546                .iter(),
547        );
548
549        // small chunks are merged
550        let msg = pl.decode(&mut buf).unwrap().unwrap();
551        assert_eq!(msg, PayloadItem::Chunk(Bytes::from_static(b"dataline")));
552
553        let msg = pl.decode(&mut buf).unwrap().unwrap();
554        assert_eq!(msg, PayloadItem::Eof);
555
556        // decode next message
557        let (req, _pl) = codec.decode(&mut buf).unwrap().unwrap();
558        assert_eq!(*req.method(), Method::POST);
559        assert!(req.chunked().unwrap());
560
561        let codec = Codec::new(0, cfg.get());
562        let mut buf = BytesMut::from(
563            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
564             connection: upgrade\r\nupgrade: websocket\r\n\r\n",
565        );
566        let (req, _) = codec.decode(&mut buf).unwrap().unwrap();
567        assert!(req.upgrade());
568        assert!(!codec.keepalive());
569        codec.reset_upgrade();
570        assert!(!codec.keepalive());
571
572        // `Connection: keep-alive, Upgrade` is sent by browsers
573        let codec = Codec::new(0, cfg.get());
574        let mut buf = BytesMut::from(
575            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
576             connection: keep-alive, Upgrade\r\nupgrade: websocket\r\n\r\n",
577        );
578        let (req, _) = codec.decode(&mut buf).unwrap().unwrap();
579        assert!(req.upgrade());
580
581        let codec = Codec::new(0, cfg.get());
582        let mut buf = BytesMut::from("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
583        let (req, _) = codec.decode(&mut buf).unwrap().unwrap();
584        assert!(!req.upgrade());
585
586        let cfg: SharedCfg = SharedCfg::new("DBG")
587            .add(HttpServiceConfig::new().set_keepalive(KeepAlive::Disabled))
588            .into();
589        let codec = Codec::new(0, cfg.get());
590        assert!(!codec.keepalive());
591    }
592
593    /// STATEMENT: Zero keep-alive timeouts make HTTP/1 connections non-persistent, while `Os` and nonzero timeouts stay persistent.
594    ///
595    /// HOW:
596    /// - Build codecs from `KeepAlive::Os`, a 10-second timeout, and zero timeouts given as `usize`, `Seconds`, and `set_keepalive_timeout`.
597    /// - Decode an HTTP/1.1 request without a `Connection` header and compare `Codec::keepalive` before and after decoding.
598    #[test]
599    fn keepalive_zero_policy() {
600        let cases = [
601            (HttpServiceConfig::new().set_keepalive(KeepAlive::Os), true),
602            (HttpServiceConfig::new().set_keepalive(10), true),
603            (HttpServiceConfig::new().set_keepalive(0), false),
604            (HttpServiceConfig::new().set_keepalive(Seconds::ZERO), false),
605            (
606                HttpServiceConfig::new().set_keepalive_timeout(Seconds::ZERO),
607                false,
608            ),
609        ];
610        for (cfg, persistent) in cases {
611            let cfg: SharedCfg = SharedCfg::new("DBG").add(cfg).into();
612            let codec = Codec::new(0, cfg.get());
613            assert_eq!(codec.keepalive(), persistent);
614
615            let mut buf = BytesMut::from("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
616            codec.decode(&mut buf).unwrap().unwrap();
617            assert_eq!(codec.keepalive(), persistent);
618        }
619    }
620}