Skip to main content

http_type/stream/
impl.rs

1use super::*;
2
3/// Implementation of `From` trait for converting `usize` address into `&Stream`.
4impl From<usize> for &'static Stream {
5    /// Converts a memory address into a reference to `Stream`.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - The memory address of the `Stream` instance.
10    ///
11    /// # Returns
12    ///
13    /// - `&'static Stream` - A reference to the `Stream` at the given address.
14    ///
15    /// # Safety
16    ///
17    /// - The address is guaranteed to be a valid `Stream` instance
18    ///   that was previously converted from a reference and is managed by the runtime.
19    #[inline(always)]
20    fn from(address: usize) -> &'static Stream {
21        unsafe { &*(address as *const Stream) }
22    }
23}
24
25/// Implementation of `From` trait for converting `usize` address into `&mut Stream`.
26impl<'a> From<usize> for &'a mut Stream {
27    /// Converts a memory address into a mutable reference to `Stream`.
28    ///
29    /// # Arguments
30    ///
31    /// - `usize` - The memory address of the `Stream` instance.
32    ///
33    /// # Returns
34    ///
35    /// - `&'a mut Stream` - A mutable reference to the `Stream` at the given address.
36    ///
37    /// # Safety
38    ///
39    /// - The address is guaranteed to be a valid `Stream` instance
40    ///   that was previously converted from a reference and is managed by the runtime.
41    #[inline(always)]
42    fn from(address: usize) -> &'a mut Stream {
43        unsafe { &mut *(address as *mut Stream) }
44    }
45}
46
47/// Implementation of `From` trait for converting `&Stream` into `usize` address.
48impl From<&Stream> for usize {
49    /// Converts a reference to `Stream` into its memory address.
50    ///
51    /// # Arguments
52    ///
53    /// - `&Stream` - The reference to the `Stream` instance.
54    ///
55    /// # Returns
56    ///
57    /// - `usize` - The memory address of the `Stream` instance.
58    #[inline(always)]
59    fn from(stream: &Stream) -> Self {
60        stream as *const Stream as usize
61    }
62}
63
64/// Implementation of `From` trait for converting `&mut Stream` into `usize` address.
65impl From<&mut Stream> for usize {
66    /// Converts a mutable reference to `Stream` into its memory address.
67    ///
68    /// # Arguments
69    ///
70    /// - `&mut Stream` - The mutable reference to the `Stream` instance.
71    ///
72    /// # Returns
73    ///
74    /// - `usize` - The memory address of the `Stream` instance.
75    #[inline(always)]
76    fn from(stream: &mut Stream) -> Self {
77        stream as *mut Stream as usize
78    }
79}
80
81/// Implementation of `AsRef` trait for `Stream`.
82impl AsRef<Stream> for Stream {
83    /// Converts `&Stream` to `&Stream` via memory address conversion.
84    ///
85    /// # Returns
86    ///
87    /// - `&Self` - A reference to the `Stream` instance.
88    #[inline(always)]
89    fn as_ref(&self) -> &Self {
90        let address: usize = self.into();
91        address.into()
92    }
93}
94
95/// Implementation of `AsMut` trait for `Stream`.
96impl AsMut<Stream> for Stream {
97    /// Converts `&mut Stream` to `&mut Stream` via memory address conversion.
98    ///
99    /// # Returns
100    ///
101    /// - `&mut Self` - A mutable reference to the `Stream` instance.
102    #[inline(always)]
103    fn as_mut(&mut self) -> &mut Self {
104        let address: usize = self.into();
105        address.into()
106    }
107}
108
109/// Implementation of `Lifetime` trait for `Stream`.
110impl Lifetime for Stream {
111    /// Converts a reference to the stream into a `'static` reference.
112    ///
113    /// # Returns
114    ///
115    /// - `&'static Self` - A reference to the stream with a `'static` lifetime.
116    ///
117    /// # Safety
118    ///
119    /// - The address is guaranteed to be a valid `Self` instance
120    ///   that was previously converted from a reference and is managed by the runtime.
121    #[inline(always)]
122    unsafe fn leak(&self) -> &'static Self {
123        let address: usize = self.into();
124        address.into()
125    }
126
127    /// Converts a reference to the stream into a `'static` mutable reference.
128    ///
129    /// # Returns
130    ///
131    /// - `&'static mut Self` - A mutable reference to the stream with a `'static` lifetime.
132    ///
133    /// # Safety
134    ///
135    /// - The address is guaranteed to be a valid `Self` instance
136    ///   that was previously converted from a reference and is managed by the runtime.
137    #[inline(always)]
138    unsafe fn leak_mut(&self) -> &'static mut Self {
139        let address: usize = self.into();
140        address.into()
141    }
142}
143
144/// Implementation of `Transport` trait for the plain TCP socket.
145///
146/// The socket is the reference transport: it already carries a socket
147/// identity, so its addresses are reported directly.
148impl Transport for TcpStream {
149    /// Reports the address of the remote end of the socket.
150    ///
151    /// # Returns
152    ///
153    /// - `Result<SocketAddr, io::Error>` - The peer address of the socket.
154    fn peer_addr(&self) -> Result<SocketAddr, io::Error> {
155        TcpStream::peer_addr(self)
156    }
157
158    /// Reports the address of the local end of the socket.
159    ///
160    /// # Returns
161    ///
162    /// - `Result<SocketAddr, io::Error>` - The local address of the socket.
163    fn local_addr(&self) -> Result<SocketAddr, io::Error> {
164        TcpStream::local_addr(self)
165    }
166}
167
168/// Implements [`Drop`] for [`PooledReader`].
169impl Drop for PooledReader<'_> {
170    /// Releases the buffer back to the pool for reuse by later requests.
171    fn drop(&mut self) {
172        let buffer: Vec<u8> = mem::take(self.get_mut_buffer());
173        return_read_buffer(buffer);
174    }
175}
176
177/// Implements non-blocking buffered reads for `PooledReader`.
178///
179/// Buffered bytes are served first; once drained, reads are delegated
180/// directly to the underlying stream.
181impl AsyncRead for PooledReader<'_> {
182    /// Polls to read data into the provided buffer.
183    ///
184    /// # Arguments
185    ///
186    /// - `Pin<&mut Self>` - The pinned reader.
187    /// - `&mut Context<'_>` - The task context.
188    /// - `&mut ReadBuf<'_>` - The destination buffer.
189    ///
190    /// # Returns
191    ///
192    /// - `Poll<io::Result<()>>` - Ready when data was read or an error occurred.
193    fn poll_read(
194        self: Pin<&mut Self>,
195        cx: &mut Context<'_>,
196        buf: &mut ReadBuf<'_>,
197    ) -> Poll<io::Result<()>> {
198        let this: &mut Self = self.get_mut();
199        if this.get_start() < this.get_end() {
200            let available: usize = this.get_end() - this.get_start();
201            let amount: usize = available.min(buf.remaining());
202            let end: usize = this.get_start() + amount;
203            buf.put_slice(&this.get_buffer()[this.get_start()..end]);
204            this.set_start(end);
205            return Poll::Ready(Ok(()));
206        }
207        Pin::new(&mut **this.get_mut_stream()).poll_read(cx, buf)
208    }
209}
210
211/// Implements buffered-read support for `PooledReader`.
212///
213/// The internal buffer is refilled from the stream only when fully
214/// consumed, so a single socket read serves multiple line parses.
215impl AsyncBufRead for PooledReader<'_> {
216    /// Polls to fill the internal buffer and returns the available data.
217    ///
218    /// # Arguments
219    ///
220    /// - `Pin<&mut Self>` - The pinned reader.
221    /// - `&mut Context<'_>` - The task context.
222    ///
223    /// # Returns
224    ///
225    /// - `Poll<io::Result<&[u8]>>` - Ready with the unconsumed bytes, or an error.
226    fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
227        let this: &mut Self = self.get_mut();
228        let PooledReader {
229            stream,
230            buffer,
231            start,
232            end,
233        } = this;
234        if *start >= *end {
235            *start = 0;
236            *end = 0;
237            let mut read_buf: ReadBuf<'_> = ReadBuf::new(buffer);
238            match Pin::new(&mut **stream).poll_read(cx, &mut read_buf) {
239                Poll::Ready(Ok(())) => {
240                    *end = read_buf.filled().len();
241                }
242                Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
243                Poll::Pending => return Poll::Pending,
244            }
245        }
246        Poll::Ready(Ok(&buffer[*start..*end]))
247    }
248
249    /// Marks the given number of bytes as consumed.
250    ///
251    /// # Arguments
252    ///
253    /// - `Pin<&mut Self>` - The pinned reader.
254    /// - `usize` - The number of bytes to consume.
255    fn consume(self: Pin<&mut Self>, amount: usize) {
256        let this: &mut Self = self.get_mut();
257        let new_start: usize = (this.get_start() + amount).min(this.get_end());
258        this.set_start(new_start);
259    }
260}
261
262/// Inherent implementation of [`Stream`].
263impl Stream {
264    /// Boxes a transport into a `Stream` for the request pipeline.
265    ///
266    /// This is the single construction path: a plain TCP socket, a TLS session
267    /// and a per-request duplex stream all enter here, so nothing above the
268    /// transport line has to know which one it is serving. The transport is
269    /// type erased immediately, which keeps `Stream` a fixed size regardless of
270    /// the concrete protocol adapter behind it.
271    ///
272    /// # Arguments
273    ///
274    /// - `T` - The transport type to serve the request cycle over.
275    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
276    /// - `bool` - Whether the connection starts already closed.
277    ///
278    /// # Returns
279    ///
280    /// - `Self` - A stream serving bytes through the boxed transport.
281    pub fn from_transport<T>(transport: T, request_config: RequestConfig, closed: bool) -> Self
282    where
283        T: Transport + 'static,
284    {
285        Self {
286            stream: Box::new(transport),
287            request_config,
288            closed,
289            leftover: Vec::new(),
290            leftover_start: 0,
291            leftover_end: 0,
292        }
293    }
294
295    /// Boxes a TCP socket into a `Stream` for the request pipeline.
296    ///
297    /// Kept as the socket-facing constructor so the accept loop keeps its
298    /// existing call shape; it delegates to `from_transport`, so there is one
299    /// construction path rather than two.
300    ///
301    /// # Arguments
302    ///
303    /// - `TcpStream` - The accepted socket to serve the request cycle over.
304    /// - `RequestConfig` - The parsing limits and read timeout for the cycle.
305    /// - `bool` - Whether the connection starts already closed.
306    ///
307    /// # Returns
308    ///
309    /// - `Self` - A stream serving bytes through the boxed socket.
310    pub fn new(stream: TcpStream, request_config: RequestConfig, closed: bool) -> Self {
311        Self::from_transport(stream, request_config, closed)
312    }
313
314    /// Reports the address of the remote end of the transport.
315    ///
316    /// Delegates to the transport itself, so a transport without a socket
317    /// identity answers with an error rather than a fabricated address.
318    ///
319    /// # Returns
320    ///
321    /// - `Result<SocketAddr, io::Error>` - The peer address reported by the transport.
322    #[inline(always)]
323    pub fn get_peer_addr(&self) -> Result<SocketAddr, io::Error> {
324        self.get_stream().peer_addr()
325    }
326
327    /// Reports the address of the local end of the transport.
328    ///
329    /// Delegates to the transport itself, so a transport without a socket
330    /// identity answers with an error rather than a fabricated address.
331    ///
332    /// # Returns
333    ///
334    /// - `Result<SocketAddr, io::Error>` - The local address reported by the transport.
335    #[inline(always)]
336    pub fn get_local_addr(&self) -> Result<SocketAddr, io::Error> {
337        self.get_stream().local_addr()
338    }
339
340    /// Checks if the connection should be kept alive.
341    ///
342    /// This method evaluates whether the connection should remain open based on
343    /// the closed state and the keep_alive parameter.
344    ///
345    /// # Arguments
346    ///
347    /// - `bool` - Whether keep-alive is enabled for the request.
348    ///
349    /// # Returns
350    ///
351    /// - `bool` - True if the connection should be kept alive, otherwise false.
352    #[inline(always)]
353    pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
354        !self.get_closed() && keep_alive
355    }
356
357    /// Parses the HTTP request content from the stream into the given request.
358    ///
359    /// The request is reset first, then filled in place so its existing
360    /// allocations are reused across keep-alive requests.
361    ///
362    /// # Arguments
363    ///
364    /// - `&mut Request` - The request object to fill.
365    ///
366    /// # Returns
367    ///
368    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
369    async fn fill_http_from_stream(&mut self, request: &mut Request) -> Result<(), RequestError> {
370        request.reset();
371        let config: RequestConfig = *self.get_request_config();
372        let buffer_size: usize = config.get_buffer_size();
373        let max_path_size: usize = config.get_max_path_size();
374        // Take any bytes the previous request read ahead, BEFORE borrowing the
375        // socket: those bytes already left the socket and cannot be re-read, so
376        // dropping them would silently discard a pipelined request.
377        let seeded: Vec<u8> = {
378            let start: usize = self.get_leftover_start();
379            let end: usize = self.get_leftover_end();
380            let mut pending: Vec<u8> = Vec::new();
381            if start < end {
382                let leftover: Vec<u8> = mem::take(self.get_mut_leftover());
383                let take: usize = (end - start).min(leftover.len());
384                pending.extend_from_slice(&leftover[start..start + take]);
385            }
386            self.set_leftover(Vec::new());
387            self.set_leftover_start(0);
388            self.set_leftover_end(0);
389            pending
390        };
391        let buffer: Vec<u8> = take_read_buffer(buffer_size);
392        let mut reader: PooledReader<'_> = PooledReader::new(self.get_mut_stream(), buffer);
393        if !seeded.is_empty() {
394            let target: &mut Vec<u8> = reader.get_mut_buffer();
395            let copy_len: usize = seeded.len().min(target.len());
396            target[..copy_len].copy_from_slice(&seeded[..copy_len]);
397            reader.set_end(copy_len);
398        }
399        let mut line: String = String::with_capacity(REQUEST_LINE_BUFFER_CAPACITY);
400        AsyncBufReadExt::read_line(&mut reader, &mut line).await?;
401        let (method, path, version): (RequestMethod, &str, RequestVersion) =
402            Request::get_http_first_line(&line)?;
403        Request::check_http_path_size(path, max_path_size)?;
404        let hash_index: Option<usize> = path.find(HASH);
405        let query_index: Option<usize> = path.find(QUERY);
406        let query: &str = Request::get_http_query(path, query_index, hash_index);
407        Request::fill_http_querys(query, request.get_mut_querys());
408        let path_slice: &str = Request::get_http_path(path, query_index, hash_index);
409        request.get_mut_path().push_str(path_slice);
410        let content_size: usize = request.get_http_headers(&mut reader, &config).await?;
411        request.set_method(method);
412        request.set_version(version);
413        Request::fill_http_body(&mut reader, request.get_mut_body(), content_size).await?;
414        // Preserve bytes read ahead for the next pipelined request: they have
415        // already left the socket and cannot be read again.
416        let reader_start: usize = reader.get_start();
417        let reader_end: usize = reader.get_end();
418        let pending: Vec<u8> = if reader_start < reader_end {
419            reader.get_buffer()[reader_start..reader_end].to_vec()
420        } else {
421            Vec::new()
422        };
423        drop(reader);
424        let pending_len: usize = pending.len();
425        self.set_leftover(pending);
426        self.set_leftover_start(0);
427        self.set_leftover_end(pending_len);
428        Ok(())
429    }
430
431    /// Parses an HTTP request from a TCP stream into the given request.
432    ///
433    /// The request is reset and filled in place, reusing its allocations.
434    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
435    ///
436    /// # Arguments
437    ///
438    /// - `&mut Request` - The request object to reset and fill.
439    ///
440    /// # Returns
441    ///
442    /// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
443    pub async fn try_fill_http_request(
444        &mut self,
445        request: &mut Request,
446    ) -> Result<(), RequestError> {
447        if self.get_closed() {
448            return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
449        }
450        let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
451        if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
452            return self.fill_http_from_stream(request).await;
453        }
454        let duration: Duration = Duration::from_millis(timeout_ms);
455        timeout(duration, self.fill_http_from_stream(request)).await?
456    }
457
458    /// Parses an HTTP request from a TCP stream.
459    ///
460    /// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
461    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
462    ///
463    /// # Returns
464    ///
465    /// - `Result<Request, RequestError>` - The parsed request or an error.
466    pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
467        let mut request: Request = Request::default();
468        self.try_fill_http_request(&mut request).await?;
469        Ok(request)
470    }
471
472    /// Parses a WebSocket request from a TCP stream.
473    ///
474    /// Wraps the stream in a buffered reader and delegates to `ws_from_reader`.
475    /// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
476    ///
477    /// # Returns
478    ///
479    /// - `Result<RequestBody, RequestError>` - The parsed WebSocket request or an error.
480    pub async fn try_get_websocket_request(&mut self) -> Result<RequestBody, RequestError> {
481        if self.get_closed() {
482            return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
483        }
484        let config: RequestConfig = *self.get_request_config();
485        let buffer_size: usize = config.get_buffer_size();
486        let read_timeout_ms: u64 = config.get_read_timeout_ms();
487        let mut dynamic_buffer: Vec<u8> = Vec::with_capacity(buffer_size);
488        let mut temp_buffer: Vec<u8> = vec![0; buffer_size];
489        let mut full_frame: Vec<u8> = Vec::new();
490        let mut is_client_response: bool = false;
491        let duration_opt: Option<Duration> =
492            if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
493                None
494            } else {
495                let adjusted_timeout_ms: u64 = (read_timeout_ms >> 1) + (read_timeout_ms & 1);
496                Some(Duration::from_millis(adjusted_timeout_ms))
497            };
498        loop {
499            let len: usize = match self
500                .get_websocket_from_stream(&mut temp_buffer, duration_opt, &mut is_client_response)
501                .await
502            {
503                Ok(Some(len)) => len,
504                Ok(None) => continue,
505                Err(error) => return Err(error),
506            };
507            if len == 0 {
508                return Err(RequestError::IncompleteWebSocketFrame(
509                    HttpStatus::BadRequest,
510                ));
511            }
512            dynamic_buffer.extend_from_slice(&temp_buffer[..len]);
513            while let Some((frame, consumed)) = WebSocketFrame::decode_ws_frame(&dynamic_buffer) {
514                is_client_response = true;
515                dynamic_buffer.drain(0..consumed);
516                match frame.get_opcode() {
517                    WebSocketOpcode::Close => {
518                        return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
519                    }
520                    WebSocketOpcode::Ping | WebSocketOpcode::Pong => continue,
521                    WebSocketOpcode::Text | WebSocketOpcode::Binary => {
522                        match frame.build_full_frame(&mut full_frame) {
523                            Ok(Some(result)) => return Ok(result),
524                            Ok(None) => continue,
525                            Err(error) => return Err(error),
526                        }
527                    }
528                    _ => {
529                        return Err(RequestError::WebSocketOpcodeUnsupported(
530                            HttpStatus::NotImplemented,
531                        ));
532                    }
533                }
534            }
535        }
536    }
537
538    /// Reads data from the stream with optional timeout handling.
539    ///
540    /// # Arguments
541    ///
542    /// - `&mut [u8]` - The buffer to read data into.
543    /// - `Option<Duration>` - The optional timeout duration. If Some, timeout is applied; if None, no timeout.
544    /// - `&mut bool` - Mutable reference to track if we got a client response.
545    ///
546    /// # Returns
547    ///
548    /// - `Result<Option<usize>, RequestError>` - The number of bytes read, None for timeout/ping, or an error.
549    pub(crate) async fn get_websocket_from_stream(
550        &mut self,
551        buffer: &mut [u8],
552        duration_opt: Option<Duration>,
553        is_client_response: &mut bool,
554    ) -> Result<Option<usize>, RequestError> {
555        let stream: &mut Box<dyn Transport> = self.get_mut_stream();
556        if let Some(duration) = duration_opt {
557            return match timeout(duration, stream.read(buffer)).await {
558                Ok(result) => match result {
559                    Ok(len) => Ok(Some(len)),
560                    Err(error) => Err(error.into()),
561                },
562                Err(error) => {
563                    if !*is_client_response {
564                        return Err(error.into());
565                    }
566                    *is_client_response = false;
567                    self.try_send(&PING_FRAME).await?;
568                    Ok(None)
569                }
570            };
571        }
572        match stream.read(buffer).await {
573            Ok(len) => Ok(Some(len)),
574            Err(error) => Err(error.into()),
575        }
576    }
577
578    /// Sends data over the stream.
579    ///
580    /// # Arguments
581    ///
582    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
583    ///
584    /// # Returns
585    ///
586    /// - `Result<(), ResponseError>` - Result indicating success or failure.
587    pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
588    where
589        D: AsRef<[u8]>,
590    {
591        if self.get_closed() {
592            return Err(ResponseError::ConnectionClosed);
593        }
594        Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
595    }
596
597    /// Sends data over the stream.
598    ///
599    /// # Arguments
600    ///
601    /// - `D` - The data to send, which must implement `AsRef<[u8]>`.
602    ///
603    /// # Panics
604    ///
605    /// Panics if the write operation fails.
606    pub async fn send<D>(&mut self, data: D)
607    where
608        D: AsRef<[u8]>,
609    {
610        self.try_send(data).await.unwrap();
611    }
612
613    /// Sends multiple data.
614    ///
615    /// # Arguments
616    ///
617    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
618    ///   `D` requiring the `AsRef<[u8]>` bound.
619    ///
620    /// # Returns
621    ///
622    /// - `Result<(), ResponseError>` - Result indicating success or failure.
623    pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
624    where
625        I: IntoIterator<Item = D>,
626        D: AsRef<[u8]>,
627    {
628        if self.get_closed() {
629            return Err(ResponseError::ConnectionClosed);
630        }
631        let stream: &mut Box<dyn Transport> = self.get_mut_stream();
632        for data in data_iter {
633            stream.write_all(data.as_ref()).await?;
634        }
635        Ok(())
636    }
637
638    /// Sends multiple data.
639    ///
640    /// # Arguments
641    ///
642    /// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
643    ///   `D` requiring the `AsRef<[u8]>` bound.
644    ///
645    /// # Panics
646    ///
647    /// Panics if any write operation fails.
648    pub async fn send_list<I, D>(&mut self, data_iter: I)
649    where
650        I: IntoIterator<Item = D>,
651        D: AsRef<[u8]>,
652    {
653        self.try_send_list(data_iter).await.unwrap();
654    }
655
656    /// Flushes all buffered data to the stream.
657    ///
658    /// # Returns
659    ///
660    /// - `Result<(), ResponseError>` - Result indicating success or failure.
661    pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
662        if self.get_closed() {
663            return Err(ResponseError::ConnectionClosed);
664        }
665        Ok(self.get_mut_stream().flush().await?)
666    }
667
668    /// Flushes all buffered data to the stream.
669    ///
670    /// # Panics
671    ///
672    /// Panics if the flush operation fails.
673    pub async fn flush(&mut self) {
674        self.try_flush().await.unwrap();
675    }
676}