1use std::fmt;
82use std::sync::atomic::{AtomicUsize, Ordering};
83use std::sync::Arc;
84
85use dashmap::DashMap;
86use tokio::sync::{OwnedSemaphorePermit, Semaphore};
87
88use crate::error::{Error, Result};
89
90#[derive(Debug, Clone, Default)]
107pub struct PoolConfig {
108 pub max_idle_connections: Option<usize>,
114 pub max_idle_connections_per_host: Option<usize>,
118 pub max_connections: Option<usize>,
124 pub max_connections_per_host: Option<usize>,
131 pub max_in_flight_requests: Option<usize>,
136 pub max_in_flight_requests_per_origin: Option<usize>,
140 pub idle_timeout: Option<std::time::Duration>,
147}
148
149impl PoolConfig {
150 #[must_use]
152 pub(crate) fn effective_max_in_flight(&self) -> Option<usize> {
153 self.max_in_flight_requests.or(self.max_connections)
154 }
155
156 #[must_use]
158 pub(crate) fn effective_max_in_flight_per_origin(&self) -> Option<usize> {
159 self.max_in_flight_requests_per_origin
160 .or(self.max_connections_per_host)
161 }
162
163 #[must_use]
171 pub(crate) fn effective_max_idle_per_host(&self) -> Option<usize> {
172 self.max_idle_connections_per_host
173 .or(self.max_idle_connections)
174 }
175}
176
177#[derive(Debug, Clone, PartialEq, Eq, Hash)]
185pub(crate) struct OriginKey {
186 scheme: String,
188 host: String,
190 port: u16,
192 proxy_host: Option<String>,
194 proxy_port: Option<u16>,
196 proxy_scheme: Option<String>,
199 is_tunnel: bool,
202}
203
204impl OriginKey {
205 pub(crate) fn from_url(scheme: &str, url: &url::Url) -> Option<Self> {
207 let host = url.host_str()?.to_owned();
208 let port = url.port_or_known_default()?;
209 Some(Self {
210 scheme: scheme.to_owned(),
211 host,
212 port,
213 proxy_host: None,
214 proxy_port: None,
215 proxy_scheme: None,
216 is_tunnel: false,
217 })
218 }
219
220 #[cfg(feature = "proxy")]
222 pub(crate) fn from_url_with_proxy_scheme(
223 scheme: &str,
224 url: &url::Url,
225 proxy_host: Option<&str>,
226 proxy_port: Option<u16>,
227 proxy_scheme: Option<&str>,
228 is_tunnel: bool,
229 ) -> Option<Self> {
230 let host = url.host_str()?.to_owned();
231 let port = url.port_or_known_default()?;
232 Some(Self {
233 scheme: scheme.to_owned(),
234 host,
235 port,
236 proxy_host: proxy_host.map(str::to_owned),
237 proxy_port,
238 proxy_scheme: proxy_scheme.map(str::to_owned),
239 is_tunnel,
240 })
241 }
242
243 #[cfg(any(test, feature = "test-util"))]
246 #[allow(dead_code)]
247 pub(crate) fn from_parts(scheme: &str, host: &str, port: u16) -> Self {
248 Self {
249 scheme: scheme.to_owned(),
250 host: host.to_owned(),
251 port,
252 proxy_host: None,
253 proxy_port: None,
254 proxy_scheme: None,
255 is_tunnel: false,
256 }
257 }
258
259 #[cfg(all(feature = "proxy", any(test, feature = "test-util")))]
262 #[allow(dead_code)]
263 pub(crate) fn from_parts_with_proxy(
264 scheme: &str,
265 host: &str,
266 port: u16,
267 proxy_host: Option<&str>,
268 proxy_port: Option<u16>,
269 proxy_scheme: Option<&str>,
270 is_tunnel: bool,
271 ) -> Self {
272 Self {
273 scheme: scheme.to_owned(),
274 host: host.to_owned(),
275 port,
276 proxy_host: proxy_host.map(str::to_owned),
277 proxy_port,
278 proxy_scheme: proxy_scheme.map(str::to_owned),
279 is_tunnel,
280 }
281 }
282
283 #[cfg(any(test, feature = "test-util"))]
285 #[allow(dead_code)]
286 pub(crate) fn scheme(&self) -> &str {
287 &self.scheme
288 }
289
290 pub(crate) fn host(&self) -> &str {
292 &self.host
293 }
294
295 #[cfg(any(test, feature = "test-util"))]
297 #[allow(dead_code)]
298 pub(crate) fn port(&self) -> u16 {
299 self.port
300 }
301
302 #[cfg(any(test, feature = "test-util"))]
304 #[allow(dead_code)]
305 pub(crate) fn proxy_host(&self) -> Option<&str> {
306 self.proxy_host.as_deref()
307 }
308
309 #[cfg(any(test, feature = "test-util"))]
311 #[allow(dead_code)]
312 pub(crate) fn proxy_port(&self) -> Option<u16> {
313 self.proxy_port
314 }
315
316 #[cfg(any(test, feature = "test-util"))]
318 #[allow(dead_code)]
319 pub(crate) fn is_tunnel(&self) -> bool {
320 self.is_tunnel
321 }
322}
323
324impl fmt::Display for OriginKey {
325 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
326 write!(f, "{}://{}:{}", self.scheme, self.host, self.port)?;
327 if let (Some(ref ph), Some(pp)) = (&self.proxy_host, self.proxy_port) {
328 if let Some(ref scheme) = self.proxy_scheme {
329 write!(f, " via {scheme}://{ph}:{pp}")?;
330 } else {
331 write!(f, " via {ph}:{pp}")?;
332 }
333 if self.is_tunnel {
334 write!(f, " tunnel")?;
335 }
336 }
337 Ok(())
338 }
339}
340
341#[derive(Debug, Default)]
364pub struct PoolMetrics {
365 pub acquisition_waits: AtomicUsize,
367 pub acquisition_cancellations: AtomicUsize,
369}
370
371pub struct PoolGuard {
375 pool: Arc<PoolInner>,
376 pub(crate) origin: Option<OriginKey>,
377 #[allow(dead_code)]
381 pub(crate) global_permit: Option<OwnedSemaphorePermit>,
382 #[allow(dead_code)]
383 pub(crate) origin_permit: Option<OwnedSemaphorePermit>,
384}
385
386impl PoolGuard {
387 fn new(
389 pool: Arc<PoolInner>,
390 origin: Option<OriginKey>,
391 global_permit: Option<OwnedSemaphorePermit>,
392 origin_permit: Option<OwnedSemaphorePermit>,
393 ) -> Self {
394 Self {
395 pool,
396 origin,
397 global_permit,
398 origin_permit,
399 }
400 }
401
402 #[must_use]
404 #[allow(dead_code)] pub(crate) fn origin(&self) -> Option<&OriginKey> {
406 self.origin.as_ref()
407 }
408
409 #[allow(dead_code)]
411 pub fn host(&self) -> Option<&str> {
412 self.origin.as_ref().map(OriginKey::host)
413 }
414
415 #[must_use]
417 pub fn metrics(&self) -> &PoolMetrics {
418 &self.pool.metrics
419 }
420}
421
422impl Drop for PoolGuard {
423 fn drop(&mut self) {
424 }
427}
428
429struct PoolInner {
431 global_semaphore: Option<Arc<Semaphore>>,
433 per_origin: DashMap<OriginKey, Arc<PerOriginSemaphore>>,
435 per_origin_table_lock: tokio::sync::Mutex<()>,
441 config: PoolConfig,
443 metrics: PoolMetrics,
445}
446
447struct PerOriginSemaphore {
452 semaphore: Arc<Semaphore>,
453 waiters: AtomicUsize,
454}
455
456impl PerOriginSemaphore {
457 fn new(max_per_origin: usize) -> Self {
458 Self {
459 semaphore: Arc::new(Semaphore::new(max_per_origin)),
460 waiters: AtomicUsize::new(0),
461 }
462 }
463}
464
465struct WaiterGuard {
471 entry: Arc<PerOriginSemaphore>,
472}
473
474impl WaiterGuard {
475 fn new(entry: Arc<PerOriginSemaphore>) -> Self {
476 entry.waiters.fetch_add(1, Ordering::AcqRel);
477 Self { entry }
478 }
479}
480
481impl Drop for WaiterGuard {
482 fn drop(&mut self) {
483 self.entry.waiters.fetch_sub(1, Ordering::AcqRel);
484 }
485}
486
487#[derive(Clone)]
504pub struct Pool {
505 inner: Arc<PoolInner>,
506}
507
508impl Pool {
509 #[must_use]
511 pub fn new(config: PoolConfig) -> Self {
512 let global_semaphore = config
513 .effective_max_in_flight()
514 .map(|n| Arc::new(Semaphore::new(n)));
515
516 Self {
517 inner: Arc::new(PoolInner {
518 global_semaphore,
519 per_origin: DashMap::new(),
520 per_origin_table_lock: tokio::sync::Mutex::new(()),
521 config,
522 metrics: PoolMetrics::default(),
523 }),
524 }
525 }
526
527 #[must_use]
533 pub(crate) fn idle_timeout(&self) -> Option<std::time::Duration> {
534 self.inner.config.idle_timeout
535 }
536
537 #[must_use]
544 pub(crate) fn max_idle_per_host(&self) -> Option<usize> {
545 self.inner.config.effective_max_idle_per_host()
546 }
547
548 pub(crate) async fn acquire(&self, origin: Option<&OriginKey>) -> Result<PoolGuard> {
561 let mut waited = false;
562 let mut global_permit: Option<OwnedSemaphorePermit> = None;
563 let mut origin_permit: Option<OwnedSemaphorePermit> = None;
564
565 if let Some(ref sem) = self.inner.global_semaphore {
568 if let Ok(permit) = sem.clone().try_acquire_owned() {
569 global_permit = Some(permit);
570 } else if let Ok(permit) = sem.clone().acquire_owned().await {
571 global_permit = Some(permit);
572 waited = true;
573 } else {
574 self.inner
575 .metrics
576 .acquisition_cancellations
577 .fetch_add(1, Ordering::Relaxed);
578 return Err(Error::Pool("global semaphore is closed".into()));
579 }
580 }
581
582 if let (Some(max_per_origin), Some(origin)) = (
585 self.inner.config.effective_max_in_flight_per_origin(),
586 origin,
587 ) {
588 let entry = if let Some(entry) = self.inner.per_origin.get(origin) {
594 entry.clone()
595 } else {
596 let table_lock = self.inner.per_origin_table_lock.lock().await;
607 let entry = if let Some(entry) = self.inner.per_origin.get(origin) {
608 entry.clone()
609 } else {
610 self.inner.per_origin.retain(|_, entry| {
611 entry.semaphore.available_permits() < max_per_origin
612 || entry.waiters.load(Ordering::Acquire) > 0
613 });
614 self.inner
615 .per_origin
616 .entry(origin.clone())
617 .or_insert_with(|| Arc::new(PerOriginSemaphore::new(max_per_origin)))
618 .clone()
619 };
620 drop(table_lock);
621 entry
622 };
623
624 let mut waiter_guard = Some(WaiterGuard::new(Arc::clone(&entry)));
627 if let Ok(permit) = entry.semaphore.clone().try_acquire_owned() {
631 waiter_guard.take();
632 origin_permit = Some(permit);
633 } else {
634 let permit = entry.semaphore.clone().acquire_owned().await;
635 waiter_guard.take();
636 if let Ok(permit) = permit {
637 origin_permit = Some(permit);
638 waited = true;
639 } else {
640 self.inner
641 .metrics
642 .acquisition_cancellations
643 .fetch_add(1, Ordering::Relaxed);
644 drop(global_permit);
645 return Err(Error::Pool("per-origin semaphore is closed".into()));
646 }
647 }
648 }
649
650 if waited {
651 self.inner
652 .metrics
653 .acquisition_waits
654 .fetch_add(1, Ordering::Relaxed);
655 }
656
657 Ok(PoolGuard::new(
658 self.inner.clone(),
659 origin.cloned(),
660 global_permit,
661 origin_permit,
662 ))
663 }
664
665 #[must_use]
667 pub fn metrics(&self) -> &PoolMetrics {
668 &self.inner.metrics
669 }
670}
671
672#[cfg(test)]
673mod tests {
674 use super::*;
675
676 #[test]
677 fn default_config_has_no_limits() {
678 let config = PoolConfig::default();
679 assert!(config.max_idle_connections.is_none());
680 assert!(config.max_idle_connections_per_host.is_none());
681 assert!(config.max_connections.is_none());
682 assert!(config.max_connections_per_host.is_none());
683 assert!(config.max_in_flight_requests.is_none());
684 assert!(config.max_in_flight_requests_per_origin.is_none());
685 assert!(config.idle_timeout.is_none());
686 }
687
688 #[test]
689 fn effective_limits_prefer_new_names() {
690 let config = PoolConfig {
691 max_connections: Some(10),
692 max_in_flight_requests: Some(7),
693 max_connections_per_host: Some(5),
694 max_in_flight_requests_per_origin: Some(3),
695 ..PoolConfig::default()
696 };
697 assert_eq!(config.effective_max_in_flight(), Some(7));
698 assert_eq!(config.effective_max_in_flight_per_origin(), Some(3));
699 }
700
701 #[test]
702 fn effective_limits_fall_back_to_aliases() {
703 let config = PoolConfig {
704 max_connections: Some(10),
705 max_connections_per_host: Some(5),
706 ..PoolConfig::default()
707 };
708 assert_eq!(config.effective_max_in_flight(), Some(10));
709 assert_eq!(config.effective_max_in_flight_per_origin(), Some(5));
710 }
711
712 #[test]
713 fn effective_idle_cap_prefers_per_host() {
714 let config = PoolConfig {
715 max_idle_connections: Some(20),
716 max_idle_connections_per_host: Some(7),
717 ..PoolConfig::default()
718 };
719 assert_eq!(config.effective_max_idle_per_host(), Some(7));
720 let pool = Pool::new(config);
721 assert_eq!(pool.max_idle_per_host(), Some(7));
722 }
723
724 #[test]
725 fn effective_idle_cap_falls_back_to_global() {
726 let config = PoolConfig {
727 max_idle_connections: Some(20),
728 ..PoolConfig::default()
729 };
730 assert_eq!(config.effective_max_idle_per_host(), Some(20));
731 let pool = Pool::new(config);
732 assert_eq!(pool.max_idle_per_host(), Some(20));
733 }
734
735 #[test]
736 fn effective_idle_cap_absent_when_unset() {
737 let pool = Pool::new(PoolConfig::default());
738 assert_eq!(pool.max_idle_per_host(), None);
739 assert_eq!(pool.idle_timeout(), None);
740 }
741
742 #[tokio::test]
743 async fn new_names_enforce_logical_concurrency() {
744 let pool = Pool::new(PoolConfig {
747 max_in_flight_requests_per_origin: Some(1),
748 ..PoolConfig::default()
749 });
750 let origin = OriginKey::from_parts("http", "example.com", 80);
751 let _guard = pool.acquire(Some(&origin)).await.unwrap();
752 assert!(
753 tokio::time::timeout(
754 std::time::Duration::from_millis(10),
755 pool.acquire(Some(&origin))
756 )
757 .await
758 .is_err(),
759 "second logical request must wait while first holds its permit"
760 );
761 }
762
763 #[test]
764 fn pool_constructs_with_defaults() {
765 let pool = Pool::new(PoolConfig::default());
766 assert!(pool.inner.global_semaphore.is_none());
767 assert!(pool.inner.per_origin.is_empty());
768 }
769
770 #[test]
771 fn pool_constructs_with_global_limit() {
772 let config = PoolConfig {
773 max_connections: Some(10),
774 ..Default::default()
775 };
776 let pool = Pool::new(config);
777 assert!(pool.inner.global_semaphore.is_some());
778 }
779
780 #[test]
781 fn pool_metrics_starts_zeroed() {
782 let pool = Pool::new(PoolConfig::default());
783 let metrics = pool.metrics();
784 assert_eq!(metrics.acquisition_waits.load(Ordering::Relaxed), 0);
785 assert_eq!(metrics.acquisition_cancellations.load(Ordering::Relaxed), 0);
786 }
787
788 #[tokio::test]
789 async fn acquire_without_limits_returns_immediately() {
790 let pool = Pool::new(PoolConfig::default());
791 let guard = pool.acquire(None).await.unwrap();
792 assert!(guard.origin().is_none());
793 }
794
795 #[tokio::test]
796 async fn acquire_with_global_limit() {
797 let config = PoolConfig {
798 max_connections: Some(2),
799 ..Default::default()
800 };
801 let pool = Pool::new(config);
802
803 let origin = OriginKey::from_parts("http", "example.com", 80);
804 let g1 = pool.acquire(Some(&origin)).await.unwrap();
805 let g2 = pool.acquire(Some(&origin)).await.unwrap();
806
807 assert_eq!(pool.metrics().acquisition_waits.load(Ordering::Relaxed), 0);
809
810 drop(g1);
811 drop(g2);
812 }
813
814 #[tokio::test]
815 async fn acquire_with_per_origin_limit() {
816 let config = PoolConfig {
817 max_connections_per_host: Some(1),
818 ..Default::default()
819 };
820 let pool = Pool::new(config);
821
822 let origin = OriginKey::from_parts("http", "example.com", 80);
823 let g1 = pool.acquire(Some(&origin)).await.unwrap();
824 assert_eq!(pool.metrics().acquisition_waits.load(Ordering::Relaxed), 0);
825
826 drop(g1);
827 }
828
829 #[tokio::test]
830 async fn closed_semaphores_count_cancellation_without_a_wait() {
831 let global_pool = Pool::new(PoolConfig {
832 max_connections: Some(1),
833 ..Default::default()
834 });
835 let global_guard = global_pool.acquire(None).await.unwrap();
836 global_pool.inner.global_semaphore.as_ref().unwrap().close();
837 assert!(global_pool.acquire(None).await.is_err());
838 assert_eq!(
839 global_pool
840 .metrics()
841 .acquisition_waits
842 .load(Ordering::Relaxed),
843 0
844 );
845 assert_eq!(
846 global_pool
847 .metrics()
848 .acquisition_cancellations
849 .load(Ordering::Relaxed),
850 1
851 );
852 drop(global_guard);
853
854 let origin_pool = Pool::new(PoolConfig {
855 max_connections_per_host: Some(1),
856 ..Default::default()
857 });
858 let origin = OriginKey::from_parts("http", "example.com", 80);
859 let origin_guard = origin_pool.acquire(Some(&origin)).await.unwrap();
860 origin_pool
861 .inner
862 .per_origin
863 .get(&origin)
864 .unwrap()
865 .semaphore
866 .close();
867 assert!(origin_pool.acquire(Some(&origin)).await.is_err());
868 assert_eq!(
869 origin_pool
870 .metrics()
871 .acquisition_waits
872 .load(Ordering::Relaxed),
873 0
874 );
875 assert_eq!(
876 origin_pool
877 .metrics()
878 .acquisition_cancellations
879 .load(Ordering::Relaxed),
880 1
881 );
882 drop(origin_guard);
883 }
884
885 #[test]
886 fn pool_is_clone() {
887 let pool = Pool::new(PoolConfig::default());
888 let pool2 = pool.clone();
889 assert!(Arc::ptr_eq(&pool.inner, &pool2.inner));
891 }
892
893 #[tokio::test]
894 async fn acquire_per_origin_limit_separate_origins() {
895 let config = PoolConfig {
896 max_connections_per_host: Some(1),
897 ..Default::default()
898 };
899 let pool = Pool::new(config);
900 let o1 = OriginKey::from_parts("http", "host-a", 80);
901 let o2 = OriginKey::from_parts("http", "host-b", 80);
902 let g1 = pool.acquire(Some(&o1)).await.unwrap();
903 let g2 = pool.acquire(Some(&o2)).await.unwrap();
904 assert!(g1.origin().is_some());
905 assert!(g2.origin().is_some());
906 drop(g1);
907 drop(g2);
908 }
909
910 #[test]
911 fn origin_key_from_url_http() {
912 let url = url::Url::parse("http://example.com:8080/path").unwrap();
913 let key = OriginKey::from_url("http", &url).unwrap();
914 assert_eq!(key.scheme(), "http");
915 assert_eq!(key.host(), "example.com");
916 assert_eq!(key.port(), 8080);
917 }
918
919 #[test]
920 fn origin_key_from_url_https_default_port() {
921 let url = url::Url::parse("https://example.com/path").unwrap();
922 let key = OriginKey::from_url("https", &url).unwrap();
923 assert_eq!(key.scheme(), "https");
924 assert_eq!(key.host(), "example.com");
925 assert_eq!(key.port(), 443);
926 }
927
928 #[test]
929 fn origin_key_from_url_http_default_port() {
930 let url = url::Url::parse("http://example.com/path").unwrap();
931 let key = OriginKey::from_url("http", &url).unwrap();
932 assert_eq!(key.scheme(), "http");
933 assert_eq!(key.port(), 80);
934 }
935
936 #[test]
937 fn origin_keys_distinguish_scheme() {
938 let http = OriginKey::from_parts("http", "example.com", 80);
939 let https = OriginKey::from_parts("https", "example.com", 443);
940 assert_ne!(http, https);
941 }
942
943 #[test]
944 fn origin_keys_distinguish_port() {
945 let p80 = OriginKey::from_parts("http", "example.com", 80);
946 let p8080 = OriginKey::from_parts("http", "example.com", 8080);
947 assert_ne!(p80, p8080);
948 }
949
950 #[test]
951 fn origin_keys_equal_for_same_origin() {
952 let a = OriginKey::from_parts("http", "example.com", 80);
953 let b = OriginKey::from_parts("http", "example.com", 80);
954 assert_eq!(a, b);
955 }
956
957 #[test]
958 fn origin_key_display() {
959 let key = OriginKey::from_parts("https", "example.com", 443);
960 assert_eq!(key.to_string(), "https://example.com:443");
961 }
962
963 #[tokio::test]
964 async fn origin_keys_separate_per_origin_map_entries() {
965 let config = PoolConfig {
966 max_connections_per_host: Some(1),
967 ..Default::default()
968 };
969 let pool = Pool::new(config);
970 let a = OriginKey::from_parts("http", "example.com", 80);
971 let b = OriginKey::from_parts("http", "example.com", 8080);
972 assert!(pool.acquire(Some(&a)).await.unwrap().origin().is_some());
973 assert!(pool.acquire(Some(&b)).await.unwrap().origin().is_some());
974 }
975
976 #[test]
977 fn origin_keys_distinct_by_scheme() {
978 let http = OriginKey::from_parts("http", "example.com", 443);
980 let https = OriginKey::from_parts("https", "example.com", 443);
981 assert_ne!(http, https);
982 }
983
984 #[test]
985 fn origin_key_from_url_uses_scheme_default_port() {
986 let explicit = url::Url::parse("http://example.com:8080/path").unwrap();
988 let default = url::Url::parse("http://example.com/path").unwrap();
989 let k_explicit = OriginKey::from_url("http", &explicit).unwrap();
990 let k_default = OriginKey::from_url("http", &default).unwrap();
991 assert_eq!(k_explicit.port(), 8080);
992 assert_eq!(k_default.port(), 80);
993 }
994
995 #[test]
996 fn origin_key_direct_has_no_proxy() {
997 let key = OriginKey::from_parts("http", "example.com", 80);
998 assert!(key.proxy_host().is_none());
999 assert!(key.proxy_port().is_none());
1000 assert!(!key.is_tunnel());
1001 }
1002
1003 #[cfg(feature = "proxy")]
1004 #[test]
1005 fn origin_key_proxy_a_not_equal_proxy_b() {
1006 let url = url::Url::parse("http://example.com/path").unwrap();
1007 let a = OriginKey::from_url_with_proxy_scheme(
1008 "http",
1009 &url,
1010 Some("proxy-a"),
1011 Some(8080),
1012 None,
1013 false,
1014 )
1015 .unwrap();
1016 let b = OriginKey::from_url_with_proxy_scheme(
1017 "http",
1018 &url,
1019 Some("proxy-b"),
1020 Some(8080),
1021 None,
1022 false,
1023 )
1024 .unwrap();
1025 assert_ne!(a, b);
1026 }
1027
1028 #[cfg(feature = "proxy")]
1029 #[test]
1030 fn origin_key_tunnel_not_equal_non_tunnel() {
1031 let url = url::Url::parse("http://example.com/path").unwrap();
1032 let tunnel = OriginKey::from_url_with_proxy_scheme(
1033 "http",
1034 &url,
1035 Some("proxy"),
1036 Some(8080),
1037 None,
1038 true,
1039 )
1040 .unwrap();
1041 let direct = OriginKey::from_url_with_proxy_scheme(
1042 "http",
1043 &url,
1044 Some("proxy"),
1045 Some(8080),
1046 None,
1047 false,
1048 )
1049 .unwrap();
1050 assert_ne!(tunnel, direct);
1051 }
1052
1053 #[cfg(feature = "proxy")]
1054 #[test]
1055 fn origin_key_proxy_same_route_equal() {
1056 let url = url::Url::parse("http://example.com/path").unwrap();
1057 let a = OriginKey::from_url_with_proxy_scheme(
1058 "http",
1059 &url,
1060 Some("proxy"),
1061 Some(8080),
1062 None,
1063 false,
1064 )
1065 .unwrap();
1066 let b = OriginKey::from_url_with_proxy_scheme(
1067 "http",
1068 &url,
1069 Some("proxy"),
1070 Some(8080),
1071 None,
1072 false,
1073 )
1074 .unwrap();
1075 assert_eq!(a, b);
1076 }
1077
1078 #[cfg(feature = "proxy")]
1079 #[test]
1080 fn origin_key_parts_preserves_proxy_scheme() {
1081 let http = OriginKey::from_parts_with_proxy(
1082 "https",
1083 "example.com",
1084 443,
1085 Some("proxy"),
1086 Some(8080),
1087 Some("http"),
1088 true,
1089 );
1090 let https = OriginKey::from_parts_with_proxy(
1091 "https",
1092 "example.com",
1093 443,
1094 Some("proxy"),
1095 Some(8080),
1096 Some("https"),
1097 true,
1098 );
1099 assert_ne!(http, https);
1100 assert_eq!(
1101 http.to_string(),
1102 "https://example.com:443 via http://proxy:8080 tunnel"
1103 );
1104 }
1105
1106 #[cfg(feature = "proxy")]
1107 #[test]
1108 fn origin_key_display_with_proxy() {
1109 let url = url::Url::parse("https://example.com/path").unwrap();
1110 let key = OriginKey::from_url_with_proxy_scheme(
1111 "https",
1112 &url,
1113 Some("proxy"),
1114 Some(8080),
1115 None,
1116 true,
1117 )
1118 .unwrap();
1119 assert_eq!(
1120 key.to_string(),
1121 "https://example.com:443 via proxy:8080 tunnel"
1122 );
1123 }
1124
1125 #[cfg(feature = "proxy")]
1126 #[test]
1127 fn origin_key_display_without_tunnel() {
1128 let url = url::Url::parse("http://example.com/path").unwrap();
1129 let key = OriginKey::from_url_with_proxy_scheme(
1130 "http",
1131 &url,
1132 Some("proxy"),
1133 Some(8080),
1134 None,
1135 false,
1136 )
1137 .unwrap();
1138 assert_eq!(key.to_string(), "http://example.com:80 via proxy:8080");
1139 }
1140
1141 #[cfg(feature = "proxy")]
1142 #[tokio::test]
1143 async fn proxy_route_separate_from_direct() {
1144 let config = PoolConfig {
1145 max_connections_per_host: Some(1),
1146 ..Default::default()
1147 };
1148 let pool = Pool::new(config);
1149 let direct = OriginKey::from_parts("http", "example.com", 80);
1150 let proxied = OriginKey::from_parts_with_proxy(
1151 "http",
1152 "example.com",
1153 80,
1154 Some("proxy"),
1155 Some(8080),
1156 None,
1157 false,
1158 );
1159 let g1 = pool.acquire(Some(&direct)).await.unwrap();
1160 let g2 = pool.acquire(Some(&proxied)).await.unwrap();
1161 assert!(g1.origin().is_some());
1162 assert!(g2.origin().is_some());
1163 }
1164
1165 #[tokio::test]
1166 async fn global_wait_does_not_hold_per_origin_slot() {
1167 let pool = Pool::new(PoolConfig {
1168 max_connections: Some(1),
1169 max_connections_per_host: Some(1),
1170 ..Default::default()
1171 });
1172 let first_origin = OriginKey::from_parts("http", "first.example", 80);
1173 let waiting_origin = OriginKey::from_parts("http", "waiting.example", 80);
1174 let first = pool.acquire(Some(&first_origin)).await.unwrap();
1175
1176 let pool_for_task = pool.clone();
1177 let waiting_origin_for_task = waiting_origin.clone();
1178 let waiter =
1179 tokio::spawn(
1180 async move { pool_for_task.acquire(Some(&waiting_origin_for_task)).await },
1181 );
1182 for _ in 0..3 {
1183 tokio::task::yield_now().await;
1184 }
1185
1186 assert!(pool.inner.per_origin.get(&waiting_origin).is_none());
1187 drop(first);
1188 drop(waiter.await.unwrap().unwrap());
1189 }
1190
1191 #[tokio::test]
1192 async fn idle_per_origin_entries_are_swept_on_acquire() {
1193 let pool = Pool::new(PoolConfig {
1194 max_connections_per_host: Some(1),
1195 ..Default::default()
1196 });
1197
1198 for index in 0..8 {
1199 let origin = OriginKey::from_parts("http", &format!("host-{index}.example"), 80);
1200 drop(pool.acquire(Some(&origin)).await.unwrap());
1201 }
1202
1203 assert!(pool.inner.per_origin.len() <= 8);
1210 if std::env::var("EGGFETCH_STRICT_POOL_EVICTION").is_ok() {
1214 assert!(pool.inner.per_origin.len() <= 1);
1215 }
1216 }
1217
1218 #[cfg(feature = "proxy")]
1219 #[tokio::test]
1220 async fn tunnel_separate_from_non_tunnel() {
1221 let config = PoolConfig {
1222 max_connections_per_host: Some(1),
1223 ..Default::default()
1224 };
1225 let pool = Pool::new(config);
1226 let http_fwd = OriginKey::from_parts_with_proxy(
1227 "http",
1228 "example.com",
1229 80,
1230 Some("proxy"),
1231 Some(8080),
1232 None,
1233 false,
1234 );
1235 let https_tunnel = OriginKey::from_parts_with_proxy(
1236 "http",
1237 "example.com",
1238 80,
1239 Some("proxy"),
1240 Some(8080),
1241 None,
1242 true,
1243 );
1244 let g1 = pool.acquire(Some(&http_fwd)).await.unwrap();
1245 let g2 = pool.acquire(Some(&https_tunnel)).await.unwrap();
1246 assert!(g1.origin().is_some());
1247 assert!(g2.origin().is_some());
1248 }
1249
1250 #[cfg(feature = "proxy")]
1251 #[tokio::test]
1252 async fn different_proxies_separate_semaphores() {
1253 let config = PoolConfig {
1254 max_connections_per_host: Some(1),
1255 ..Default::default()
1256 };
1257 let pool = Pool::new(config);
1258 let a = OriginKey::from_parts_with_proxy(
1259 "http",
1260 "example.com",
1261 80,
1262 Some("proxy-a"),
1263 Some(8080),
1264 None,
1265 false,
1266 );
1267 let b = OriginKey::from_parts_with_proxy(
1268 "http",
1269 "example.com",
1270 80,
1271 Some("proxy-b"),
1272 Some(8080),
1273 None,
1274 false,
1275 );
1276 let g1 = pool.acquire(Some(&a)).await.unwrap();
1277 let g2 = pool.acquire(Some(&b)).await.unwrap();
1278 assert!(g1.origin().is_some());
1279 assert!(g2.origin().is_some());
1280 }
1281}