hyperlane-core 22.8.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
use super::*;

/// Takes a recycled HTTP/3 byte buffer from the worker-local pool.
///
/// # Returns
///
/// - `Vec<u8>` - An empty byte vector retaining pooled capacity when available.
#[inline(always)]
pub(crate) fn take_h3_buffer() -> Vec<u8> {
    H3_BUFFER_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
        let mut buf: Vec<u8> = pool
            .borrow_mut()
            .pop()
            .unwrap_or_else(|| Vec::with_capacity(H3_READ_CHUNK_SIZE));
        buf.clear();
        buf
    })
}

/// Returns a reusable HTTP/3 byte buffer to the worker-local pool.
///
/// # Arguments
///
/// - `Vec<u8>` - The buffer to recycle.
#[inline(always)]
pub(crate) fn return_h3_buffer(mut buffer: Vec<u8>) {
    if buffer.capacity() == 0 || buffer.capacity() > MAX_POOLED_BUFFER_CAPACITY {
        return;
    }
    buffer.clear();
    H3_BUFFER_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
        let mut pool: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
        if pool.len() < MAX_POOLED_H3_BUFFERS {
            pool.push(buffer);
        }
    });
}

/// Reports whether an HTTP/3 frame type is a reserved GREASE type (`0x1f * N + 0x21`).
///
/// # Arguments
///
/// - `u64` - The decoded frame type identifier.
///
/// # Returns
///
/// - `bool` - `true` when the frame must be ignored.
#[inline(always)]
fn is_grease_id(id: u64) -> bool {
    id >= 0x21 && (id - 0x21).is_multiple_of(0x1f)
}

/// Reports whether a frame type is reserved from HTTP/2 and forbidden in HTTP/3 (RFC 9114 §7.2.8).
///
/// # Arguments
///
/// - `u64` - The decoded frame type identifier.
///
/// # Returns
///
/// - `bool` - `true` when receiving the frame must close the connection with `H3_FRAME_UNEXPECTED`.
#[inline(always)]
fn is_reserved_h2_frame(id: u64) -> bool {
    let low_reserved: bool = id == 0x02 || id == 0x06;
    let high_reserved: bool = id == 0x08 || id == 0x09;
    low_reserved || high_reserved
}

/// Serves one QUIC connection speaking HTTP/3 until it closes.
///
/// Opens the server unidirectional control stream with a pre-encoded empty
/// `SETTINGS` frame and polls incoming bidirectional request streams,
/// unidirectional peer streams, and active request futures concurrently within
/// a single task without per-stream `tokio::spawn` overhead.
///
/// # Arguments
///
/// - `ConnectionEnv` - The shared server, compiled pipeline, limits and protocol.
/// - `StreamPeers` - The local and remote addresses of the QUIC connection.
/// - `QuicConnection` - The established QUIC connection.
pub(crate) async fn serve_h3_connection(
    env: ConnectionEnv,
    peers: StreamPeers,
    connection: QuicConnection,
) {
    let mut control_stream: Option<QuicSendStream> = match connection.open_uni().await {
        Ok(mut send) => {
            if send.write_all(H3_SERVER_CONTROL_SETTINGS).await.is_err() {
                return;
            }
            Some(send)
        }
        Err(_) => return,
    };
    let control_state: H3ControlState = H3ControlState::default();
    let mut first_req: Pin<&mut Option<_>> = pin!(None);
    let mut extra_reqs: Option<FuturesUnordered<_>> = None;
    let mut first_uni: Pin<&mut Option<_>> = pin!(None);
    let mut extra_unis: Option<FuturesUnordered<_>> = None;
    loop {
        let has_extra_reqs: bool = extra_reqs
            .as_ref()
            .is_some_and(|queue: &FuturesUnordered<_>| !queue.is_empty());
        let has_extra_unis: bool = extra_unis
            .as_ref()
            .is_some_and(|queue: &FuturesUnordered<_>| !queue.is_empty());
        tokio::select! {
            biased;
            _ = async {
                if let Some(fut) = first_req.as_mut().as_pin_mut() {
                    let _: Result<(), Box<dyn Any + Send>> = fut.await;
                }
            }, if first_req.is_some() => {
                first_req.set(None);
            }
            _ = async {
                if let Some(queue) = extra_reqs.as_mut() {
                    let _: Option<Result<(), Box<dyn Any + Send>>> = queue.next().await;
                }
            }, if has_extra_reqs => {}
            _ = async {
                if let Some(fut) = first_uni.as_mut().as_pin_mut() {
                    fut.await;
                }
            }, if first_uni.is_some() => {
                first_uni.set(None);
            }
            _ = async {
                if let Some(queue) = extra_unis.as_mut() {
                    let _: Option<()> = queue.next().await;
                }
            }, if has_extra_unis => {}
            accepted = connection.accept_bi() => {
                match accepted {
                    Ok((send, recv)) => {
                        let req_env: H3RequestEnv = H3RequestEnv {
                            shared: Arc::clone(&env.shared),
                            peers,
                        };
                        if first_req.is_none() {
                            first_req.set(Some(
                                AssertUnwindSafe(h3_request_task(req_env, &connection, send, recv))
                                    .catch_unwind(),
                            ));
                        } else {
                            extra_reqs
                                .get_or_insert_with(FuturesUnordered::new)
                                .push(
                                    AssertUnwindSafe(h3_request_task(req_env, &connection, send, recv))
                                        .catch_unwind(),
                                );
                        }
                    }
                    Err(_) => break,
                }
            }
            uni = connection.accept_uni() => {
                match uni {
                    Ok(recv) => {
                        if first_uni.is_none() {
                            first_uni.set(Some(handle_h3_uni_stream(
                                &connection,
                                recv,
                                &control_state,
                            )));
                        } else {
                            extra_unis
                                .get_or_insert_with(FuturesUnordered::new)
                                .push(handle_h3_uni_stream(&connection, recv, &control_state));
                        }
                    }
                    Err(_) => break,
                }
            }
        }
    }
    let _: Option<QuicSendStream> = control_stream.take();
}

/// Validates an HTTP/3 `SETTINGS` frame payload per RFC 9114 §7.2.4.
///
/// # Arguments
///
/// - `&[u8]` - The `SETTINGS` frame payload bytes.
///
/// # Returns
///
/// - `Result<(), u32>` - `Ok(())` when valid, or the RFC 9114 HTTP/3 error code to close with.
fn validate_h3_settings_payload(payload: &[u8]) -> Result<(), u32> {
    let mut pos: usize = 0;
    let mut seen: [u64; 16] = [0; 16];
    let mut seen_len: usize = 0;
    let mut overflow: Option<HashSet<u64>> = None;
    while pos < payload.len() {
        let Some((id, id_len)) = decode_varint(&payload[pos..]) else {
            return Err(H3_FRAME_ERROR);
        };
        pos += id_len;
        let Some((_, val_len)) = decode_varint(&payload[pos..]) else {
            return Err(H3_FRAME_ERROR);
        };
        pos += val_len;
        if (0x02..=0x05).contains(&id) {
            return Err(H3_SETTINGS_ERROR);
        }
        if seen[..seen_len].contains(&id) {
            return Err(H3_SETTINGS_ERROR);
        }
        if seen_len < seen.len() {
            seen[seen_len] = id;
            seen_len += 1;
        } else {
            let set: &mut HashSet<u64> = overflow.get_or_insert_with(HashSet::new);
            if !set.insert(id) {
                return Err(H3_SETTINGS_ERROR);
            }
        }
    }
    Ok(())
}

/// Validates and drains the peer's HTTP/3 unidirectional control stream per RFC 9114 §6.2.1.
///
/// # Arguments
///
/// - `&QuicConnection` - The owning QUIC connection closed on any control-stream violation.
/// - `&mut QuicRecvStream` - The peer's control stream after its stream-type varint.
async fn drive_h3_control_stream(connection: &QuicConnection, recv: &mut QuicRecvStream) {
    let mut buf: Vec<u8> = take_h3_buffer();
    let mut pos: usize = 0;
    let mut settings_seen: bool = false;
    loop {
        if pos == buf.len() {
            buf.clear();
            pos = 0;
        }
        let header: Option<(u64, usize)> =
            match read_h3_frame_header(recv, &mut buf, &mut pos).await {
                Ok(Some(pair)) => Some(pair),
                Ok(None) => None,
                Err(_) => {
                    return_h3_buffer(buf);
                    connection.close(
                        VarInt::from_u32(H3_FRAME_ERROR),
                        H3_REASON_MALFORMED_CONTROL,
                    );
                    return;
                }
            };
        let Some((frame_type, payload_len)) = header else {
            return_h3_buffer(buf);
            connection.close(
                VarInt::from_u32(H3_CLOSED_CRITICAL_STREAM),
                H3_REASON_CONTROL_CLOSED,
            );
            return;
        };
        if !settings_seen {
            if frame_type != H3_FRAME_SETTINGS {
                return_h3_buffer(buf);
                connection.close(
                    VarInt::from_u32(H3_MISSING_SETTINGS),
                    H3_REASON_MISSING_SETTINGS,
                );
                return;
            }
            if payload_len > H3_MAX_SETTINGS_FRAME_LEN {
                return_h3_buffer(buf);
                connection.close(
                    VarInt::from_u32(H3_FRAME_ERROR),
                    H3_REASON_SETTINGS_TOO_LARGE,
                );
                return;
            }
            match ensure_h3_bytes(recv, &mut buf, pos, payload_len).await {
                Ok(true) => {}
                Ok(false) => {
                    return_h3_buffer(buf);
                    connection.close(
                        VarInt::from_u32(H3_CLOSED_CRITICAL_STREAM),
                        H3_REASON_SETTINGS_TRUNCATED,
                    );
                    return;
                }
                Err(_) => {
                    return_h3_buffer(buf);
                    connection.close(VarInt::from_u32(H3_FRAME_ERROR), H3_REASON_CONTROL_READ);
                    return;
                }
            }
            let end: usize = pos + payload_len;
            if let Err(code) = validate_h3_settings_payload(&buf[pos..end]) {
                return_h3_buffer(buf);
                connection.close(VarInt::from_u32(code), H3_REASON_INVALID_SETTINGS);
                return;
            }
            pos = end;
            settings_seen = true;
            continue;
        }
        match frame_type {
            H3_FRAME_SETTINGS | H3_FRAME_DATA | H3_FRAME_HEADERS | H3_FRAME_PUSH_PROMISE => {
                return_h3_buffer(buf);
                connection.close(
                    VarInt::from_u32(H3_FRAME_UNEXPECTED),
                    H3_REASON_UNEXPECTED_CONTROL,
                );
                return;
            }
            other if is_reserved_h2_frame(other) => {
                return_h3_buffer(buf);
                connection.close(
                    VarInt::from_u32(H3_FRAME_UNEXPECTED),
                    H3_REASON_RESERVED_FRAME,
                );
                return;
            }
            _ => {
                if skip_h3_payload(recv, &mut buf, &mut pos, payload_len)
                    .await
                    .is_err()
                {
                    return_h3_buffer(buf);
                    connection.close(
                        VarInt::from_u32(H3_CLOSED_CRITICAL_STREAM),
                        H3_REASON_CONTROL_TRUNCATED,
                    );
                    return;
                }
            }
        }
    }
}

/// Identifies and enforces RFC 9114 §6.2 rules on an incoming unidirectional peer stream.
///
/// # Arguments
///
/// - `&QuicConnection` - The owning QUIC connection for closing on fatal stream errors.
/// - `QuicRecvStream` - The incoming unidirectional stream.
/// - `&H3ControlState` - Atomic flags recording peer critical streams immediately.
async fn handle_h3_uni_stream(
    connection: &QuicConnection,
    mut recv: QuicRecvStream,
    state: &H3ControlState,
) {
    let mut header_buf: [u8; 8] = [0; 8];
    let mut filled: usize = 0;
    let stream_type: u64 = loop {
        if filled > 0
            && let Some((val, _)) = decode_varint(&header_buf[..filled])
        {
            break val;
        }
        if filled == header_buf.len() {
            return;
        }
        match recv.read(&mut header_buf[filled..filled + 1]).await {
            Ok(Some(n)) if n > 0 => filled += n,
            _ => return,
        }
    };
    match stream_type {
        H3_STREAM_CONTROL => {
            if state.control_seen.swap(true, AtomicOrdering::AcqRel) {
                connection.close(
                    VarInt::from_u32(H3_STREAM_CREATION_ERROR),
                    H3_REASON_DUPLICATE_CONTROL,
                );
                return;
            }
            drive_h3_control_stream(connection, &mut recv).await;
        }
        H3_STREAM_QPACK_ENCODER => {
            if state.qpack_enc_seen.swap(true, AtomicOrdering::AcqRel) {
                connection.close(
                    VarInt::from_u32(H3_STREAM_CREATION_ERROR),
                    H3_REASON_DUPLICATE_ENCODER,
                );
                return;
            }
            let mut buf: [u8; 64] = [0; 64];
            loop {
                match recv.read(&mut buf).await {
                    Ok(Some(0)) | Ok(None) => {
                        connection.close(
                            VarInt::from_u32(H3_CLOSED_CRITICAL_STREAM),
                            H3_REASON_ENCODER_CLOSED,
                        );
                        return;
                    }
                    Ok(Some(n)) => {
                        if buf[..n].iter().any(|b: &u8| *b != QPACK_SET_CAPACITY_ZERO) {
                            connection.close(
                                VarInt::from_u32(H3_QPACK_ENCODER_STREAM_ERROR),
                                H3_REASON_QPACK_DYNAMIC_UNSUPPORTED,
                            );
                            return;
                        }
                    }
                    Err(_) => return,
                }
            }
        }
        H3_STREAM_QPACK_DECODER => {
            if state.qpack_dec_seen.swap(true, AtomicOrdering::AcqRel) {
                connection.close(
                    VarInt::from_u32(H3_STREAM_CREATION_ERROR),
                    H3_REASON_DUPLICATE_DECODER,
                );
                return;
            }
            let mut buf: [u8; 64] = [0; 64];
            loop {
                match recv.read(&mut buf).await {
                    Ok(Some(0)) | Ok(None) => {
                        connection.close(
                            VarInt::from_u32(H3_CLOSED_CRITICAL_STREAM),
                            H3_REASON_DECODER_CLOSED,
                        );
                        return;
                    }
                    Ok(Some(n)) => {
                        if buf[..n].iter().any(|b: &u8| {
                            let is_inc: bool = (*b & 0xc0) == 0x00;
                            let is_ack: bool = (*b & 0x80) == 0x80;
                            is_inc || is_ack
                        }) {
                            connection.close(
                                VarInt::from_u32(H3_QPACK_DECODER_STREAM_ERROR),
                                H3_REASON_QPACK_DECODER_INVALID,
                            );
                            return;
                        }
                    }
                    Err(_) => return,
                }
            }
        }
        H3_STREAM_PUSH => {
            connection.close(
                VarInt::from_u32(H3_STREAM_CREATION_ERROR),
                H3_REASON_CLIENT_PUSH,
            );
        }
        _ => {
            let _: Result<(), _> = recv.stop(VarInt::from_u32(H3_NO_ERROR));
        }
    }
}

/// Ensures at least `needed` unread bytes are buffered in `buf[pos..]`, returning `false` on EOF.
///
/// # Arguments
///
/// - `&mut QuicRecvStream` - The QUIC receive stream.
/// - `&mut Vec<u8>` - The pooled read buffer.
/// - `usize` - Current unread cursor inside `buf`.
/// - `usize` - Minimum unread bytes required.
///
/// # Returns
///
/// - `Result<bool, RequestError>` - `Ok(true)` when `needed` bytes are available, `Ok(false)` on clean EOF.
#[inline(always)]
async fn ensure_h3_bytes(
    recv: &mut QuicRecvStream,
    buf: &mut Vec<u8>,
    pos: usize,
    needed: usize,
) -> Result<bool, RequestError> {
    while buf.len() - pos < needed {
        let old_len: usize = buf.len();
        let grow: usize = H3_READ_CHUNK_SIZE.max(needed - (old_len - pos));
        buf.resize(old_len + grow, 0);
        match recv.read(&mut buf[old_len..]).await {
            Ok(Some(n)) if n > 0 => {
                buf.truncate(old_len + n);
            }
            Ok(Some(_)) | Ok(None) => {
                buf.truncate(old_len);
                return Ok(false);
            }
            Err(error) => {
                buf.truncate(old_len);
                return Err(RequestError::Request(error.to_string()));
            }
        }
    }
    Ok(true)
}

/// Reads the next HTTP/3 frame header `(frame_type, payload_len)` from `buf` / `recv`.
///
/// # Arguments
///
/// - `&mut QuicRecvStream` - The QUIC receive stream.
/// - `&mut Vec<u8>` - The pooled read buffer.
/// - `&mut usize` - Read cursor inside `buf`, advanced past the frame header.
///
/// # Returns
///
/// - `Result<Option<(u64, usize)>, RequestError>` - `None` on clean stream EOF before a frame.
async fn read_h3_frame_header(
    recv: &mut QuicRecvStream,
    buf: &mut Vec<u8>,
    pos: &mut usize,
) -> Result<Option<(u64, usize)>, RequestError> {
    let frame_type: u64 = loop {
        if *pos < buf.len() {
            let need: usize = 1usize << (buf[*pos] >> 6);
            if buf.len() - *pos >= need
                && let Some((val, consumed)) = decode_varint(&buf[*pos..])
            {
                *pos += consumed;
                break val;
            }
        }
        let need_more: usize = if *pos < buf.len() {
            1usize << (buf[*pos] >> 6)
        } else {
            1
        };
        if !ensure_h3_bytes(recv, buf, *pos, need_more).await? {
            if *pos == buf.len() {
                return Ok(None);
            }
            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
        }
    };
    let payload_len_u64: u64 = loop {
        if *pos < buf.len() {
            let need: usize = 1usize << (buf[*pos] >> 6);
            if buf.len() - *pos >= need
                && let Some((val, consumed)) = decode_varint(&buf[*pos..])
            {
                *pos += consumed;
                break val;
            }
        }
        let need_more: usize = if *pos < buf.len() {
            1usize << (buf[*pos] >> 6)
        } else {
            1
        };
        if !ensure_h3_bytes(recv, buf, *pos, need_more).await? {
            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
        }
    };
    let payload_len: usize = usize::try_from(payload_len_u64)
        .map_err(|_| RequestError::HttpRead(HttpStatus::BadRequest))?;
    Ok(Some((frame_type, payload_len)))
}

/// Skips `remaining` payload bytes belonging to an ignored GREASE or trailer frame.
///
/// # Arguments
///
/// - `&mut QuicRecvStream` - The QUIC receive stream.
/// - `&mut Vec<u8>` - The pooled read buffer.
/// - `&mut usize` - Read cursor inside `buf`.
/// - `usize` - Number of bytes to discard.
///
/// # Returns
///
/// - `Result<(), RequestError>` - `Ok(())` once discarded.
async fn skip_h3_payload(
    recv: &mut QuicRecvStream,
    buf: &mut Vec<u8>,
    pos: &mut usize,
    mut remaining: usize,
) -> Result<(), RequestError> {
    while remaining > 0 {
        let avail: usize = buf.len() - *pos;
        if avail > 0 {
            let take: usize = avail.min(remaining);
            *pos += take;
            remaining -= take;
            continue;
        }
        buf.clear();
        *pos = 0;
        if !ensure_h3_bytes(recv, buf, 0, 1).await? {
            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
        }
    }
    Ok(())
}

/// Reads and decodes the initial HTTP/3 `HEADERS` frame directly into `request` and `target`.
///
/// # Arguments
///
/// - `&QuicConnection` - The owning QUIC connection closed on connection-level frame violations.
/// - `&mut QuicRecvStream` - The QUIC receive stream.
/// - `&mut Vec<u8>` - The pooled read buffer.
/// - `&mut usize` - Read cursor inside `buf`.
/// - `&RequestConfig` - Security limits.
/// - `&mut Request` - The destination framework request.
/// - `&mut String` - The destination target buffer.
///
/// # Returns
///
/// - `Result<Option<H3DecodedRequestMeta>, RequestError>` - `None` if peer closed before sending headers.
async fn read_h3_request_headers(
    connection: &QuicConnection,
    recv: &mut QuicRecvStream,
    buf: &mut Vec<u8>,
    pos: &mut usize,
    config: &RequestConfig,
    request: &mut Request,
    target: &mut String,
) -> Result<Option<H3DecodedRequestMeta>, RequestError> {
    loop {
        let Some((frame_type, payload_len)) = read_h3_frame_header(recv, buf, pos).await? else {
            return Ok(None);
        };
        if frame_type != H3_FRAME_HEADERS {
            let forbidden: bool =
                frame_type == H3_FRAME_DATA || H3_FORBIDDEN_REQUEST_FRAMES.contains(&frame_type);
            if forbidden || is_reserved_h2_frame(frame_type) {
                let reason: &[u8] = if is_reserved_h2_frame(frame_type) {
                    H3_REASON_RESERVED_FRAME
                } else {
                    H3_REASON_UNEXPECTED_REQUEST_FRAME
                };
                connection.close(VarInt::from_u32(H3_FRAME_UNEXPECTED), reason);
                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
            }
            skip_h3_payload(recv, buf, pos, payload_len).await?;
            continue;
        }
        if payload_len > H3_MAX_HEADERS_FRAME_LEN {
            return Err(RequestError::HeaderValueTooLong(
                HttpStatus::RequestHeaderFieldsTooLarge,
            ));
        }
        if !ensure_h3_bytes(recv, buf, *pos, payload_len).await? {
            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
        }
        let payload_end: usize = *pos + payload_len;
        let meta: H3DecodedRequestMeta =
            decode_qpack_request(&buf[*pos..payload_end], config, request, target)?;
        *pos = payload_end;
        return Ok(Some(meta));
    }
}

/// Collects HTTP/3 `DATA` frames into `body` while enforcing size limits.
///
/// # Arguments
///
/// - `&QuicConnection` - The owning QUIC connection closed on connection-level frame violations.
/// - `&mut QuicRecvStream` - The receive stream carrying `DATA` frames.
/// - `&mut Vec<u8>` - The pooled read buffer containing any bytes already read after `HEADERS`.
/// - `&mut usize` - Read cursor inside `buf`.
/// - `usize` - Maximum permitted body length.
/// - `&mut Vec<u8>` - Destination request body buffer.
///
/// # Returns
///
/// - `Result<(), RequestError>` - `Ok(())` when the request stream ends cleanly.
async fn collect_h3_data_frames(
    connection: &QuicConnection,
    recv: &mut QuicRecvStream,
    buf: &mut Vec<u8>,
    pos: &mut usize,
    max_body_size: usize,
    body: &mut Vec<u8>,
) -> Result<(), RequestError> {
    let mut trailers_seen: bool = false;
    loop {
        if *pos == buf.len() {
            buf.clear();
            *pos = 0;
        }
        let Some((frame_type, payload_len)) = read_h3_frame_header(recv, buf, pos).await? else {
            return Ok(());
        };
        match frame_type {
            H3_FRAME_DATA => {
                if trailers_seen {
                    connection.close(
                        VarInt::from_u32(H3_FRAME_UNEXPECTED),
                        H3_REASON_FRAME_AFTER_TRAILERS,
                    );
                    return Err(RequestError::HttpRead(HttpStatus::BadRequest));
                }
                if max_body_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE
                    && body.len().saturating_add(payload_len) > max_body_size
                {
                    let _: Result<(), _> = recv.stop(VarInt::from_u32(H3_NO_ERROR));
                    return Err(RequestError::ContentLengthTooLarge(
                        HttpStatus::PayloadTooLarge,
                    ));
                }
                let mut remaining: usize = payload_len;
                while remaining > 0 {
                    let avail: usize = buf.len() - *pos;
                    if avail > 0 {
                        let take: usize = avail.min(remaining);
                        body.extend_from_slice(&buf[*pos..*pos + take]);
                        *pos += take;
                        remaining -= take;
                        continue;
                    }
                    let old_len: usize = body.len();
                    let chunk_len: usize = remaining.min(MAX_POOLED_BUFFER_CAPACITY);
                    body.resize(old_len + chunk_len, 0);
                    match recv.read(&mut body[old_len..]).await {
                        Ok(Some(n)) if n > 0 => {
                            body.truncate(old_len + n);
                            remaining -= n;
                        }
                        Ok(Some(_)) | Ok(None) => {
                            body.truncate(old_len);
                            return Err(RequestError::HttpRead(HttpStatus::BadRequest));
                        }
                        Err(error) => {
                            body.truncate(old_len);
                            return Err(RequestError::Request(error.to_string()));
                        }
                    }
                }
            }
            H3_FRAME_HEADERS => {
                if trailers_seen {
                    connection.close(
                        VarInt::from_u32(H3_FRAME_UNEXPECTED),
                        H3_REASON_FRAME_AFTER_TRAILERS,
                    );
                    return Err(RequestError::HttpRead(HttpStatus::BadRequest));
                }
                trailers_seen = true;
                skip_h3_payload(recv, buf, pos, payload_len).await?;
            }
            other if is_grease_id(other) => {
                skip_h3_payload(recv, buf, pos, payload_len).await?;
            }
            H3_FRAME_SETTINGS
            | H3_FRAME_GOAWAY
            | H3_FRAME_CANCEL_PUSH
            | H3_FRAME_PUSH_PROMISE
            | H3_FRAME_MAX_PUSH_ID => {
                connection.close(
                    VarInt::from_u32(H3_FRAME_UNEXPECTED),
                    H3_REASON_UNEXPECTED_REQUEST_FRAME,
                );
                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
            }
            other if is_reserved_h2_frame(other) => {
                connection.close(
                    VarInt::from_u32(H3_FRAME_UNEXPECTED),
                    H3_REASON_RESERVED_FRAME,
                );
                return Err(RequestError::HttpRead(HttpStatus::BadRequest));
            }
            _ => {
                skip_h3_payload(recv, buf, pos, payload_len).await?;
            }
        }
    }
}

/// Runs the framework lifecycle directly over one QUIC bidirectional stream speaking HTTP/3.
///
/// # Arguments
///
/// - `H3RequestEnv` - Shared server state, compiled pipeline and connection addresses.
/// - `&QuicConnection` - The owning QUIC connection closed on connection-level frame violations.
/// - `QuicSendStream` - The QUIC send stream for the response.
/// - `QuicRecvStream` - The QUIC receive stream for the request.
pub(crate) async fn h3_request_task(
    env: H3RequestEnv,
    connection: &QuicConnection,
    mut send_stream: QuicSendStream,
    mut recv_stream: QuicRecvStream,
) {
    let H3RequestEnv { shared, peers } = env;
    let server: &Server = &shared.server;
    let request_config: RequestConfig = shared.request_config;
    let mut read_buf: Vec<u8> = take_h3_buffer();
    let mut read_pos: usize = 0;
    let mut ctx: Context = take_pooled_context();
    let mut target: String = take_target_buffer();
    let read_timeout_ms: u64 = request_config.get_read_timeout_ms();
    let head_result: Result<Option<H3DecodedRequestMeta>, RequestError> =
        if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
            read_h3_request_headers(
                connection,
                &mut recv_stream,
                &mut read_buf,
                &mut read_pos,
                &request_config,
                ctx.get_mut_request(),
                &mut target,
            )
            .await
        } else {
            let mut reading: Pin<&mut _> = pin!(read_h3_request_headers(
                connection,
                &mut recv_stream,
                &mut read_buf,
                &mut read_pos,
                &request_config,
                ctx.get_mut_request(),
                &mut target,
            ));
            if let Some(done) = poll_once_protocol(reading.as_mut()).await {
                done
            } else {
                match timeout(Duration::from_millis(read_timeout_ms), reading).await {
                    Ok(done) => done,
                    Err(_) => Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout)),
                }
            }
        };
    let meta: H3DecodedRequestMeta = match head_result {
        Ok(Some(meta)) => meta,
        Ok(None) => {
            return_h3_buffer(read_buf);
            return_target_buffer(target);
            return_pooled_context(ctx);
            return;
        }
        Err(error) => {
            let _: Result<(), _> = recv_stream.stop(VarInt::from_u32(H3_NO_ERROR));
            return_h3_buffer(read_buf);
            return_target_buffer(target);
            h3_fail_request(
                server,
                request_config,
                peers,
                send_stream,
                &mut ctx,
                HttpVersion::Http3,
                error,
            )
            .await;
            return_pooled_context(ctx);
            return;
        }
    };
    let max_body_size: usize = request_config.get_max_body_size();
    let body: &mut Vec<u8> = ctx.get_mut_request().get_mut_body();
    body.clear();
    if let Some(expected) = meta.declared_content_length
        && expected > 0
    {
        body.reserve(expected.min(MAX_POOLED_BUFFER_CAPACITY));
    }
    let body_result: Result<(), RequestError> = {
        let mut reading: Pin<&mut _> = pin!(async {
            if meta.expect_continue {
                send_stream
                    .write_all(H3_CONTINUE_FRAME)
                    .await
                    .map_err(|error: QuicWriteError| RequestError::Request(error.to_string()))?;
            }
            collect_h3_data_frames(
                connection,
                &mut recv_stream,
                &mut read_buf,
                &mut read_pos,
                max_body_size,
                body,
            )
            .await
        });
        if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
            reading.await
        } else if let Some(done) = poll_once_protocol(reading.as_mut()).await {
            done
        } else {
            match timeout(Duration::from_millis(read_timeout_ms), reading).await {
                Ok(done) => done,
                Err(_) => Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout)),
            }
        }
    };
    return_h3_buffer(read_buf);
    let body_check: Result<(), RequestError> =
        body_result.and_then(|()| match meta.declared_content_length {
            None => Ok(()),
            Some(declared) => match ctx.get_request().get_body().len().cmp(&declared) {
                Ordering::Equal => Ok(()),
                _ => Err(RequestError::Request(CONTENT_LENGTH_MISMATCH.to_owned())),
            },
        });
    if let Err(error) = body_check {
        let _: Result<(), _> = recv_stream.stop(VarInt::from_u32(H3_NO_ERROR));
        return_target_buffer(target);
        h3_fail_request(
            server,
            request_config,
            peers,
            send_stream,
            &mut ctx,
            HttpVersion::Http3,
            error,
        )
        .await;
        return_pooled_context(ctx);
        return;
    }
    let mut stream: Stream = Stream::from_transport(
        H3DirectTransport::new(send_stream, peers, meta.is_head),
        request_config,
        false,
    );
    server
        .run_protocol_lifecycle_in_place(&shared.pipeline, &mut stream, &mut ctx, target)
        .await;
    let _: Result<(), io::Error> = stream.get_mut_stream().shutdown().await;
    return_pooled_context(ctx);
}

/// Answers an HTTP/3 request that failed before a handler could run.
///
/// # Arguments
///
/// - `&Server` - The server owning the request error hooks.
/// - `RequestConfig` - The parsing limits and read timeout.
/// - `StreamPeers` - The connection's socket addresses.
/// - `QuicSendStream` - The QUIC send stream for the error response.
/// - `&mut Context` - The context passed to error hooks.
/// - `HttpVersion` - The real protocol version to stamp on the error context.
/// - `RequestError` - The failure that stopped the request.
#[cold]
pub(crate) async fn h3_fail_request(
    server: &Server,
    request_config: RequestConfig,
    peers: StreamPeers,
    send_stream: QuicSendStream,
    ctx: &mut Context,
    version: HttpVersion,
    error: RequestError,
) {
    ctx.get_mut_request().reset().set_version(version.clone());
    ctx.get_mut_response().reset().set_version(version.clone());
    ctx.clear_route_params();
    ctx.reset_request_attributes();
    let mut stream: Stream = Stream::from_transport(
        H3DirectTransport::new(send_stream, peers, false),
        request_config,
        false,
    );
    reply_to_request_error(server, &mut stream, ctx, &error, Some(version)).await;
    let _: Result<(), io::Error> = stream.get_mut_stream().shutdown().await;
}