1use std::{cell::Ref, cell::RefCell, cell::RefMut, fmt, net, rc::Rc};
2
3use bitflags::bitflags;
4use ntex_h2::StreamRef;
5use urly::Url;
6
7use crate::http::header::HeaderMap;
8use crate::http::{HeaderItem, Method, StatusCode, Version, h1::Codec};
9use crate::io::{IoBoxed, IoRef, types};
10use crate::util::{ByteString, Extensions};
11
12#[derive(Copy, Clone, PartialEq, Eq, Debug)]
14pub enum ConnectionType {
15 Close,
17 KeepAlive,
19 Upgrade,
21}
22
23bitflags! {
24 #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
25 pub(crate) struct Flags: u8 {
26 const CLOSE = 0b0000_0001;
27 const KEEP_ALIVE = 0b0000_0010;
28 const UPGRADE = 0b0000_0100;
29 const EXPECT = 0b0000_1000;
30 const NO_CHUNKING = 0b0001_0000;
31 }
32}
33
34pub(crate) trait Head: Default + 'static + fmt::Debug {
35 fn clear(&mut self);
36
37 fn with_pool<F, R>(f: F) -> Option<R>
39 where
40 F: FnOnce(&MessagePool<Self>) -> R;
41}
42
43#[derive(Clone, Debug)]
44pub(crate) enum CurrentIo {
45 Ref(IoRef),
46 Io(Rc<dyn IoAccess>),
47 None,
48}
49
50pub(crate) trait IoAccess: fmt::Debug {
51 fn get(&self) -> Option<&IoRef>;
52
53 fn take(&self) -> Option<(IoBoxed, Codec)>;
54}
55
56impl CurrentIo {
57 pub(crate) fn new(io: Rc<dyn IoAccess>) -> Self {
58 CurrentIo::Io(io)
59 }
60
61 pub(crate) fn as_ref(&self) -> Option<&IoRef> {
62 match self {
63 CurrentIo::Ref(io) => Some(io),
64 CurrentIo::Io(io) => io.get(),
65 CurrentIo::None => None,
66 }
67 }
68
69 pub(crate) fn take(&self) -> Option<(IoBoxed, Codec)> {
70 match self {
71 CurrentIo::Io(io) => io.take(),
72 _ => None,
73 }
74 }
75}
76
77#[derive(Debug)]
79pub struct RequestHead {
80 pub id: usize,
82 pub uri: Url,
88 pub method: Method,
90 pub version: Version,
92 pub headers: HeaderMap,
94 pub headers_vec: Vec<HeaderItem>,
100 pub extensions: RefCell<Extensions>,
102 pub(crate) stream: Option<StreamRef>,
104 pub(crate) scheme: Option<ByteString>,
106 pub(crate) authority: Option<ByteString>,
108 pub(crate) io: CurrentIo,
109 pub(crate) flags: Flags,
110}
111
112impl Default for RequestHead {
113 fn default() -> RequestHead {
114 RequestHead {
115 id: 0,
116 stream: None,
117 scheme: None,
118 authority: None,
119 io: CurrentIo::None,
120 uri: Url::new(),
121 method: Method::default(),
122 version: Version::HTTP_11,
123 headers: HeaderMap::with_capacity(16),
124 headers_vec: Vec::default(),
125 flags: Flags::empty(),
126 extensions: RefCell::new(Extensions::new()),
127 }
128 }
129}
130
131impl Head for RequestHead {
132 fn clear(&mut self) {
133 self.io = CurrentIo::None;
134 self.uri = Url::new();
137 self.scheme = None;
138 self.authority = None;
139 self.flags = Flags::empty();
140 self.version = Version::HTTP_11;
141 self.headers.clear();
142 self.headers_vec.clear();
143 self.extensions.get_mut().clear();
144 self.stream = None;
145 }
146
147 fn with_pool<F, R>(f: F) -> Option<R>
148 where
149 F: FnOnce(&MessagePool<Self>) -> R,
150 {
151 REQUEST_POOL.try_with(|p| f(p)).ok()
152 }
153}
154
155impl RequestHead {
156 pub fn scheme(&self) -> Option<&str> {
163 self.uri.scheme_str().or(self.scheme.as_deref())
164 }
165
166 pub fn authority(&self) -> Option<&str> {
173 self.uri
174 .authority()
175 .map(urly::Authority::as_str)
176 .or(self.authority.as_deref())
177 }
178
179 #[inline]
181 pub fn extensions(&self) -> Ref<'_, Extensions> {
182 self.extensions.borrow()
183 }
184
185 #[inline]
187 pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
188 self.extensions.borrow_mut()
189 }
190
191 pub fn headers(&self) -> &HeaderMap {
193 &self.headers
194 }
195
196 pub fn headers_mut(&mut self) -> &mut HeaderMap {
198 &mut self.headers
199 }
200
201 pub fn headers_vec(&self) -> &[HeaderItem] {
203 &self.headers_vec
204 }
205
206 #[inline]
207 pub fn set_connection_type(&mut self, ctype: ConnectionType) {
213 match ctype {
214 ConnectionType::Close => self.flags.insert(Flags::CLOSE),
215 ConnectionType::KeepAlive => self.flags.insert(Flags::KEEP_ALIVE),
216 ConnectionType::Upgrade => self.flags.insert(Flags::UPGRADE),
217 }
218 }
219
220 #[inline]
221 pub fn connection_type(&self) -> ConnectionType {
223 if self.flags.contains(Flags::CLOSE) {
224 ConnectionType::Close
225 } else if self.flags.contains(Flags::KEEP_ALIVE) {
226 ConnectionType::KeepAlive
227 } else if self.flags.contains(Flags::UPGRADE) {
228 ConnectionType::Upgrade
229 } else if self.version < Version::HTTP_11 {
230 ConnectionType::Close
231 } else {
232 ConnectionType::KeepAlive
233 }
234 }
235
236 #[inline]
237 pub fn upgrade(&self) -> bool {
239 self.flags.contains(Flags::UPGRADE)
240 }
241
242 #[inline]
243 pub fn expect(&self) -> bool {
245 self.flags.contains(Flags::EXPECT)
246 }
247
248 #[inline]
249 pub fn chunked(&self) -> bool {
251 !self.flags.contains(Flags::NO_CHUNKING)
252 }
253
254 #[inline]
255 pub fn no_chunking(&mut self, val: bool) {
259 if val {
260 self.flags.insert(Flags::NO_CHUNKING);
261 } else {
262 self.flags.remove(Flags::NO_CHUNKING);
263 }
264 }
265
266 #[inline]
267 pub(crate) fn set_expect(&mut self) {
268 self.flags.insert(Flags::EXPECT);
269 }
270
271 #[inline]
272 pub(crate) fn set_upgrade(&mut self) {
273 self.flags.insert(Flags::UPGRADE);
274 }
275
276 pub(crate) fn set_stream(&mut self, stream: StreamRef) {
277 self.stream = Some(stream);
278 }
279
280 pub fn stream(&self) -> Option<&StreamRef> {
281 self.stream.as_ref()
282 }
283
284 #[inline]
289 pub fn peer_addr(&self) -> Option<net::SocketAddr> {
290 self.io.as_ref().and_then(|io| {
291 io.query::<types::PeerAddr>()
292 .get()
293 .map(types::PeerAddr::into_inner)
294 })
295 }
296
297 pub fn take_io(&self) -> Option<(IoBoxed, Codec)> {
304 self.io.take()
305 }
306
307 #[doc(hidden)]
308 pub fn remove_io(&mut self) {
309 self.io = CurrentIo::None;
310 }
311}
312
313#[derive(Debug)]
315pub struct ResponseHead {
316 pub version: Version,
318 pub status: StatusCode,
320 pub headers: HeaderMap,
322 pub headers_vec: Vec<HeaderItem>,
328 pub reason: Option<&'static str>,
330 pub(crate) io: CurrentIo,
331 pub(crate) extensions: RefCell<Extensions>,
332 pub(crate) flags: Flags,
333}
334
335impl ResponseHead {
336 #[inline]
338 pub fn new(status: StatusCode, version: Version) -> ResponseHead {
339 ResponseHead {
340 status,
341 version,
342 headers: HeaderMap::with_capacity(12),
343 headers_vec: Vec::default(),
344 reason: None,
345 flags: Flags::empty(),
346 io: CurrentIo::None,
347 extensions: RefCell::new(Extensions::new()),
348 }
349 }
350
351 #[inline]
353 pub fn extensions(&self) -> Ref<'_, Extensions> {
354 self.extensions.borrow()
355 }
356
357 #[inline]
359 pub fn extensions_mut(&self) -> RefMut<'_, Extensions> {
360 self.extensions.borrow_mut()
361 }
362
363 #[inline]
364 pub fn headers(&self) -> &HeaderMap {
366 &self.headers
367 }
368
369 #[inline]
370 pub fn headers_mut(&mut self) -> &mut HeaderMap {
372 &mut self.headers
373 }
374
375 pub fn headers_vec(&self) -> &[HeaderItem] {
377 &self.headers_vec
378 }
379
380 #[inline]
381 pub fn set_connection_type(&mut self, ctype: ConnectionType) {
387 match ctype {
388 ConnectionType::Close => self.flags.insert(Flags::CLOSE),
389 ConnectionType::KeepAlive => self.flags.insert(Flags::KEEP_ALIVE),
390 ConnectionType::Upgrade => self.flags.insert(Flags::UPGRADE),
391 }
392 }
393
394 #[inline]
395 pub fn connection_type(&self) -> ConnectionType {
397 if self.flags.contains(Flags::CLOSE) {
398 ConnectionType::Close
399 } else if self.flags.contains(Flags::KEEP_ALIVE) {
400 ConnectionType::KeepAlive
401 } else if self.flags.contains(Flags::UPGRADE) {
402 ConnectionType::Upgrade
403 } else if self.version < Version::HTTP_11 {
404 ConnectionType::Close
405 } else {
406 ConnectionType::KeepAlive
407 }
408 }
409
410 #[inline]
411 pub fn keep_alive(&self) -> bool {
413 self.connection_type() == ConnectionType::KeepAlive
414 }
415
416 #[inline]
417 pub fn upgrade(&self) -> bool {
419 self.connection_type() == ConnectionType::Upgrade
420 }
421
422 #[inline]
426 pub fn reason(&self) -> &str {
427 if let Some(reason) = self.reason {
428 reason
429 } else {
430 self.status.canonical_reason().unwrap_or("")
431 }
432 }
433
434 #[inline]
435 pub(crate) fn ctype(&self) -> Option<ConnectionType> {
436 if self.flags.contains(Flags::CLOSE) {
437 Some(ConnectionType::Close)
438 } else if self.flags.contains(Flags::KEEP_ALIVE) {
439 Some(ConnectionType::KeepAlive)
440 } else if self.flags.contains(Flags::UPGRADE) {
441 Some(ConnectionType::Upgrade)
442 } else {
443 None
444 }
445 }
446
447 #[inline]
448 pub fn chunked(&self) -> bool {
450 !self.flags.contains(Flags::NO_CHUNKING)
451 }
452
453 #[inline]
454 pub fn no_chunking(&mut self, val: bool) {
456 if val {
457 self.flags.insert(Flags::NO_CHUNKING);
458 } else {
459 self.flags.remove(Flags::NO_CHUNKING);
460 }
461 }
462}
463
464impl Default for ResponseHead {
465 fn default() -> Self {
466 Self::new(StatusCode::default(), Version::default())
467 }
468}
469
470impl Head for ResponseHead {
471 fn clear(&mut self) {
472 self.reason = None;
473 self.headers.clear();
474 self.headers_vec.clear();
475 self.io = CurrentIo::None;
476 self.flags = Flags::empty();
477 self.extensions.get_mut().clear();
478 }
479
480 fn with_pool<F, R>(f: F) -> Option<R>
481 where
482 F: FnOnce(&MessagePool<Self>) -> R,
483 {
484 RESPONSE_POOL.try_with(|p| f(p)).ok()
485 }
486}
487
488#[derive(Debug)]
489pub(crate) struct Message<T: Head> {
490 head: Rc<T>,
491}
492
493impl<T: Head> Message<T> {
494 pub(crate) fn new() -> Self {
496 let head = T::with_pool(MessagePool::get_head)
497 .flatten()
498 .unwrap_or_else(|| Rc::new(T::default()));
499 Message { head }
500 }
501
502 pub(crate) fn clear(&mut self) {
504 if let Some(head) = Rc::get_mut(&mut self.head) {
505 head.clear();
506 }
507 }
508}
509
510impl Message<ResponseHead> {
511 pub(crate) fn with_status(status: StatusCode) -> Self {
513 let mut msg = Self::new();
514 msg.status = status;
515 msg
516 }
517
518 pub(crate) fn copy(&self) -> Self {
520 let mut msg = Self::with_status(self.status);
521 msg.version = self.version;
522 msg.headers = self.headers.clone();
523 msg.headers_vec.clone_from(&self.headers_vec);
524 msg.reason = self.reason;
525 msg.io = self.io.clone();
526 msg.flags = self.flags;
527 msg
528 }
529}
530
531impl<T: Head> Clone for Message<T> {
532 fn clone(&self) -> Self {
533 Self {
534 head: self.head.clone(),
535 }
536 }
537}
538
539impl<T: Head> std::ops::Deref for Message<T> {
540 type Target = T;
541
542 fn deref(&self) -> &Self::Target {
543 self.head.as_ref()
544 }
545}
546
547impl<T: Head> std::ops::DerefMut for Message<T> {
548 fn deref_mut(&mut self) -> &mut Self::Target {
549 Rc::get_mut(&mut self.head).expect("Multiple copies exist")
550 }
551}
552
553impl<T: Head> Drop for Message<T> {
554 fn drop(&mut self) {
555 let Some(head) = Rc::get_mut(&mut self.head) else {
556 return;
557 };
558 if !T::with_pool(MessagePool::has_room).unwrap_or(false) {
561 return;
562 }
563 head.clear();
566 T::with_pool(|pool| {
567 if let Ok(mut v) = pool.0.try_borrow_mut()
568 && v.len() < POOL_CAP
569 {
570 v.push(self.head.clone());
571 }
572 });
573 }
574}
575
576const POOL_CAP: usize = 128;
578
579pub(crate) struct MessagePool<T: Head>(RefCell<Vec<Rc<T>>>);
581
582thread_local!(static REQUEST_POOL: MessagePool<RequestHead> = MessagePool::<RequestHead>::new());
583thread_local!(static RESPONSE_POOL: MessagePool<ResponseHead> = MessagePool::<ResponseHead>::new());
584
585impl<T: Head> MessagePool<T> {
586 fn new() -> MessagePool<T> {
587 MessagePool(RefCell::new(Vec::with_capacity(256)))
588 }
589
590 #[inline]
592 fn get_head(&self) -> Option<Rc<T>> {
593 self.0.try_borrow_mut().ok()?.pop()
594 }
595
596 fn has_room(&self) -> bool {
597 self.0.try_borrow().is_ok_and(|v| v.len() < POOL_CAP)
598 }
599}
600
601#[cfg(test)]
602mod tests {
603 use super::*;
604
605 #[test]
610 fn nested_message_drop() {
611 let inner = Message::<RequestHead>::new();
612 let outer = Message::<RequestHead>::new();
613 outer.extensions_mut().insert(inner);
614 let mut res = Message::<ResponseHead>::with_status(StatusCode::OK);
615 res.extensions
616 .get_mut()
617 .insert(Message::<ResponseHead>::new());
618 outer.extensions_mut().insert(res);
619 drop(outer);
620
621 let _ = Message::<RequestHead>::new();
622 let _ = Message::<ResponseHead>::new();
623 }
624
625 #[test]
631 fn message_drop_after_pool_destroyed() {
632 struct Holder(Option<Message<RequestHead>>, Option<Message<ResponseHead>>);
633
634 impl Drop for Holder {
635 fn drop(&mut self) {
636 drop(self.0.take());
637 drop(self.1.take());
638 drop(Message::<RequestHead>::new());
639 }
640 }
641
642 thread_local!(static HOLDER: RefCell<Option<Holder>> = const { RefCell::new(None) });
643
644 std::thread::spawn(|| {
645 HOLDER.with(|_| ());
647 let req = Message::<RequestHead>::new();
648 let res = Message::<ResponseHead>::new();
649 HOLDER.with(|h| *h.borrow_mut() = Some(Holder(Some(req), Some(res))));
650 })
651 .join()
652 .unwrap();
653 }
654
655 #[test]
660 fn response_connection_type() {
661 let mut res = Message::<ResponseHead>::with_status(StatusCode::OK);
662 assert_eq!(res.connection_type(), ConnectionType::KeepAlive);
663 res.version = Version::HTTP_10;
664 assert_eq!(res.connection_type(), ConnectionType::Close);
665 res.set_connection_type(ConnectionType::KeepAlive);
666 assert_eq!(res.connection_type(), ConnectionType::KeepAlive);
667 }
668
669 #[test]
674 fn message_clone() {
675 let mut msg = Message::<RequestHead>::new();
676 msg.method = Method::POST;
677 let msg2 = msg.clone();
678 assert_eq!(msg2.method, Method::POST);
679 assert!(CurrentIo::None.take().is_none());
680 }
681}