hyperlane-core 23.4.0

A lightweight, high-performance, and cross-platform Rust HTTP server library built on Tokio. It simplifies modern web service development by providing built-in support for middleware, WebSocket, Server-Sent Events (SSE), and raw TCP communication. With a unified and ergonomic API across Windows, Linux, and MacOS, it enables developers to build robust, scalable, and event-driven network applications with minimal overhead and maximum flexibility.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
use super::*;

/// Inherent implementation of [`H2BodyBuf`].
impl H2BodyBuf {
    /// Creates an empty HTTP/2 DATA payload buffer.
    ///
    /// # Returns
    ///
    /// - `Self` - An empty [`H2BodyBuf`].
    #[inline(always)]
    pub(super) fn empty() -> Self {
        Self::Empty
    }

    /// Copies a response body slice into an inline or pooled HTTP/2 DATA buffer.
    ///
    /// # Arguments
    ///
    /// - `&[u8]` - The response body slice to copy.
    ///
    /// # Returns
    ///
    /// - `Self` - An inline buffer for small payloads or a pooled buffer for larger ones.
    #[inline(always)]
    pub(super) fn from_slice(bytes: &[u8]) -> Self {
        let len: usize = bytes.len();
        if len == 0 {
            return Self::Empty;
        }
        if len <= H2_INLINE_BODY_CAP {
            let mut data: [MaybeUninit<u8>; H2_INLINE_BODY_CAP] =
                [const { MaybeUninit::uninit() }; H2_INLINE_BODY_CAP];
            // SAFETY: `len <= H2_INLINE_BODY_CAP` and `MaybeUninit<u8>` has identical layout to `u8`.
            unsafe {
                ptr::copy_nonoverlapping(bytes.as_ptr(), data.as_mut_ptr().cast::<u8>(), len);
            }
            return Self::Inline {
                data,
                pos: 0,
                len: len as u8,
            };
        }
        let mut buf: Vec<u8> = H2_BODY_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
            pool.borrow_mut()
                .pop()
                .unwrap_or_else(|| Vec::with_capacity(len))
        });
        buf.clear();
        buf.extend_from_slice(bytes);
        Self::Pooled { buf, pos: 0 }
    }
}

/// Implements [`Buf`] for [`H2BodyBuf`].
impl Buf for H2BodyBuf {
    /// Reports the number of unread bytes remaining in this buffer.
    ///
    /// # Returns
    ///
    /// - `usize` - Remaining byte count.
    #[inline(always)]
    fn remaining(&self) -> usize {
        match self {
            Self::Empty => 0,
            Self::Inline { pos, len, .. } => usize::from(*len - *pos),
            Self::Pooled { buf, pos } => buf.len() - *pos,
        }
    }

    /// Returns the currently readable contiguous slice.
    ///
    /// # Returns
    ///
    /// - `&[u8]` - Remaining bytes ready for HTTP/2 framing.
    #[inline(always)]
    fn chunk(&self) -> &[u8] {
        match self {
            Self::Empty => &[],
            Self::Inline { data, pos, len } => {
                let start: usize = usize::from(*pos);
                let end: usize = usize::from(*len);
                // SAFETY: `data[0..end]` was initialized in `from_slice`, and `start <= end <= H2_INLINE_BODY_CAP`.
                unsafe { slice::from_raw_parts(data.as_ptr().cast::<u8>().add(start), end - start) }
            }
            Self::Pooled { buf, pos } => &buf[*pos..],
        }
    }

    /// Advances the internal read cursor by `cnt` bytes.
    ///
    /// # Arguments
    ///
    /// - `usize` - Number of bytes consumed by the HTTP/2 framer.
    #[inline(always)]
    fn advance(&mut self, cnt: usize) {
        match self {
            Self::Empty => {}
            Self::Inline { pos, len, .. } => {
                let step: usize = cnt.min(usize::from(*len - *pos));
                *pos += step as u8;
            }
            Self::Pooled { buf, pos } => {
                let step: usize = cnt.min(buf.len() - *pos);
                *pos += step;
            }
        }
    }
}

/// Implements [`fmt::Debug`] for [`H2BodyBuf`].
impl fmt::Debug for H2BodyBuf {
    /// Formats the remaining payload length for diagnostics.
    ///
    /// # Arguments
    ///
    /// - `&mut fmt::Formatter<'_>` - The destination formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting result.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("H2BodyBuf")
            .field("remaining", &self.remaining())
            .finish()
    }
}

/// Returns pooled heap storage back to [`H2_BODY_POOL`] when a large DATA buffer drops.
impl Drop for H2BodyBuf {
    /// Recycles bounded backing vectors into the worker-local pool.
    fn drop(&mut self) {
        if let Self::Pooled { buf, .. } = self {
            let mut owned: Vec<u8> = mem::take(buf);
            if owned.capacity() > 0 && owned.capacity() <= MAX_POOLED_BUFFER_CAPACITY {
                owned.clear();
                H2_BODY_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
                    let mut pool: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
                    if pool.len() < MAX_POOLED_H2_BODIES {
                        pool.push(owned);
                    }
                });
            }
        }
    }
}

/// Inherent implementation of [`H2DirectState`].
impl H2DirectState {
    /// Reinitializes pooled state for a new HTTP/2 request stream while retaining buffer capacity.
    ///
    /// # Arguments
    ///
    /// - `SendResponse<H2BodyBuf>` - The response half of the new HTTP/2 stream.
    /// - `bool` - Whether the incoming request method was `HEAD`.
    /// - `HeaderMap` - Cleared `HeaderMap` recycled from the incoming request.
    #[inline(always)]
    pub(super) fn reinit(
        &mut self,
        send_response: SendResponse<H2BodyBuf>,
        is_head: bool,
        mut incoming_headers: HeaderMap,
    ) {
        self.set_send_response(Some(send_response));
        self.set_send_stream(None);
        self.get_mut_pending_head().clear();
        self.get_mut_pending_body().clear();
        self.set_pending_body_offset(0);
        self.set_head_sent(false);
        self.set_suppress_body(is_head);
        self.set_is_head(is_head);
        self.set_announced_len(None);
        self.set_body_len(0);
        self.set_finished(false);
        self.set_failed(false);
        self.set_direct_inflight(false);
        let inc_cap: usize = incoming_headers.capacity();
        if inc_cap > 0 && inc_cap <= H2_RECYCLED_HEADER_CAP {
            incoming_headers.clear();
            self.set_recycled_headers(incoming_headers);
        }
    }

    /// Cleans up stream handles and trims oversized buffers before returning state to the pool.
    #[inline(always)]
    pub(super) fn release(&mut self) {
        if !self.get_finished() {
            self.reset();
        }
        let _: Option<SendResponse<H2BodyBuf>> = self.get_mut_send_response().take();
        let _: Option<h2::SendStream<H2BodyBuf>> = self.get_mut_send_stream().take();
        if self.get_pending_head().capacity() > MAX_POOLED_BUFFER_CAPACITY {
            self.set_pending_head(Vec::new());
        } else {
            self.get_mut_pending_head().clear();
        }
        if self.get_pending_body().capacity() > MAX_POOLED_BUFFER_CAPACITY {
            self.set_pending_body(Vec::new());
        } else {
            self.get_mut_pending_body().clear();
        }
        self.set_pending_body_offset(0);
        self.set_direct_inflight(false);
        let recycled: &mut HeaderMap = self.get_mut_recycled_headers();
        if recycled.capacity() > H2_RECYCLED_HEADER_CAP {
            *recycled = HeaderMap::new();
        } else {
            recycled.clear();
        }
    }

    /// Resets the underlying HTTP/2 stream after a framing error or truncation.
    pub(super) fn reset(&mut self) {
        if let Some(mut send_response) = self.get_mut_send_response().take() {
            send_response.send_reset(Reason::INTERNAL_ERROR);
        }
        if let Some(mut send_stream) = self.get_mut_send_stream().take() {
            send_stream.send_reset(Reason::INTERNAL_ERROR);
        }
        self.set_finished(true);
    }

    /// Marks the stream failed, resets it, and builds an I/O error.
    ///
    /// # Arguments
    ///
    /// - `&str` - The error message to report.
    ///
    /// # Returns
    ///
    /// - `io::Error` - The wrapped framing error.
    pub(super) fn fail(&mut self, message: &str) -> io::Error {
        self.set_failed(true);
        self.reset();
        io::Error::other(message.to_owned())
    }

    /// Drains any buffered trailing body bytes extracted after a split head.
    ///
    /// # Arguments
    ///
    /// - `&mut task::Context<'_>` - The task context for flow-control backpressure.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<()>>` - Ready once all buffered body bytes are sent.
    pub(super) fn poll_drain_pending_body(
        &mut self,
        context: &mut task::Context<'_>,
    ) -> Poll<io::Result<()>> {
        while self.get_pending_body_offset() < self.get_pending_body().len() {
            if self.get_suppress_body() {
                self.get_mut_pending_body().clear();
                self.set_pending_body_offset(0);
                return Poll::Ready(Ok(()));
            }
            let remaining: usize = self.get_pending_body().len() - self.get_pending_body_offset();
            let capacity: Poll<Option<Result<usize, h2::Error>>> = {
                let Some(send_stream) = self.get_mut_send_stream().as_mut() else {
                    return Poll::Ready(Err(self.fail(MISSING_SEND_CAPACITY)));
                };
                send_stream.reserve_capacity(remaining);
                send_stream.poll_capacity(context)
            };
            match capacity {
                Poll::Ready(Some(Ok(capacity))) if capacity > 0 => {
                    let take: usize = capacity.min(remaining);
                    let start: usize = self.get_pending_body_offset();
                    let end: usize = start + take;
                    let new_len: usize = self.get_body_len() + take;
                    let is_final: bool = self.try_get_announced_len() == Some(new_len);
                    let chunk: H2BodyBuf =
                        H2BodyBuf::from_slice(&self.get_pending_body()[start..end]);
                    let Some(send_stream) = self.get_mut_send_stream().as_mut() else {
                        return Poll::Ready(Err(self.fail(MISSING_SEND_CAPACITY)));
                    };
                    if let Err(error) = send_stream.send_data(chunk, is_final) {
                        return Poll::Ready(Err(self.fail(&error.to_string())));
                    }
                    self.set_body_len(new_len);
                    self.set_pending_body_offset(end);
                    if is_final {
                        self.set_finished(true);
                        let _: Option<h2::SendStream<H2BodyBuf>> =
                            self.get_mut_send_stream().take();
                    }
                }
                Poll::Ready(Some(Ok(_))) => continue,
                Poll::Ready(Some(Err(error))) => {
                    return Poll::Ready(Err(self.fail(&error.to_string())));
                }
                Poll::Ready(None) => {
                    return Poll::Ready(Err(self.fail(MISSING_SEND_CAPACITY)));
                }
                Poll::Pending => return Poll::Pending,
            }
        }
        self.get_mut_pending_body().clear();
        self.set_pending_body_offset(0);
        Poll::Ready(Ok(()))
    }

    /// Emits an already-parsed response head, optionally forwarding inline body bytes.
    ///
    /// # Arguments
    ///
    /// - `&mut task::Context<'_>` - The task context for flow-control backpressure.
    /// - `ParsedProtocolHead` - The parsed and validated protocol response head.
    /// - `&[u8]` - Any body bytes already present in the same write.
    ///
    /// # Returns
    ///
    /// - `io::Result<usize>` - Number of inline body bytes consumed directly.
    #[inline(always)]
    pub(super) fn emit_parsed_head_and_inline_body(
        &mut self,
        context: &mut task::Context<'_>,
        parsed: ParsedProtocolHead,
        body_bytes: &[u8],
    ) -> io::Result<usize> {
        self.set_announced_len(parsed.announced_len);
        self.set_suppress_body(parsed.suppress_body);
        let Some(mut send_response) = self.get_mut_send_response().take() else {
            return Err(self.fail("response head already sent"));
        };
        if parsed.suppress_body {
            if let Err(error) = send_response.send_response(parsed.response, true) {
                return Err(self.fail(&error.to_string()));
            }
            self.set_head_sent(true);
            self.set_finished(true);
            return Ok(body_bytes.len());
        }
        if check_body_budget(self.try_get_announced_len(), 0, body_bytes.len()) {
            send_response.send_reset(Reason::INTERNAL_ERROR);
            return Err(self.fail(OVERFLOWING_RESPONSE_BODY));
        }
        if parsed.announced_len == Some(0) && body_bytes.is_empty() {
            if let Err(error) = send_response.send_response(parsed.response, true) {
                return Err(self.fail(&error.to_string()));
            }
            self.set_head_sent(true);
            self.set_finished(true);
            return Ok(0);
        }
        let mut send_stream: h2::SendStream<H2BodyBuf> =
            match send_response.send_response(parsed.response, false) {
                Ok(stream) => stream,
                Err(error) => return Err(self.fail(&error.to_string())),
            };
        self.set_head_sent(true);
        if body_bytes.is_empty() {
            self.set_send_stream(Some(send_stream));
            return Ok(0);
        }
        send_stream.reserve_capacity(body_bytes.len());
        match send_stream.poll_capacity(context) {
            Poll::Ready(Some(Ok(capacity))) if capacity > 0 => {
                let take: usize = capacity.min(body_bytes.len());
                let is_final: bool = self.try_get_announced_len() == Some(take);
                let chunk: H2BodyBuf = H2BodyBuf::from_slice(&body_bytes[..take]);
                if let Err(error) = send_stream.send_data(chunk, is_final) {
                    return Err(self.fail(&error.to_string()));
                }
                self.set_body_len(take);
                if is_final {
                    self.set_finished(true);
                } else {
                    self.set_send_stream(Some(send_stream));
                }
                Ok(take)
            }
            Poll::Ready(Some(Ok(_))) | Poll::Pending => {
                self.set_send_stream(Some(send_stream));
                Ok(0)
            }
            Poll::Ready(Some(Err(error))) => Err(self.fail(&error.to_string())),
            Poll::Ready(None) => Err(self.fail(MISSING_SEND_CAPACITY)),
        }
    }

    /// Parses and emits the response head, optionally forwarding inline body bytes.
    ///
    /// # Arguments
    ///
    /// - `&mut task::Context<'_>` - The task context for flow-control backpressure.
    /// - `&[u8]` - The serialized head bytes up to and including the blank line.
    /// - `&[u8]` - Any body bytes already present in the same write.
    ///
    /// # Returns
    ///
    /// - `io::Result<usize>` - Number of inline body bytes consumed directly.
    pub(super) fn emit_head_and_inline_body(
        &mut self,
        context: &mut task::Context<'_>,
        head_bytes: &[u8],
        body_bytes: &[u8],
    ) -> io::Result<usize> {
        let is_head: bool = self.get_is_head();
        let parsed: ParsedProtocolHead = match parse_protocol_response_head(
            head_bytes,
            is_head,
            self.get_mut_recycled_headers(),
        ) {
            Ok(parsed) => parsed,
            Err(error) => return Err(self.fail(&error.to_string())),
        };
        self.emit_parsed_head_and_inline_body(context, parsed, body_bytes)
    }
}

/// Inherent implementation of [`H2DirectTransport`].
impl H2DirectTransport {
    /// Creates a direct HTTP/2 transport owning its framing state inline.
    ///
    /// # Arguments
    ///
    /// - `StreamPeers` - Local and remote addresses of the carrying TCP connection.
    /// - `H2DirectState` - Direct framing state for this stream.
    ///
    /// # Returns
    ///
    /// - `Self` - The direct HTTP/2 transport.
    #[inline(always)]
    pub(crate) fn new(peers: StreamPeers, state: H2DirectState) -> Self {
        Self { peers, state }
    }

    /// Reinitializes this transport in place for a new HTTP/2 request stream.
    ///
    /// # Arguments
    ///
    /// - `SendResponse<H2BodyBuf>` - The response half of the new stream.
    /// - `StreamPeers` - Local and remote addresses of the carrying TCP connection.
    /// - `bool` - Whether the incoming request method was `HEAD`.
    /// - `HeaderMap` - Cleared `HeaderMap` recycled from the incoming request.
    #[inline(always)]
    pub(super) fn reinit(
        &mut self,
        send_response: SendResponse<H2BodyBuf>,
        peers: StreamPeers,
        is_head: bool,
        recycled_headers: HeaderMap,
    ) {
        let Self {
            peers: slot_peers,
            state,
        } = self;
        *slot_peers = peers;
        state.reinit(send_response, is_head, recycled_headers);
    }
}

// SAFETY: `H2DirectTransport` is `Send`, and every `&self` method (`Debug`, `peer_addr`,
// `local_addr`, `supports_direct_response`) accesses only `self.peers` (`Copy + Send + Sync`);
// `self.state` is accessed exclusively through `&mut self`.
unsafe impl Sync for H2DirectTransport {}

/// Implements [`fmt::Debug`] for [`H2DirectTransport`].
impl fmt::Debug for H2DirectTransport {
    /// Formats the direct HTTP/2 transport without touching mutable framing state.
    ///
    /// # Arguments
    ///
    /// - `&mut fmt::Formatter<'_>` - The formatter to write into.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - The formatting result.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("H2DirectTransport")
            .field("peers", &self.peers)
            .finish()
    }
}

/// Inherent implementation of [`H2StreamGuard`].
impl H2StreamGuard {
    /// Takes a pooled boxed HTTP/2 `Stream` (or allocates one on first use) and binds it to the request stream.
    ///
    /// # Arguments
    ///
    /// - `SendResponse<H2BodyBuf>` - The response half of the HTTP/2 stream.
    /// - `StreamPeers` - The local and remote addresses of the carrying TCP connection.
    /// - `RequestConfig` - The active request limits for the stream.
    /// - `bool` - Whether the incoming request method was `HEAD`.
    /// - `HeaderMap` - Cleared `HeaderMap` recycled from the incoming request.
    ///
    /// # Returns
    ///
    /// - `Self` - Guard owning the ready `Stream` until dropped.
    #[inline(always)]
    pub(crate) fn take(
        send_response: SendResponse<H2BodyBuf>,
        peers: StreamPeers,
        request_config: RequestConfig,
        is_head: bool,
        mut recycled_headers: HeaderMap,
    ) -> Self {
        let pooled: Option<Stream> =
            H2_STREAM_POOL.with(|pool: &RefCell<Vec<PooledH2Stream>>| pool.borrow_mut().pop());
        let stream: Stream = match pooled {
            Some(mut stream) if *stream.get_request_config() == request_config => {
                if let Some(transport) = stream
                    .get_mut_stream()
                    .as_any_mut()
                    .and_then(|any: &mut dyn Any| any.downcast_mut::<H2DirectTransport>())
                {
                    transport.reinit(send_response, peers, is_head, recycled_headers);
                    stream.clear_cached_addrs();
                    stream.set_closed(false);
                    return Self {
                        inner: Some(stream),
                    };
                }
                let retained: HeaderMap = if recycled_headers.capacity() <= H2_RECYCLED_HEADER_CAP {
                    recycled_headers.clear();
                    recycled_headers
                } else {
                    HeaderMap::new()
                };
                Stream::from_transport(
                    H2DirectTransport::new(
                        peers,
                        H2DirectState {
                            send_response: Some(send_response),
                            send_stream: None,
                            pending_head: Vec::new(),
                            pending_body: Vec::new(),
                            pending_body_offset: 0,
                            head_sent: false,
                            suppress_body: is_head,
                            is_head,
                            announced_len: None,
                            body_len: 0,
                            finished: false,
                            failed: false,
                            direct_inflight: false,
                            recycled_headers: retained,
                        },
                    ),
                    request_config,
                    false,
                )
            }
            _ => {
                let retained: HeaderMap = if recycled_headers.capacity() <= H2_RECYCLED_HEADER_CAP {
                    recycled_headers.clear();
                    recycled_headers
                } else {
                    HeaderMap::new()
                };
                Stream::from_transport(
                    H2DirectTransport::new(
                        peers,
                        H2DirectState {
                            send_response: Some(send_response),
                            send_stream: None,
                            pending_head: Vec::new(),
                            pending_body: Vec::new(),
                            pending_body_offset: 0,
                            head_sent: false,
                            suppress_body: is_head,
                            is_head,
                            announced_len: None,
                            body_len: 0,
                            finished: false,
                            failed: false,
                            direct_inflight: false,
                            recycled_headers: retained,
                        },
                    ),
                    request_config,
                    false,
                )
            }
        };
        Self {
            inner: Some(stream),
        }
    }

    /// Returns a mutable reference to the pooled `Stream`.
    ///
    /// # Returns
    ///
    /// - `Option<&mut Stream>` - The active HTTP/2 stream wrapper, or `None` once finalized.
    #[inline(always)]
    pub(crate) fn stream_mut(&mut self) -> Option<&mut Stream> {
        let Self { inner } = self;
        inner.as_mut()
    }

    /// Finalizes the HTTP/2 stream if end-of-stream was not yet emitted, then recycles it.
    #[inline(always)]
    pub(crate) async fn finish(mut self) {
        let Self { inner } = &mut self;
        let Some(mut stream) = inner.take() else {
            return;
        };
        let already_finished: bool = match stream
            .get_mut_stream()
            .as_any_mut()
            .and_then(|any: &mut dyn Any| any.downcast_mut::<H2DirectTransport>())
        {
            Some(transport) if transport.state.finished && !transport.state.failed => {
                transport.state.release();
                true
            }
            Some(_) => false,
            None => return,
        };
        if !already_finished {
            let _: Result<(), io::Error> = stream.get_mut_stream().shutdown().await;
            if let Some(transport) = stream
                .get_mut_stream()
                .as_any_mut()
                .and_then(|any: &mut dyn Any| any.downcast_mut::<H2DirectTransport>())
            {
                transport.state.release();
            } else {
                return;
            }
        }
        stream.set_closed(false);
        H2_STREAM_POOL.with(|pool: &RefCell<Vec<PooledH2Stream>>| {
            let mut pool: RefMut<'_, Vec<Stream>> = pool.borrow_mut();
            if pool.len() < MAX_POOLED_CONTEXTS {
                pool.push(stream);
            }
        });
    }
}

/// Returns the pooled HTTP/2 `Stream` to [`H2_STREAM_POOL`] after releasing stream handles.
impl Drop for H2StreamGuard {
    /// Resets any unfinished stream and recycles the boxed `Stream` wrapper.
    fn drop(&mut self) {
        let Self { inner } = self;
        let Some(mut stream) = inner.take() else {
            return;
        };
        if let Some(transport) = stream
            .get_mut_stream()
            .as_any_mut()
            .and_then(|any: &mut dyn Any| any.downcast_mut::<H2DirectTransport>())
        {
            transport.state.release();
        } else {
            return;
        }
        stream.set_closed(false);
        H2_STREAM_POOL.with(|pool: &RefCell<Vec<PooledH2Stream>>| {
            let mut pool: RefMut<'_, Vec<Stream>> = pool.borrow_mut();
            if pool.len() < MAX_POOLED_CONTEXTS {
                pool.push(stream);
            }
        });
    }
}

/// Ensures an unfinished HTTP/2 stream is reset if dropped before shutdown.
impl Drop for H2DirectTransport {
    /// Resets the stream when dropped before end-of-stream was emitted.
    fn drop(&mut self) {
        let Self { state, .. } = self;
        if !state.finished {
            state.reset();
        }
    }
}

/// Implements [`Transport`] for [`H2DirectTransport`].
impl Transport for H2DirectTransport {
    /// Reports the remote address of the carrying TCP connection.
    ///
    /// # Returns
    ///
    /// - `Result<SocketAddr, io::Error>` - The peer socket address.
    #[inline(always)]
    fn peer_addr(&self) -> Result<SocketAddr, io::Error> {
        let Self { peers, .. } = self;
        Ok(peers.remote)
    }

    /// Reports the local address of the carrying TCP connection.
    ///
    /// # Returns
    ///
    /// - `Result<SocketAddr, io::Error>` - The local socket address.
    #[inline(always)]
    fn local_addr(&self) -> Result<SocketAddr, io::Error> {
        let Self { peers, .. } = self;
        Ok(peers.local)
    }

    /// Exposes a mutable dynamic reference for pooled transport reuse.
    ///
    /// # Returns
    ///
    /// - `Option<&mut dyn Any>` - Mutable reference to `self`.
    #[inline(always)]
    fn as_any_mut(&mut self) -> Option<&mut dyn Any> {
        Some(self)
    }

    /// Reports support for direct structured [`Response`] emission without HTTP/1.1 serialization.
    ///
    /// # Returns
    ///
    /// - `bool` - Always `true` for [`H2DirectTransport`].
    #[inline(always)]
    fn supports_direct_response(&self) -> bool {
        true
    }

    /// Directly frames a [`Response`] onto the HTTP/2 stream without HTTP/1.1 wire serialization.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - The pinned transport.
    /// - `&mut task::Context<'_>` - The task context for flow-control backpressure.
    /// - `&mut Response` - The response to emit directly.
    /// - `bool` - Whether only the response head must be transmitted.
    ///
    /// # Returns
    ///
    /// - `Option<Poll<io::Result<()>>>` - Direct framing result, or `None` to fall back to wire serialization.
    fn poll_write_response(
        self: Pin<&mut Self>,
        context: &mut task::Context<'_>,
        response: &mut Response,
        is_head_call: bool,
    ) -> Option<Poll<io::Result<()>>> {
        let state: &mut H2DirectState = &mut self.get_mut().state;
        if state.failed {
            return Some(Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY))));
        }
        if state.direct_inflight {
            return Some(match state.poll_drain_pending_body(context) {
                Poll::Pending => Poll::Pending,
                Poll::Ready(res) => {
                    state.direct_inflight = false;
                    Poll::Ready(res)
                }
            });
        }
        if state.head_sent
            || !state.pending_head.is_empty()
            || state.pending_body_offset < state.pending_body.len()
        {
            return None;
        }
        let req_is_head: bool = state.is_head;
        let parsed: ParsedProtocolHead = match build_h2_direct_head(
            response,
            is_head_call,
            req_is_head,
            &mut state.recycled_headers,
        )? {
            Ok(parsed) => parsed,
            Err(error) => return Some(Poll::Ready(Err(state.fail(&error.to_string())))),
        };
        let body: &[u8] = if parsed.suppress_body {
            &[]
        } else {
            response.get_body().as_slice()
        };
        let consumed: usize = match state.emit_parsed_head_and_inline_body(context, parsed, body) {
            Ok(consumed) => consumed,
            Err(error) => return Some(Poll::Ready(Err(error))),
        };
        if !state.suppress_body && consumed < body.len() {
            state.pending_body.clear();
            state.pending_body.extend_from_slice(&body[consumed..]);
            state.pending_body_offset = 0;
            state.direct_inflight = true;
            return Some(match state.poll_drain_pending_body(context) {
                Poll::Pending => Poll::Pending,
                Poll::Ready(res) => {
                    state.direct_inflight = false;
                    Poll::Ready(res)
                }
            });
        }
        Some(Poll::Ready(Ok(())))
    }
}

/// Implements [`AsyncRead`] for [`H2DirectTransport`].
impl AsyncRead for H2DirectTransport {
    /// Immediately signals EOF because request bodies are collected beforehand.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - The pinned transport.
    /// - `&mut task::Context<'_>` - The task context.
    /// - `&mut ReadBuf<'_>` - The destination read buffer.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<()>>` - Ready with zero bytes read.
    fn poll_read(
        self: Pin<&mut Self>,
        _context: &mut task::Context<'_>,
        buffer: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        buffer.advance(0);
        Poll::Ready(Ok(()))
    }
}

/// Implements [`AsyncWrite`] for [`H2DirectTransport`].
impl AsyncWrite for H2DirectTransport {
    /// Parses and frames written HTTP/1.1 bytes directly onto the HTTP/2 stream.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - The pinned transport.
    /// - `&mut task::Context<'_>` - The task context.
    /// - `&[u8]` - The bytes written by the handler or middleware.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<usize>>` - The number of bytes consumed.
    fn poll_write(
        self: Pin<&mut Self>,
        context: &mut task::Context<'_>,
        bytes: &[u8],
    ) -> Poll<io::Result<usize>> {
        let state: &mut H2DirectState = &mut self.get_mut().state;
        if state.failed {
            return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY)));
        }
        if state.pending_body_offset < state.pending_body.len() {
            match state.poll_drain_pending_body(context) {
                Poll::Ready(Ok(())) => {}
                Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
                Poll::Pending => return Poll::Pending,
            }
        }
        if bytes.is_empty() {
            return Poll::Ready(Ok(0));
        }
        if !state.head_sent {
            if state.pending_head.is_empty() {
                let is_head: bool = state.is_head;
                if let Some((parsed, body_start)) =
                    try_parse_fast_200_wire(bytes, is_head, &mut state.recycled_headers)
                {
                    let consumed_body: usize = match state.emit_parsed_head_and_inline_body(
                        context,
                        parsed,
                        &bytes[body_start..],
                    ) {
                        Ok(consumed) => consumed,
                        Err(error) => return Poll::Ready(Err(error)),
                    };
                    return Poll::Ready(Ok(body_start + consumed_body));
                }
                if let Some(body_start) = find_head_end(bytes) {
                    if body_start > RESPONSE_HEAD_MAX {
                        return Poll::Ready(Err(state.fail(RESPONSE_HEAD_TOO_LONG)));
                    }
                    let consumed_body: usize = match state.emit_head_and_inline_body(
                        context,
                        &bytes[..body_start],
                        &bytes[body_start..],
                    ) {
                        Ok(consumed) => consumed,
                        Err(error) => return Poll::Ready(Err(error)),
                    };
                    return Poll::Ready(Ok(body_start + consumed_body));
                }
                if bytes.len() > RESPONSE_HEAD_MAX {
                    return Poll::Ready(Err(state.fail(RESPONSE_HEAD_TOO_LONG)));
                }
                state.pending_head.extend_from_slice(bytes);
                return Poll::Ready(Ok(bytes.len()));
            }
            let accepted: usize = bytes
                .len()
                .min(RESPONSE_HEAD_MAX - state.pending_head.len());
            if accepted == 0 {
                return Poll::Ready(Err(state.fail(RESPONSE_HEAD_TOO_LONG)));
            }
            state.pending_head.extend_from_slice(&bytes[..accepted]);
            let Some(body_start) = find_head_end(&state.pending_head) else {
                if state.pending_head.len() > RESPONSE_HEAD_MAX {
                    return Poll::Ready(Err(state.fail(RESPONSE_HEAD_TOO_LONG)));
                }
                return Poll::Ready(Ok(accepted));
            };
            if body_start > RESPONSE_HEAD_MAX {
                return Poll::Ready(Err(state.fail(RESPONSE_HEAD_TOO_LONG)));
            }
            let pending_head: Vec<u8> = mem::take(&mut state.pending_head);
            let consumed_body: usize = match state.emit_head_and_inline_body(
                context,
                &pending_head[..body_start],
                &pending_head[body_start..],
            ) {
                Ok(consumed) => consumed,
                Err(error) => return Poll::Ready(Err(error)),
            };
            let trailing_start: usize = body_start + consumed_body;
            if !state.suppress_body && trailing_start < pending_head.len() {
                state
                    .pending_body
                    .extend_from_slice(&pending_head[trailing_start..]);
            }
            return Poll::Ready(Ok(accepted));
        }
        if state.suppress_body {
            return Poll::Ready(Ok(bytes.len()));
        }
        if check_body_budget(state.announced_len, state.body_len, bytes.len()) {
            return Poll::Ready(Err(state.fail(OVERFLOWING_RESPONSE_BODY)));
        }
        let current_body_len: usize = state.body_len;
        let announced_len: Option<usize> = state.announced_len;
        loop {
            let capacity: Poll<Option<Result<usize, h2::Error>>> = {
                let Some(send_stream) = state.send_stream.as_mut() else {
                    return Poll::Ready(Err(state.fail(OVERFLOWING_RESPONSE_BODY)));
                };
                send_stream.reserve_capacity(bytes.len());
                send_stream.poll_capacity(context)
            };
            match capacity {
                Poll::Ready(Some(Ok(capacity))) if capacity > 0 => {
                    let take: usize = capacity.min(bytes.len());
                    let new_len: usize = current_body_len + take;
                    let is_final: bool = announced_len == Some(new_len);
                    let chunk: H2BodyBuf = H2BodyBuf::from_slice(&bytes[..take]);
                    let Some(send_stream) = state.send_stream.as_mut() else {
                        return Poll::Ready(Err(state.fail(OVERFLOWING_RESPONSE_BODY)));
                    };
                    if let Err(error) = send_stream.send_data(chunk, is_final) {
                        return Poll::Ready(Err(state.fail(&error.to_string())));
                    }
                    state.body_len = new_len;
                    if is_final {
                        state.finished = true;
                        let _: Option<h2::SendStream<H2BodyBuf>> = state.send_stream.take();
                    }
                    return Poll::Ready(Ok(take));
                }
                Poll::Ready(Some(Ok(_))) => continue,
                Poll::Pending => return Poll::Pending,
                Poll::Ready(Some(Err(error))) => {
                    return Poll::Ready(Err(state.fail(&error.to_string())));
                }
                Poll::Ready(None) => {
                    return Poll::Ready(Err(state.fail(MISSING_SEND_CAPACITY)));
                }
            }
        }
    }

    /// Flushes any buffered trailing body bytes onto the HTTP/2 stream.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - The pinned transport.
    /// - `&mut task::Context<'_>` - The task context.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<()>>` - Ready once flushed.
    fn poll_flush(self: Pin<&mut Self>, context: &mut task::Context<'_>) -> Poll<io::Result<()>> {
        let state: &mut H2DirectState = &mut self.get_mut().state;
        if state.failed {
            return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY)));
        }
        state.poll_drain_pending_body(context)
    }

    /// Validates the completed response and emits the final EOS flag if needed.
    ///
    /// # Arguments
    ///
    /// - `Pin<&mut Self>` - The pinned transport.
    /// - `&mut task::Context<'_>` - The task context.
    ///
    /// # Returns
    ///
    /// - `Poll<io::Result<()>>` - Ready once finalized or reset on protocol violation.
    fn poll_shutdown(
        self: Pin<&mut Self>,
        context: &mut task::Context<'_>,
    ) -> Poll<io::Result<()>> {
        let state: &mut H2DirectState = &mut self.get_mut().state;
        if state.failed {
            state.reset();
            return Poll::Ready(Err(io::Error::other(MISSING_SEND_CAPACITY)));
        }
        match state.poll_drain_pending_body(context) {
            Poll::Ready(Ok(())) => {}
            Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
            Poll::Pending => return Poll::Pending,
        }
        if !state.head_sent {
            return Poll::Ready(Err(state.fail(MISSING_RESPONSE_HEAD)));
        }
        if !state.suppress_body
            && let Some(announced) = state.announced_len
            && state.body_len != announced
        {
            return Poll::Ready(Err(state.fail(TRUNCATED_RESPONSE_BODY)));
        }
        if !state.finished {
            state.finished = true;
            if let Some(mut send_stream) = state.send_stream.take()
                && let Err(error) = send_stream.send_data(H2BodyBuf::empty(), true)
            {
                return Poll::Ready(Err(state.fail(&error.to_string())));
            }
        }
        Poll::Ready(Ok(()))
    }
}