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
use std::{fmt::Write, io};

use bytes::{BufMut, BytesMut};
use http::{StatusCode, Version};
use monoio::{
    buf::IoBuf,
    io::{sink::Sink, AsyncWriteRent, AsyncWriteRentExt},
};
use monoio_codec::Encoder;
use thiserror::Error as ThisError;

use crate::{
    common::{
        body::{Body, StreamHint},
        error::HttpError,
        ext::Reason,
        request::{RequestHead, RequestHeadRef},
        response::{ResponseHead, ResponseHeadRef},
        IntoParts,
    },
    h1::payload::PayloadError,
};

const AVERAGE_HEADER_SIZE: usize = 30;

#[derive(ThisError, Debug)]
pub enum EncodeError {
    #[error("payload error")]
    Payload(#[from] PayloadError),
    #[error("io error {0}")]
    Io(#[from] io::Error),
    #[error("payload error debug")]
    InvalidPayload(String),
}

impl Clone for EncodeError {
    fn clone(&self) -> Self {
        match self {
            Self::Payload(e) => Self::InvalidPayload(e.to_string()),
            _ => self.clone(),
        }
    }
}

struct HeadEncoder(pub Length);

impl HeadEncoder {
    #[inline]
    fn write_length(&self, dst: &mut BytesMut) {
        match self.0 {
            Length::None => (),
            Length::ContentLength(l) => {
                dst.extend_from_slice(http::header::CONTENT_LENGTH.as_ref());
                dst.extend_from_slice(b": ");
                let _ = write!(dst, "{l}");
                dst.extend_from_slice(b"\r\n");
            }
            Length::Chunked => {
                dst.extend_from_slice(http::header::TRANSFER_ENCODING.as_ref());
                dst.extend_from_slice(b": chunked\r\n");
            }
        }
    }

    #[inline]
    fn write_headers(headers: &http::HeaderMap<http::HeaderValue>, dst: &mut BytesMut) {
        if !headers.contains_key(http::header::CONTENT_LENGTH)
            && !headers.contains_key(http::header::TRANSFER_ENCODING)
        {
            // fast path
            for (name, value) in headers.iter() {
                dst.extend_from_slice(name.as_ref());
                dst.extend_from_slice(b": ");
                dst.extend_from_slice(value.as_ref());
                dst.extend_from_slice(b"\r\n");
            }
        } else {
            for (name, value) in headers.iter().filter(|(name, _)| {
                *name != http::header::CONTENT_LENGTH && *name != http::header::TRANSFER_ENCODING
            }) {
                dst.extend_from_slice(name.as_ref());
                dst.extend_from_slice(b": ");
                dst.extend_from_slice(value.as_ref());
                dst.extend_from_slice(b"\r\n");
            }
        }
    }
}

impl Encoder<RequestHead> for HeadEncoder {
    type Error = io::Error;

    #[inline]
    fn encode(&mut self, item: RequestHead, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode((&item.method, &item.uri, item.version, &item.headers), dst)
    }
}

impl Encoder<&RequestHead> for HeadEncoder {
    type Error = io::Error;

    #[inline]
    fn encode(&mut self, item: &RequestHead, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode((&item.method, &item.uri, item.version, &item.headers), dst)
    }
}

impl<'a> Encoder<RequestHeadRef<'a>> for HeadEncoder {
    type Error = io::Error;

    #[inline]
    fn encode(&mut self, item: RequestHeadRef<'a>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode((item.method, item.uri, item.version, item.headers), dst)
    }
}

impl<'a> Encoder<&RequestHeadRef<'a>> for HeadEncoder {
    type Error = io::Error;

    #[inline]
    fn encode(&mut self, item: &RequestHeadRef<'a>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode((item.method, item.uri, item.version, item.headers), dst)
    }
}

impl Encoder<(&http::Method, &http::Uri, http::Version, &http::HeaderMap)> for HeadEncoder {
    type Error = io::Error;

    fn encode(
        &mut self,
        item: (&http::Method, &http::Uri, http::Version, &http::HeaderMap),
        dst: &mut BytesMut,
    ) -> Result<(), Self::Error> {
        let (method, uri, version, headers) = item;
        // TODO: magic number here
        dst.reserve(256 + headers.len() * AVERAGE_HEADER_SIZE);
        // put http method
        dst.extend_from_slice(method.as_str().as_bytes());
        dst.extend_from_slice(b" ");
        // put path
        dst.extend_from_slice(
            uri.path_and_query()
                .map(|u| u.as_str())
                .unwrap_or("/")
                .as_bytes(),
        );
        dst.extend_from_slice(b" ");
        // put version
        let ver = match version {
            Version::HTTP_09 => b"HTTP/0.9\r\n",
            Version::HTTP_10 => b"HTTP/1.0\r\n",
            Version::HTTP_11 => b"HTTP/1.1\r\n",
            Version::HTTP_2 => b"HTTP/2.0\r\n",
            Version::HTTP_3 => b"HTTP/3.0\r\n",
            _ => return Err(io::Error::new(io::ErrorKind::Other, "unsupported version")),
        };
        dst.extend_from_slice(ver);

        // put content length or transfor encoding
        // note: should remote these headers if cannot guarantee these 2 header not exist.
        self.write_length(dst);
        // put headers
        Self::write_headers(headers, dst);
        dst.extend_from_slice(b"\r\n");
        Ok(())
    }
}

impl Encoder<ResponseHead> for HeadEncoder {
    type Error = io::Error;

    #[inline]
    fn encode(&mut self, item: ResponseHead, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(
            (item.status, item.version, &item.headers, &item.extensions),
            dst,
        )
    }
}

impl Encoder<&ResponseHead> for HeadEncoder {
    type Error = io::Error;

    #[inline]
    fn encode(&mut self, item: &ResponseHead, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(
            (item.status, item.version, &item.headers, &item.extensions),
            dst,
        )
    }
}

impl<'a> Encoder<ResponseHeadRef<'a>> for HeadEncoder {
    type Error = io::Error;

    #[inline]
    fn encode(&mut self, item: ResponseHeadRef<'a>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(
            (item.status, item.version, item.headers, item.extensions),
            dst,
        )
    }
}

impl<'a> Encoder<&ResponseHeadRef<'a>> for HeadEncoder {
    type Error = io::Error;

    #[inline]
    fn encode(
        &mut self,
        item: &ResponseHeadRef<'a>,
        dst: &mut BytesMut,
    ) -> Result<(), Self::Error> {
        self.encode(
            (item.status, item.version, item.headers, item.extensions),
            dst,
        )
    }
}

impl
    Encoder<(
        http::StatusCode,
        http::Version,
        &http::HeaderMap<http::HeaderValue>,
        &http::Extensions,
    )> for HeadEncoder
{
    type Error = io::Error;

    fn encode(
        &mut self,
        item: (
            http::StatusCode,
            http::Version,
            &http::HeaderMap<http::HeaderValue>,
            &http::Extensions,
        ),
        dst: &mut bytes::BytesMut,
    ) -> Result<(), Self::Error> {
        let (status, version, headers, extensions) = item;
        // TODO: magic number here
        dst.reserve(256 + headers.len() * AVERAGE_HEADER_SIZE);
        // put version
        if version == Version::HTTP_11
            && status == StatusCode::OK
            && extensions.get::<Reason>().is_none()
        {
            dst.extend_from_slice(b"HTTP/1.1 200 OK\r\n");
        } else {
            let ver = match version {
                Version::HTTP_11 => b"HTTP/1.1 ",
                Version::HTTP_10 => b"HTTP/1.0 ",
                Version::HTTP_09 => b"HTTP/0.9 ",
                _ => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        "unexpected http version",
                    ));
                }
            };
            dst.extend_from_slice(ver);
            // put status code
            dst.extend_from_slice(status.as_str().as_bytes());
            dst.extend_from_slice(b" ");
            // put reason
            let reason = match extensions.get::<Reason>() {
                Some(reason) => reason.as_bytes(),
                None => status.canonical_reason().unwrap_or("<none>").as_bytes(),
            };
            dst.extend_from_slice(reason);
            dst.extend_from_slice(b"\r\n");
        }

        // put content length or transfor encoding
        // note: should remote these headers if cannot guarantee these 2 header not exist.
        self.write_length(dst);
        // put headers
        Self::write_headers(headers, dst);
        dst.extend_from_slice(b"\r\n");
        Ok(())
    }
}

struct FixedBodyEncoder;

impl Encoder<&[u8]> for FixedBodyEncoder {
    type Error = io::Error;

    // Note: for big body, flush the buffer and send it directly to avoid copy.
    fn encode(&mut self, item: &[u8], dst: &mut bytes::BytesMut) -> Result<(), Self::Error> {
        dst.extend_from_slice(item);
        Ok(())
    }
}

struct ChunkedBodyEncoder;

impl Encoder<Option<&[u8]>> for ChunkedBodyEncoder {
    type Error = io::Error;

    fn encode(
        &mut self,
        item: Option<&[u8]>,
        dst: &mut bytes::BytesMut,
    ) -> Result<(), Self::Error> {
        let data = match item {
            Some(d) => d,
            None => {
                dst.extend_from_slice(b"0\r\n\r\n");
                return Ok(());
            }
        };
        // 8 size + \r\n + data + \r\n = 12 + data.len()
        dst.reserve(12 + data.len());
        dst.write_fmt(format_args!("{:X}\r\n", data.len()))
            .expect("write Bytes failed");
        dst.extend_from_slice(data);
        dst.extend_from_slice(b"\r\n");
        Ok(())
    }
}

/// Encoder for Request or Response(in fact it is not a encoder literally,
/// it is with io, like FramedWrite).
pub struct GenericEncoder<T> {
    io: T,
    buf: BytesMut,
}

const INITIAL_CAPACITY: usize = 8 * 1024;
const BACKPRESSURE_BOUNDARY: usize = INITIAL_CAPACITY;

impl<T> GenericEncoder<T> {
    pub fn new(io: T) -> Self {
        Self {
            io,
            buf: BytesMut::with_capacity(INITIAL_CAPACITY),
        }
    }
}

#[allow(clippy::enum_variant_names)]
enum Length {
    None,
    ContentLength(usize),
    Chunked,
}

impl<T, R> Sink<R> for GenericEncoder<T>
where
    T: AsyncWriteRent,
    R: IntoParts,
    R::Body: Body,
    HeadEncoder: Encoder<R::Parts>,
    <HeadEncoder as Encoder<R::Parts>>::Error: Into<EncodeError>,
    HttpError: From<<<R as IntoParts>::Body as Body>::Error>,
{
    type Error = HttpError;

    async fn send(&mut self, item: R) -> Result<(), Self::Error> {
        let (head, mut payload) = item.into_parts();

        // if there is too much content in buffer, flush it first
        if self.buf.len() > BACKPRESSURE_BOUNDARY {
            Sink::<R>::flush(self).await?;
        }
        let payload_type = payload.stream_hint();

        match payload_type {
            StreamHint::None => {
                let mut encoder = HeadEncoder(Length::None);
                // encode head to buffer
                encoder.encode(head, &mut self.buf).map_err(Into::into)?;
            }
            StreamHint::Fixed => {
                // get data(to set content length and body)
                let data = payload
                    .next_data()
                    .await
                    .expect("empty data with fixed hint")?;
                let mut encoder = HeadEncoder(Length::ContentLength(data.bytes_init()));
                // encode head to buffer
                encoder.encode(head, &mut self.buf).map_err(Into::into)?;
                // flush
                if self.buf.len() + data.bytes_init() > BACKPRESSURE_BOUNDARY {
                    // if data to send is too long, we will flush the buffer
                    // first, and send Bytes directly.
                    Sink::<R>::flush(self).await?;
                    let (r, _) = self.io.write_all(data).await;
                    r?;
                } else {
                    // the data length is small, we copy it to avoid too many
                    // syscall(head and body will be sent together).
                    let slice =
                        unsafe { std::slice::from_raw_parts(data.read_ptr(), data.bytes_init()) };
                    FixedBodyEncoder.encode(slice, &mut self.buf)?;
                }
            }
            StreamHint::Stream => {
                let mut encoder = HeadEncoder(Length::Chunked);
                // encode head to buffer
                encoder.encode(head, &mut self.buf).map_err(Into::into)?;

                while let Some(data_res) = payload.next_data().await {
                    let data = data_res?;
                    write!(self.buf, "{:X}\r\n", data.bytes_init())
                        .expect("unable to format data length");
                    if self.buf.len() + data.bytes_init() > BACKPRESSURE_BOUNDARY {
                        // if data to send is too long, we will flush the buffer
                        // first, and send Bytes directly.
                        if !self.buf.is_empty() {
                            Sink::<R>::flush(self).await?;
                        }
                        let (r, _) = self.io.write_all(data).await;
                        r?;
                    } else {
                        // the data length is small, we copy it to avoid too many
                        // syscall.
                        let slice = unsafe {
                            std::slice::from_raw_parts(data.read_ptr(), data.bytes_init())
                        };
                        FixedBodyEncoder.encode(slice, &mut self.buf)?;
                    }
                    self.buf.put_slice(b"\r\n");
                }
                self.buf.put_slice(b"0\r\n\r\n");
            }
        }
        Ok(())
    }

    async fn flush(&mut self) -> Result<(), Self::Error> {
        if self.buf.is_empty() {
            return Ok(());
        }
        // This action does not allocate.
        let buf = std::mem::replace(&mut self.buf, BytesMut::new());
        let (result, buf) = self.io.write_all(buf).await;
        self.buf = buf;
        result?;
        self.buf.clear();
        self.io.flush().await?;
        Ok(())
    }

    // copied from monoio-codec
    async fn close(&mut self) -> Result<(), Self::Error> {
        Sink::<R>::flush(self).await?;
        self.io.shutdown().await?;
        Ok(())
    }
}