Skip to main content

leyline/core/session/
helpers.rs

1use http::Method;
2
3use crate::cookie::Jar;
4use crate::profile::{Browser, Preset};
5
6use super::{Session, SessionBuilder};
7use crate::core::request::RequestBuilder;
8use crate::core::retry::RetryPolicy;
9use crate::core::{
10    Body, IntoUrl, ProxyConfig, ProxyUrl, RedirectPolicy, Response, Result, TimeoutConfig,
11};
12
13impl Session {
14    pub fn builder() -> SessionBuilder {
15        SessionBuilder::new()
16    }
17
18    pub fn new() -> Self {
19        Self::builder().into_builtin()
20    }
21
22    pub fn browser(browser: Browser) -> Self {
23        Self::builder().browser(browser).into_builtin()
24    }
25
26    pub fn tab(&self) -> crate::core::Tab {
27        crate::core::Tab::new(self.clone())
28    }
29
30    pub fn cookies(&self) -> &Jar {
31        &self.inner.cookie_jar
32    }
33
34    pub fn with_proxy(&self, config: impl Into<ProxyConfig>) -> Self {
35        let config = config.into();
36        self.derive(|inner| inner.proxy_config = config)
37    }
38
39    pub fn proxy_url(&self) -> Option<ProxyUrl> {
40        self.inner.proxy_config.primary().map(ProxyUrl::configured)
41    }
42
43    pub fn fresh_pool(&self) -> Self {
44        self.derive(|inner| {
45            inner.pool = std::sync::Arc::new(inner.pool.fresh());
46            inner.connector = inner.connector.with_fresh_session_cache();
47        })
48    }
49
50    pub fn with_cookie_jar(&self, jar: Jar) -> Self {
51        self.derive(|inner| inner.cookie_jar = jar)
52    }
53
54    pub fn with_redirect(&self, policy: RedirectPolicy) -> Self {
55        self.derive(|inner| inner.redirect_policy = policy)
56    }
57
58    pub fn with_base_url(&self, url: impl IntoUrl) -> Result<Self> {
59        let url = base_url(url)?;
60        Ok(self.derive(|inner| inner.base_url = Some(url)))
61    }
62
63    pub(crate) fn base_url(&self) -> Option<&url::Url> {
64        self.inner.base_url.as_ref()
65    }
66
67    fn derive(&self, change: impl FnOnce(&mut super::SessionInner)) -> Self {
68        let mut s = self.clone();
69        change(std::sync::Arc::make_mut(&mut s.inner));
70        s
71    }
72
73    pub fn host_stats(&self) -> Vec<crate::core::config::HostStats> {
74        self.inner.host_limits.stats()
75    }
76
77    pub(crate) fn host_limits(&self) -> &crate::core::config::HostLimits {
78        &self.inner.host_limits
79    }
80
81    pub(crate) fn proxy_pool(&self) -> Option<&crate::core::proxy_pool::ProxyPool> {
82        self.inner.proxy_pool.as_ref()
83    }
84
85    pub(crate) fn without_proxy_pool(&self) -> Self {
86        self.derive(|inner| inner.proxy_pool = None)
87    }
88
89    pub(crate) fn downgrade(&self) -> std::sync::Weak<super::SessionInner> {
90        std::sync::Arc::downgrade(&self.inner)
91    }
92
93    pub(crate) fn is_inner(&self, weak: &std::sync::Weak<super::SessionInner>) -> bool {
94        std::ptr::eq(weak.as_ptr(), std::sync::Arc::as_ptr(&self.inner))
95    }
96
97    pub(crate) fn impersonates(&self) -> bool {
98        self.inner.impersonates
99    }
100
101    pub(crate) fn default_retry(&self) -> &crate::core::retry::RetryPolicy {
102        &self.inner.default_retry
103    }
104
105    pub fn pool_stats(&self) -> crate::PoolStats {
106        self.inner.pool.stats()
107    }
108
109    pub async fn preconnect(&self, url: impl IntoUrl) -> Result<()> {
110        let url = url.into_url()?;
111        if url.scheme() != "https" || self.inner.protocol_policy == super::ProtocolPolicy::Http1 {
112            return Ok(());
113        }
114        let host = url.host_str().unwrap_or("");
115        let port = url.port_or_known_default().unwrap_or(443);
116        let proxy = self.proxy_for(&url, None)?;
117        let opened = crate::pool::checkout_handle(
118            &self.inner.pool,
119            &self.inner.connector,
120            &self.inner.h2_config,
121            host,
122            port,
123            proxy,
124        )
125        .await;
126        match opened {
127            Ok(_) => Ok(()),
128            Err(error) if error.alpn().is_some() => {
129                self.inner.pool.note_h1_only(host, port, proxy);
130                Ok(())
131            }
132            Err(error) => Err(error),
133        }
134    }
135
136    pub fn request(&self, method: Method, url: impl IntoUrl) -> RequestBuilder {
137        RequestBuilder::from_url(self, method, url)
138    }
139
140    pub async fn execute(&self, req: http::Request<Body>) -> Result<Response> {
141        self.http_request(req).send().await
142    }
143
144    pub(crate) fn http_request(&self, req: http::Request<Body>) -> RequestBuilder {
145        let (mut parts, body) = req.into_parts();
146        let mut builder = RequestBuilder::new(self, parts.method, &parts.uri.to_string());
147        for (name, value) in &parts.headers {
148            builder = builder.header(name.clone(), value.clone());
149        }
150        builder = builder.body(body);
151        if let Some(preset) = parts.extensions.remove::<Preset>() {
152            builder = builder.preset(preset);
153        }
154        if let Some(timeouts) = parts.extensions.remove::<TimeoutConfig>() {
155            builder = builder.timeout(timeouts);
156        }
157        if let Some(policy) = parts.extensions.remove::<RetryPolicy>() {
158            builder = builder.retry(policy);
159        }
160        if let Some(policy) = parts.extensions.remove::<RedirectPolicy>() {
161            builder = builder.redirect(policy);
162        }
163        if let Some(proxy) = parts.extensions.remove::<ProxyConfig>() {
164            builder = builder.proxy(proxy);
165        }
166        builder
167    }
168
169    pub fn get(&self, url: impl IntoUrl) -> RequestBuilder {
170        RequestBuilder::from_url(self, Method::GET, url)
171    }
172
173    pub fn post(&self, url: impl IntoUrl) -> RequestBuilder {
174        RequestBuilder::from_url(self, Method::POST, url)
175    }
176
177    pub fn put(&self, url: impl IntoUrl) -> RequestBuilder {
178        RequestBuilder::from_url(self, Method::PUT, url)
179    }
180
181    pub fn patch(&self, url: impl IntoUrl) -> RequestBuilder {
182        RequestBuilder::from_url(self, Method::PATCH, url)
183    }
184
185    pub fn delete(&self, url: impl IntoUrl) -> RequestBuilder {
186        RequestBuilder::from_url(self, Method::DELETE, url)
187    }
188
189    pub fn head(&self, url: impl IntoUrl) -> RequestBuilder {
190        RequestBuilder::from_url(self, Method::HEAD, url)
191    }
192}
193
194pub(super) fn base_url(url: impl IntoUrl) -> Result<url::Url> {
195    let url = url.into_url()?;
196    if url.cannot_be_a_base() {
197        return Err(
198            crate::core::error::Error::new(crate::core::error::Kind::Config)
199                .with_message(format!("base URL {url} cannot be a base")),
200        );
201    }
202    Ok(url)
203}
204
205impl Default for Session {
206    fn default() -> Self {
207        Self::new()
208    }
209}
210
211impl std::fmt::Debug for Session {
212    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
213        let mut debug = f.debug_struct("Session");
214        debug
215            .field("browser", &self.inner.browser)
216            .field("platform", &self.inner.platform)
217            .field(
218                "proxy",
219                &self.inner.proxy_config.primary().map(crate::util::redact),
220            )
221            .field("timeout", &self.inner.timeouts.total_limit())
222            .field("protocol_policy", &self.inner.protocol_policy);
223        if let Some(audit) = &self.inner.audit_tls {
224            debug.field("ja4", &audit.ja4);
225        }
226        debug.finish()
227    }
228}
229
230impl std::fmt::Display for Session {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        let label = match self.inner.browser {
233            Some(browser) => browser.to_string(),
234            None if self.inner.impersonates => self.inner.profile.meta.name.clone(),
235            None => "bare".to_string(),
236        };
237        let config = &self.inner.proxy_config;
238        let proxy = match config.primary() {
239            _ if config.rejects() => "rejected".into(),
240            Some(url) => crate::util::redact(url),
241            None => "none".into(),
242        };
243        write!(
244            f,
245            "Session({label}, {}, proxy={proxy})",
246            self.inner.platform
247        )
248    }
249}