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
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
use super::*;
/// Implementation of `From` trait for converting `usize` address into `&Stream`.
impl From<usize> for &'static Stream {
/// Converts a memory address into a reference to `Stream`.
///
/// # Arguments
///
/// - `usize` - The memory address of the `Stream` instance.
///
/// # Returns
///
/// - `&'static Stream` - A reference to the `Stream` at the given address.
///
/// # Safety
///
/// - The address is guaranteed to be a valid `Stream` instance
/// that was previously converted from a reference and is managed by the runtime.
#[inline(always)]
fn from(address: usize) -> &'static Stream {
unsafe { &*(address as *const Stream) }
}
}
/// Implementation of `From` trait for converting `usize` address into `&mut Stream`.
impl<'a> From<usize> for &'a mut Stream {
/// Converts a memory address into a mutable reference to `Stream`.
///
/// # Arguments
///
/// - `usize` - The memory address of the `Stream` instance.
///
/// # Returns
///
/// - `&'a mut Stream` - A mutable reference to the `Stream` at the given address.
///
/// # Safety
///
/// - The address is guaranteed to be a valid `Stream` instance
/// that was previously converted from a reference and is managed by the runtime.
#[inline(always)]
fn from(address: usize) -> &'a mut Stream {
unsafe { &mut *(address as *mut Stream) }
}
}
/// Implementation of `From` trait for converting `&Stream` into `usize` address.
impl From<&Stream> for usize {
/// Converts a reference to `Stream` into its memory address.
///
/// # Arguments
///
/// - `&Stream` - The reference to the `Stream` instance.
///
/// # Returns
///
/// - `usize` - The memory address of the `Stream` instance.
#[inline(always)]
fn from(stream: &Stream) -> Self {
stream as *const Stream as usize
}
}
/// Implementation of `From` trait for converting `&mut Stream` into `usize` address.
impl From<&mut Stream> for usize {
/// Converts a mutable reference to `Stream` into its memory address.
///
/// # Arguments
///
/// - `&mut Stream` - The mutable reference to the `Stream` instance.
///
/// # Returns
///
/// - `usize` - The memory address of the `Stream` instance.
#[inline(always)]
fn from(stream: &mut Stream) -> Self {
stream as *mut Stream as usize
}
}
/// Implementation of `AsRef` trait for `Stream`.
impl AsRef<Stream> for Stream {
/// Converts `&Stream` to `&Stream` via memory address conversion.
///
/// # Returns
///
/// - `&Self` - A reference to the `Stream` instance.
#[inline(always)]
fn as_ref(&self) -> &Self {
let address: usize = self.into();
address.into()
}
}
/// Implementation of `AsMut` trait for `Stream`.
impl AsMut<Stream> for Stream {
/// Converts `&mut Stream` to `&mut Stream` via memory address conversion.
///
/// # Returns
///
/// - `&mut Self` - A mutable reference to the `Stream` instance.
#[inline(always)]
fn as_mut(&mut self) -> &mut Self {
let address: usize = self.into();
address.into()
}
}
/// Implementation of `Lifetime` trait for `Stream`.
impl Lifetime for Stream {
/// Converts a reference to the stream into a `'static` reference.
///
/// # Returns
///
/// - `&'static Self` - A reference to the stream with a `'static` lifetime.
///
/// # Safety
///
/// - The address is guaranteed to be a valid `Self` instance
/// that was previously converted from a reference and is managed by the runtime.
#[inline(always)]
unsafe fn leak(&self) -> &'static Self {
let address: usize = self.into();
address.into()
}
/// Converts a reference to the stream into a `'static` mutable reference.
///
/// # Returns
///
/// - `&'static mut Self` - A mutable reference to the stream with a `'static` lifetime.
///
/// # Safety
///
/// - The address is guaranteed to be a valid `Self` instance
/// that was previously converted from a reference and is managed by the runtime.
#[inline(always)]
unsafe fn leak_mut(&self) -> &'static mut Self {
let address: usize = self.into();
address.into()
}
}
/// Implementation of `Transport` trait for the plain TCP socket.
///
/// The socket is the reference transport: it already carries a socket
/// identity, so its addresses are reported directly.
impl Transport for TcpStream {
/// Reports the address of the remote end of the socket.
///
/// # Returns
///
/// - `Result<SocketAddr, io::Error>` - The peer address of the socket.
fn peer_addr(&self) -> Result<SocketAddr, io::Error> {
TcpStream::peer_addr(self)
}
/// Reports the address of the local end of the socket.
///
/// # Returns
///
/// - `Result<SocketAddr, io::Error>` - The local address of the socket.
fn local_addr(&self) -> Result<SocketAddr, io::Error> {
TcpStream::local_addr(self)
}
}
/// Implements [`Drop`] for [`PooledReader`].
impl Drop for PooledReader<'_> {
/// Releases the buffer back to the pool for reuse by later requests.
fn drop(&mut self) {
let buffer: Vec<u8> = mem::take(self.get_mut_buffer());
return_read_buffer(buffer);
}
}
/// Implements non-blocking buffered reads for `PooledReader`.
///
/// Buffered bytes are served first; once drained, reads are delegated
/// directly to the underlying stream.
impl AsyncRead for PooledReader<'_> {
/// Polls to read data into the provided buffer.
///
/// # Arguments
///
/// - `Pin<&mut Self>` - The pinned reader.
/// - `&mut Context<'_>` - The task context.
/// - `&mut ReadBuf<'_>` - The destination buffer.
///
/// # Returns
///
/// - `Poll<io::Result<()>>` - Ready when data was read or an error occurred.
fn poll_read(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
let this: &mut Self = self.get_mut();
if this.get_start() < this.get_end() {
let available: usize = this.get_end() - this.get_start();
let amount: usize = available.min(buf.remaining());
let end: usize = this.get_start() + amount;
buf.put_slice(&this.get_buffer()[this.get_start()..end]);
this.set_start(end);
return Poll::Ready(Ok(()));
}
return_read_buffer(mem::take(this.get_mut_buffer()));
Pin::new(&mut **this.get_mut_stream()).poll_read(cx, buf)
}
}
/// Implements buffered-read support for `PooledReader`.
///
/// The internal buffer is refilled from the stream only when fully
/// consumed, so a single socket read serves multiple line parses.
impl AsyncBufRead for PooledReader<'_> {
/// Polls to fill the internal buffer and returns the available data.
///
/// # Arguments
///
/// - `Pin<&mut Self>` - The pinned reader.
/// - `&mut Context<'_>` - The task context.
///
/// # Returns
///
/// - `Poll<io::Result<&[u8]>>` - Ready with the unconsumed bytes, or an error.
fn poll_fill_buf(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<&[u8]>> {
let this: &mut Self = self.get_mut();
let PooledReader {
stream,
buffer,
capacity,
start,
end,
} = this;
if *start >= *end {
*start = 0;
*end = 0;
if buffer.is_empty() {
*buffer = take_read_buffer(*capacity);
}
let mut read_buf: ReadBuf<'_> = ReadBuf::new(buffer);
match Pin::new(&mut **stream).poll_read(cx, &mut read_buf) {
Poll::Ready(Ok(())) => {
*end = read_buf.filled().len();
}
Poll::Ready(Err(error)) => return Poll::Ready(Err(error)),
Poll::Pending => {
return_read_buffer(mem::take(buffer));
return Poll::Pending;
}
}
}
Poll::Ready(Ok(&buffer[*start..*end]))
}
/// Marks the given number of bytes as consumed.
///
/// # Arguments
///
/// - `Pin<&mut Self>` - The pinned reader.
/// - `usize` - The number of bytes to consume.
fn consume(self: Pin<&mut Self>, amount: usize) {
let this: &mut Self = self.get_mut();
let new_start: usize = (this.get_start() + amount).min(this.get_end());
this.set_start(new_start);
}
}
/// Inherent implementation of [`WsHeartbeatWheel`].
impl WsHeartbeatWheel {
/// Creates a new staggered heartbeat wheel with `bucket_count` watch channels.
///
/// # Arguments
///
/// - `usize` - Number of phase buckets.
///
/// # Returns
///
/// - `Self` - Initialized active heartbeat wheel.
pub(crate) fn new(bucket_count: usize) -> Self {
let mut buckets: Vec<Sender<u64>> = Vec::with_capacity(bucket_count);
for _ in 0..bucket_count {
let (tx, _): (Sender<u64>, Receiver<u64>) = watch::channel(0u64);
buckets.push(tx);
}
Self {
buckets: buckets.into_boxed_slice(),
phase: AtomicUsize::new(0),
alive: AtomicBool::new(true),
}
}
/// Subscribes to the phase bucket farthest from the next tick.
///
/// # Returns
///
/// - `Receiver<u64>` - Watch receiver positioned on the most recently ticked phase bucket.
#[inline]
pub(crate) fn subscribe_staggered(&self) -> Receiver<u64> {
let Self { buckets, phase, .. } = self;
let len: usize = buckets.len();
let cur: usize = phase.load(Ordering::Acquire);
let bucket_idx: usize = (cur.wrapping_add(len - 1)) % len;
let mut rx: Receiver<u64> = buckets[bucket_idx].subscribe();
let _: u64 = *rx.borrow_and_update();
rx
}
/// Counts active WebSocket heartbeat receivers across all phase buckets.
///
/// # Returns
///
/// - `usize` - Total live receivers subscribed to this wheel.
#[inline]
pub(crate) fn total_receivers(&self) -> usize {
let Self { buckets, .. } = self;
let mut total: usize = 0;
for bucket in buckets.iter() {
total += bucket.receiver_count();
}
total
}
}
/// Default construction for [`WebSocketReadState`].
impl Default for WebSocketReadState {
/// Initializes empty WebSocket parsing state.
///
/// # Returns
///
/// - `Self` - The initial WebSocket read state.
#[inline(always)]
fn default() -> Self {
Self {
buffer: Vec::new(),
cursor: 0,
full_frame: Vec::new(),
fragment_opcode: None,
}
}
}
/// Inherent implementation of [`Stream`].
impl Stream {
/// Boxes a transport into a `Stream` for the request pipeline.
///
/// This is the single construction path: a plain TCP socket, a TLS session
/// and a per-request duplex stream all enter here, so nothing above the
/// transport line has to know which one it is serving. The transport is
/// type erased immediately, which keeps `Stream` a fixed size regardless of
/// the concrete protocol adapter behind it.
///
/// # Arguments
///
/// - `T` - The transport type to serve the request cycle over.
/// - `RequestConfig` - The parsing limits and read timeout for the cycle.
/// - `bool` - Whether the connection starts already closed.
///
/// # Returns
///
/// - `Self` - A stream serving bytes through the boxed transport.
pub fn from_transport<T>(transport: T, request_config: RequestConfig, closed: bool) -> Self
where
T: Transport + 'static,
{
Self {
stream: Box::new(transport),
request_config,
closed,
ws_client_response: true,
leftover: Vec::new(),
leftover_start: 0,
leftover_end: 0,
line_buffer: String::new(),
header_line_buffer: String::new(),
websocket_state: None,
read_timer: StreamTimer::None,
}
}
/// Boxes a TCP socket into a `Stream` for the request pipeline.
///
/// Kept as the socket-facing constructor so the accept loop keeps its
/// existing call shape; it delegates to `from_transport`, so there is one
/// construction path rather than two.
///
/// # Arguments
///
/// - `TcpStream` - The accepted socket to serve the request cycle over.
/// - `RequestConfig` - The parsing limits and read timeout for the cycle.
/// - `bool` - Whether the connection starts already closed.
///
/// # Returns
///
/// - `Self` - A stream serving bytes through the boxed socket.
pub fn new(stream: TcpStream, request_config: RequestConfig, closed: bool) -> Self {
Self::from_transport(stream, request_config, closed)
}
/// Reports the address of the remote end of the transport.
///
/// Delegates to the transport itself, so a transport without a socket
/// identity answers with an error rather than a fabricated address.
///
/// # Returns
///
/// - `Result<SocketAddr, io::Error>` - The peer address reported by the transport.
#[inline(always)]
pub fn get_peer_addr(&self) -> Result<SocketAddr, io::Error> {
self.get_stream().peer_addr()
}
/// Reports the address of the local end of the transport.
///
/// Delegates to the transport itself, so a transport without a socket
/// identity answers with an error rather than a fabricated address.
///
/// # Returns
///
/// - `Result<SocketAddr, io::Error>` - The local address reported by the transport.
#[inline(always)]
pub fn get_local_addr(&self) -> Result<SocketAddr, io::Error> {
self.get_stream().local_addr()
}
/// Shuts the transport down.
///
/// The transport itself is crate-internal, so a caller that needs to
/// close the connection reaches it through this method rather than
/// through the field.
///
/// # Returns
///
/// - `Result<(), io::Error>` - Whether the transport shut down.
#[inline(always)]
pub async fn shutdown(&mut self) -> Result<(), io::Error> {
self.get_mut_stream().shutdown().await
}
/// Checks if the connection should be kept alive.
///
/// This method evaluates whether the connection should remain open based on
/// the closed state and the keep_alive parameter.
///
/// # Arguments
///
/// - `bool` - Whether keep-alive is enabled for the request.
///
/// # Returns
///
/// - `bool` - True if the connection should be kept alive, otherwise false.
#[inline(always)]
pub fn is_keep_alive(&self, keep_alive: bool) -> bool {
!self.get_closed() && keep_alive
}
/// Parses the HTTP request content from the stream into the given request.
///
/// The request is reset first, then filled in place so its existing
/// allocations are reused across keep-alive requests.
///
/// # Arguments
///
/// - `&mut Request` - The request object to fill.
///
/// # Returns
///
/// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
async fn fill_http_from_stream(&mut self, request: &mut Request) -> Result<(), RequestError> {
request.reset();
let config: RequestConfig = *self.get_request_config();
let buffer_size: usize = config.get_buffer_size();
let max_path_size: usize = config.get_max_path_size();
// Fast path: when no pipelined leftover bytes exist, read directly into an
// uninitialized stack buffer inside `poll_fn` (zero future size overhead,
// zero idle connection memory, zero `READ_BUFFER_POOL` TLS churn).
let mut start: usize = self.get_leftover_start();
let mut end: usize = self.get_leftover_end();
let mut buffer: Vec<u8> = mem::take(self.get_mut_leftover());
self.set_leftover_start(0);
self.set_leftover_end(0);
let mut pre_parsed_framing: Option<RequestFraming> = None;
if start >= end {
if !buffer.is_empty() {
return_read_buffer(buffer);
}
let read_cap: usize = buffer_size.clamp(1, STACK_READ_BUF_SIZE);
let fast_outcome: FastHttpRead = {
let Stream {
stream,
line_buffer,
..
} = self;
line_buffer.clear();
future::poll_fn(|cx: &mut Context<'_>| {
let mut stack_buf: [MaybeUninit<u8>; STACK_READ_BUF_SIZE] =
[const { MaybeUninit::uninit() }; STACK_READ_BUF_SIZE];
let mut read_buf: ReadBuf<'_> = ReadBuf::uninit(&mut stack_buf[..read_cap]);
match Pin::new(&mut **stream).poll_read(cx, &mut read_buf) {
Poll::Pending => Poll::Pending,
Poll::Ready(Err(error)) => Poll::Ready(Err(RequestError::from(error))),
Poll::Ready(Ok(())) => {
let filled: &[u8] = read_buf.filled();
let filled_len: usize = filled.len();
if filled_len == 0 {
return Poll::Ready(Err(RequestError::ClientClosedConnection(
HttpStatus::BadRequest,
)));
}
match request.parse_http_head_from_slice(filled, &config, line_buffer) {
Err(error) => Poll::Ready(Err(error)),
Ok(Some((RequestFraming::Fixed(content_size), consumed))) => {
let avail: usize = filled_len - consumed;
if content_size <= avail {
if content_size > 0 {
let body: &mut Vec<u8> = request.get_mut_body();
body.clear();
body.extend_from_slice(
&filled[consumed..consumed + content_size],
);
}
let after_body: usize = consumed + content_size;
if after_body < filled_len {
let mut pooled: Vec<u8> =
take_read_buffer(buffer_size.max(filled_len));
pooled[after_body..filled_len]
.copy_from_slice(&filled[after_body..filled_len]);
Poll::Ready(Ok(FastHttpRead::CompleteWithLeftover(
pooled, after_body, filled_len,
)))
} else {
Poll::Ready(Ok(FastHttpRead::Complete))
}
} else {
let pooled: Vec<u8> = if avail > 0 {
let mut buf: Vec<u8> =
take_read_buffer(buffer_size.max(avail));
buf[..avail]
.copy_from_slice(&filled[consumed..filled_len]);
buf
} else {
Vec::new()
};
Poll::Ready(Ok(FastHttpRead::BodyPending(
RequestFraming::Fixed(content_size),
pooled,
avail,
)))
}
}
Ok(Some((RequestFraming::Chunked, consumed))) => {
let avail: usize = filled_len - consumed;
let pooled: Vec<u8> = if avail > 0 {
let mut buf: Vec<u8> =
take_read_buffer(buffer_size.max(avail));
buf[..avail].copy_from_slice(&filled[consumed..filled_len]);
buf
} else {
Vec::new()
};
Poll::Ready(Ok(FastHttpRead::BodyPending(
RequestFraming::Chunked,
pooled,
avail,
)))
}
Ok(None) => {
let mut pooled: Vec<u8> =
take_read_buffer(buffer_size.max(filled_len));
pooled[..filled_len].copy_from_slice(filled);
Poll::Ready(Ok(FastHttpRead::IncompleteHead(
pooled, filled_len,
)))
}
}
}
}
})
.await?
};
match fast_outcome {
FastHttpRead::Complete => return Ok(()),
FastHttpRead::CompleteWithLeftover(pooled, leftover_start, leftover_end) => {
self.set_leftover(pooled);
self.set_leftover_start(leftover_start);
self.set_leftover_end(leftover_end);
return Ok(());
}
FastHttpRead::BodyPending(framing, pooled, avail) => {
buffer = pooled;
start = 0;
end = avail;
pre_parsed_framing = Some(framing);
}
FastHttpRead::IncompleteHead(pooled, filled_len) => {
buffer = pooled;
start = 0;
end = filled_len;
}
}
}
// Split the borrow of the stream: the reader takes the transport, the
// line buffers are separate fields, so both can be held at once.
let Stream {
stream,
line_buffer,
header_line_buffer,
..
} = self;
let mut reader: PooledReader<'_> = PooledReader::new(stream, buffer, buffer_size);
reader.set_start(start);
reader.set_end(end);
let framing: RequestFraming = match pre_parsed_framing {
Some(framing) => framing,
None => {
line_buffer.clear();
let filled_len: usize = future::poll_fn(|cx: &mut Context<'_>| {
Pin::new(&mut reader).poll_fill_buf(cx).map_ok(<[u8]>::len)
})
.await?;
if filled_len == 0 {
return Err(RequestError::ClientClosedConnection(HttpStatus::BadRequest));
}
let fast_framing: Option<RequestFraming> = {
let slice: &[u8] = &reader.get_buffer()[reader.get_start()..reader.get_end()];
match request.parse_http_head_from_slice(slice, &config, line_buffer)? {
Some((framing, consumed)) => {
Pin::new(&mut reader).consume(consumed);
Some(framing)
}
None => None,
}
};
match fast_framing {
Some(framing) => framing,
None => {
let max_request_line: usize =
if max_path_size == DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
usize::MAX
} else {
max_path_size.saturating_add(HTTP_REQUEST_LINE_OVERHEAD)
};
let line_len: usize = read_http_line_bounded(
&mut reader,
line_buffer,
max_request_line,
RequestError::RequestTooLong(HttpStatus::URITooLong),
)
.await?;
if line_len == 0 {
return Err(RequestError::ClientClosedConnection(
HttpStatus::BadRequest,
));
}
let (method, path, version): (Method, &str, HttpVersion) =
Request::get_http_first_line(line_buffer)?;
Request::check_http_path_size(path, max_path_size)?;
let (query_index, hash_index): (Option<usize>, Option<usize>) =
Request::find_path_separators(path);
let query: &str = Request::get_http_query(path, query_index, hash_index);
let max_query_count: usize =
if max_path_size == DEFAULT_LOW_SECURITY_MAX_PATH_SIZE {
usize::MAX
} else {
HTTP_MAX_QUERY_PARAM_COUNT
};
Request::fill_http_querys(
query,
request.get_mut_querys(),
max_query_count,
)?;
let path_slice: &str =
Request::get_http_path(path, query_index, hash_index);
request.get_mut_path().push_str(path_slice);
request.set_version(version);
let framing: RequestFraming = request
.get_http_headers(&mut reader, &config, header_line_buffer)
.await?;
request.set_method(method);
framing
}
}
}
};
match framing {
RequestFraming::Fixed(0) => {}
RequestFraming::Fixed(content_size) => {
let buffered: usize = reader.get_end() - reader.get_start();
if content_size <= buffered {
let body: &mut Vec<u8> = request.get_mut_body();
body.clear();
let body_start: usize = reader.get_start();
body.extend_from_slice(
&reader.get_buffer()[body_start..body_start + content_size],
);
reader.set_start(body_start + content_size);
} else {
if expects_http_continue(request) {
let transport: &mut Box<dyn Transport> = reader.get_mut_stream();
transport.write_all(HTTP_CONTINUE_RESPONSE).await?;
transport.flush().await?;
}
Request::fill_http_body(&mut reader, request.get_mut_body(), content_size)
.await?;
}
}
RequestFraming::Chunked => {
Box::pin(fill_chunked_request(&mut reader, request, &config)).await?;
}
}
// Preserve bytes read ahead for the next pipelined request: they have
// already left the socket and cannot be read again.
let reader_start: usize = reader.get_start();
let reader_end: usize = reader.get_end();
let pending: Vec<u8> = if reader_start < reader_end {
mem::take(reader.get_mut_buffer())
} else {
Vec::new()
};
drop(reader);
let pending_start: usize = if pending.is_empty() { 0 } else { reader_start };
let pending_end: usize = if pending.is_empty() { 0 } else { reader_end };
self.set_leftover(pending);
self.set_leftover_start(pending_start);
self.set_leftover_end(pending_end);
Ok(())
}
/// Parses an HTTP request from a TCP stream into the given request.
///
/// The request is reset and filled in place, reusing its allocations.
/// An HTTP/1.1 continue expectation can write an interim response after
/// header validation and before waiting for the body. A chunked body is
/// decoded, with trailers discarded and its content length normalized.
/// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
///
/// # Arguments
///
/// - `&mut Request` - The request object to reset and fill.
///
/// # Returns
///
/// - `Result<(), RequestError>` - Ok on success, or an error if parsing fails.
pub async fn try_fill_http_request(
&mut self,
request: &mut Request,
) -> Result<(), RequestError> {
if self.get_closed() {
return Err(RequestError::ServerClosedConnection(HttpStatus::BadRequest));
}
let timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
if timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
return self.fill_http_from_stream(request).await;
}
let duration: Duration = Duration::from_millis(timeout_ms);
let mut timer_slot: Option<Pin<Box<Sleep>>> = {
let Stream { read_timer, .. } = self;
match mem::replace(read_timer, StreamTimer::None) {
StreamTimer::Sleep(sleep) => Some(sleep),
StreamTimer::None | StreamTimer::WsHeartbeat { .. } => None,
}
};
let outcome: Option<Result<(), RequestError>> = {
let mut reading: Pin<&mut _> = pin!(self.fill_http_from_stream(request));
poll_with_timeout(reading.as_mut(), &mut timer_slot, duration).await
};
let Stream { read_timer, .. } = self;
*read_timer = match timer_slot {
Some(sleep) => StreamTimer::Sleep(sleep),
None => StreamTimer::None,
};
match outcome {
Some(result) => result,
None => Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout)),
}
}
/// Parses an HTTP request from a TCP stream.
///
/// Wraps the stream in a buffered reader and delegates to `http_from_reader`.
/// If the timeout is DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS, no timeout is applied.
///
/// # Returns
///
/// - `Result<Request, RequestError>` - The parsed request or an error.
pub async fn try_get_http_request(&mut self) -> Result<Request, RequestError> {
let mut request: Request = Request::default();
self.try_fill_http_request(&mut request).await?;
Ok(request)
}
/// Sends an RFC 6455 Pong frame using a zero-allocation stack buffer.
///
/// # Arguments
///
/// - `&[u8]` - Unmasked Ping payload bytes (`<= 125` bytes per RFC 6455).
///
/// # Returns
///
/// - `Result<(), RequestError>` - `Ok(())` on write and flush, or transport error.
#[cold]
async fn send_ws_pong(&mut self, payload: &[u8]) -> Result<(), RequestError> {
let len: usize = payload.len();
let mut pong: [u8; WS_PONG_STACK_CAP] = [0u8; WS_PONG_STACK_CAP];
pong[0] = WS_PONG_FIRST_BYTE;
pong[1] = len as u8;
pong[2..2 + len].copy_from_slice(payload);
self.try_send(&pong[..2 + len]).await?;
self.try_flush().await?;
Ok(())
}
/// Parses a WebSocket request from a TCP stream.
///
/// Uses a zero-idle-buffer pooled read fast path and a runtime-shared staggered heartbeat wheel
/// for long-lived idle connections while preserving RFC 6455 framing, ping/pong, and timeouts.
///
/// # Returns
///
/// - `Result<Vec<u8>, RequestError>` - The parsed WebSocket request or an error.
pub async fn try_get_websocket_request(&mut self) -> Result<Vec<u8>, RequestError> {
if self.get_closed() {
return self.reset_websocket_state_on_error(Err(RequestError::ServerClosedConnection(
HttpStatus::BadRequest,
)));
}
if self.get_line_buffer().capacity() > 0 {
self.set_line_buffer(String::new());
}
if self.get_header_line_buffer().capacity() > 0 {
self.set_header_line_buffer(String::new());
}
let leftover_start: usize = self.get_leftover_start();
let leftover_end: usize = self.get_leftover_end();
if leftover_start < leftover_end {
let leftover: Vec<u8> = mem::take(self.get_mut_leftover());
self.set_leftover_start(0);
self.set_leftover_end(0);
let unread: Vec<u8> = leftover[leftover_start..leftover_end].to_vec();
return_read_buffer(leftover);
self.set_websocket_state(Some(Box::new(WebSocketReadState {
buffer: unread,
..WebSocketReadState::default()
})));
} else if !self.get_leftover().is_empty() {
let leftover: Vec<u8> = mem::take(self.get_mut_leftover());
self.set_leftover_start(0);
self.set_leftover_end(0);
return_read_buffer(leftover);
}
let read_timeout_ms: u64 = self.get_request_config().get_read_timeout_ms();
let adjusted_timeout_opt: Option<u64> =
if read_timeout_ms == DEFAULT_LOW_SECURITY_READ_TIMEOUT_MS {
None
} else {
Some((read_timeout_ms >> 1) + (read_timeout_ms & 1))
};
loop {
if self.try_get_websocket_state().is_some() {
let parsed: Result<WebSocketParseStep, RequestError> =
self.try_parse_websocket_request();
match self.reset_websocket_state_on_error(parsed)? {
WebSocketParseStep::Message(body) => return Ok(body),
WebSocketParseStep::Ping(payload) => {
let send_res: Result<(), RequestError> =
Box::pin(self.send_ws_pong(&payload)).await;
self.reset_websocket_state_on_error(send_res)?;
continue;
}
WebSocketParseStep::NeedMore => {}
WebSocketParseStep::Eof => {
return self.reset_websocket_state_on_error(Err(
RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
));
}
}
}
let step: Result<WebSocketParseStep, RequestError> =
self.read_next_websocket_step(adjusted_timeout_opt).await;
match self.reset_websocket_state_on_error(step)? {
WebSocketParseStep::Message(body) => return Ok(body),
WebSocketParseStep::Ping(payload) => {
let send_res: Result<(), RequestError> =
Box::pin(self.send_ws_pong(&payload)).await;
self.reset_websocket_state_on_error(send_res)?;
}
WebSocketParseStep::NeedMore => {}
WebSocketParseStep::Eof => {
return self.reset_websocket_state_on_error(Err(
RequestError::IncompleteWebSocketFrame(HttpStatus::BadRequest),
));
}
}
}
}
/// Discards cached parsing state only after an operation completes with an error.
///
/// # Arguments
///
/// - `Result<T, RequestError>` - The completed parsing or reading operation.
///
/// # Returns
///
/// - `Result<T, RequestError>` - The unchanged result after releasing failed parsing state.
#[inline(always)]
fn reset_websocket_state_on_error<T>(
&mut self,
result: Result<T, RequestError>,
) -> Result<T, RequestError> {
if result.is_err() {
let Stream {
websocket_state,
ws_client_response,
..
} = self;
drop(websocket_state.take());
*ws_client_response = true;
}
result
}
/// Parses buffered frames without discarding incomplete or subsequent input.
///
/// Enforces RFC 6455 control frame constraints, continuation sequencing, UTF-8 validity
/// for text messages, close-code validity, and the configured `max_body_size` cap.
///
/// # Returns
///
/// - `Result<WebSocketParseStep, RequestError>` - A complete message, a ping requiring pong, pending input, or a protocol error.
fn try_parse_websocket_request(&mut self) -> Result<WebSocketParseStep, RequestError> {
let max_body_size: usize = self.get_request_config().get_max_body_size();
let Stream {
websocket_state,
ws_client_response,
..
} = self;
loop {
let next_frame: Option<WebSocketFrame> = {
let Some(state) = websocket_state.as_deref_mut() else {
return Ok(WebSocketParseStep::NeedMore);
};
let WebSocketReadState { buffer, cursor, .. }: &mut WebSocketReadState = state;
match WebSocketFrame::decode_ws_frame_checked(&buffer[*cursor..], max_body_size)? {
Some((frame, consumed)) => {
*ws_client_response = true;
*cursor += consumed;
if *cursor >= buffer.len() {
*cursor = 0;
*buffer = Vec::new();
} else if *cursor >= MAX_POOLED_READ_BUFFER_SIZE {
buffer.drain(..*cursor);
*cursor = 0;
}
Some(frame)
}
None => None,
}
};
let Some(frame) = next_frame else {
release_empty_ws_state(websocket_state);
return Ok(WebSocketParseStep::NeedMore);
};
if let Some(step) = process_ws_frame(frame, max_body_size, websocket_state)? {
release_empty_ws_state(websocket_state);
return Ok(step);
}
}
}
/// Handles a short sub-second WebSocket read timeout using a connection-scoped `Sleep` timer.
///
/// Kept cold and boxed out of the primary future so idle WebSocket tasks do not reserve inline `Sleep` space.
///
/// # Arguments
///
/// - `Duration` - Adjusted short timeout interval (`< 1000` ms).
///
/// # Returns
///
/// - `Result<WebSocketParseStep, RequestError>` - Parsed step, heartbeat probe, or timeout error.
#[cold]
async fn read_ws_step_short_timeout(
&mut self,
duration: Duration,
) -> Result<WebSocketParseStep, RequestError> {
let mut timer_slot: Option<Pin<Box<Sleep>>> = {
let Stream { read_timer, .. } = self;
match mem::replace(read_timer, StreamTimer::None) {
StreamTimer::Sleep(sleep) => Some(sleep),
StreamTimer::None | StreamTimer::WsHeartbeat { .. } => None,
}
};
let outcome: Option<Result<WebSocketParseStep, RequestError>> = {
let Stream {
stream,
request_config,
websocket_state,
ws_client_response,
..
} = self;
let mut reading: Pin<&mut _> = pin!(future::poll_fn(|cx: &mut Context<'_>| {
poll_websocket_transport_step(
stream,
request_config,
websocket_state,
ws_client_response,
cx,
)
}));
poll_with_timeout(reading.as_mut(), &mut timer_slot, duration).await
};
let Stream { read_timer, .. } = self;
*read_timer = match timer_slot {
Some(sleep) => StreamTimer::Sleep(sleep),
None => StreamTimer::None,
};
match outcome {
Some(result) => result,
None => self.handle_ws_heartbeat_tick().await,
}
}
/// Sends an RFC 6455 Ping probe on idle timeout, or fails with [`RequestError::ReadTimeout`].
///
/// Kept cold and boxed out of the primary read future to minimize idle WebSocket future size.
///
/// # Returns
///
/// - `Result<WebSocketParseStep, RequestError>` - `NeedMore` after ping, or `ReadTimeout`.
#[cold]
async fn handle_ws_heartbeat_tick(&mut self) -> Result<WebSocketParseStep, RequestError> {
let Stream {
ws_client_response, ..
} = self;
if !*ws_client_response {
return Err(RequestError::ReadTimeout(HttpStatus::RequestTimeout));
}
*ws_client_response = false;
self.try_send(&PING_FRAME).await?;
Ok(WebSocketParseStep::NeedMore)
}
/// Reads the next WebSocket step with optional shared-wheel or short-timeout heartbeat handling.
///
/// # Arguments
///
/// - `Option<u64>` - Adjusted ping timeout interval in milliseconds, or `None` when disabled.
///
/// # Returns
///
/// - `Result<WebSocketParseStep, RequestError>` - Parsed step, heartbeat probe, EOF, or error.
async fn read_next_websocket_step(
&mut self,
adjusted_timeout_opt: Option<u64>,
) -> Result<WebSocketParseStep, RequestError> {
if let Some(timeout_ms) = adjusted_timeout_opt
&& timeout_ms < WS_HEARTBEAT_MIN_WHEEL_MS
{
return Box::pin(self.read_ws_step_short_timeout(Duration::from_millis(timeout_ms)))
.await;
}
let timed_out: bool = {
let Stream {
stream,
request_config,
websocket_state,
ws_client_response,
read_timer,
..
} = self;
let hb_rx: Option<&mut Receiver<u64>> = match adjusted_timeout_opt {
None => {
if !matches!(read_timer, StreamTimer::None) {
*read_timer = StreamTimer::None;
}
None
}
Some(timeout_ms) => {
let needs_subscribe: bool = !matches!(
read_timer,
StreamTimer::WsHeartbeat { interval_ms, .. } if *interval_ms == timeout_ms
);
if needs_subscribe {
*read_timer = StreamTimer::WsHeartbeat {
rx: subscribe_ws_heartbeat(timeout_ms),
interval_ms: timeout_ms,
};
}
match read_timer {
StreamTimer::WsHeartbeat { rx, .. } => Some(rx),
StreamTimer::None | StreamTimer::Sleep(_) => None,
}
}
};
let mut reading: Pin<&mut _> = pin!(future::poll_fn(|cx: &mut Context<'_>| {
poll_websocket_transport_step(
stream,
request_config,
websocket_state,
ws_client_response,
cx,
)
}));
match hb_rx {
None => return reading.await,
Some(rx) => {
select! {
biased;
step = reading.as_mut() => return step,
tick = rx.changed() => tick.is_ok(),
}
}
}
};
if timed_out {
return Box::pin(self.handle_ws_heartbeat_tick()).await;
}
Ok(WebSocketParseStep::NeedMore)
}
/// Sends data over the stream.
///
/// # Arguments
///
/// - `D` - The data to send, which must implement `AsRef<[u8]>`.
///
/// # Returns
///
/// - `Result<(), ResponseError>` - Result indicating success or failure.
pub async fn try_send<D>(&mut self, data: D) -> Result<(), ResponseError>
where
D: AsRef<[u8]>,
{
if self.get_closed() {
return Err(ResponseError::ConnectionClosed);
}
Ok(self.get_mut_stream().write_all(data.as_ref()).await?)
}
/// Sends data over the stream.
///
/// # Arguments
///
/// - `D` - The data to send, which must implement `AsRef<[u8]>`.
///
/// # Panics
///
/// Panics if the write operation fails.
pub async fn send<D>(&mut self, data: D)
where
D: AsRef<[u8]>,
{
self.try_send(data).await.unwrap();
}
/// Sends multiple data.
///
/// # Arguments
///
/// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
/// `D` requiring the `AsRef<[u8]>` bound.
///
/// # Returns
///
/// - `Result<(), ResponseError>` - Result indicating success or failure.
pub async fn try_send_list<I, D>(&mut self, data_iter: I) -> Result<(), ResponseError>
where
I: IntoIterator<Item = D>,
D: AsRef<[u8]>,
{
if self.get_closed() {
return Err(ResponseError::ConnectionClosed);
}
let stream: &mut Box<dyn Transport> = self.get_mut_stream();
for data in data_iter {
stream.write_all(data.as_ref()).await?;
}
Ok(())
}
/// Sends multiple data.
///
/// # Arguments
///
/// - `I` - The data list to send, which must implement `IntoIterator<Item = D>` with
/// `D` requiring the `AsRef<[u8]>` bound.
///
/// # Panics
///
/// Panics if any write operation fails.
pub async fn send_list<I, D>(&mut self, data_iter: I)
where
I: IntoIterator<Item = D>,
D: AsRef<[u8]>,
{
self.try_send_list(data_iter).await.unwrap();
}
/// Flushes all buffered data to the stream.
///
/// # Returns
///
/// - `Result<(), ResponseError>` - Result indicating success or failure.
pub async fn try_flush(&mut self) -> Result<(), ResponseError> {
if self.get_closed() {
return Err(ResponseError::ConnectionClosed);
}
Ok(self.get_mut_stream().flush().await?)
}
/// Flushes all buffered data to the stream.
///
/// # Panics
///
/// Panics if the flush operation fails.
pub async fn flush(&mut self) {
self.try_flush().await.unwrap();
}
/// Returns whether lazy WebSocket frame-parser state is currently allocated.
#[cfg(test)]
pub(crate) fn has_websocket_state(&self) -> bool {
self.websocket_state.is_some()
}
}