use crate::error::WebDriverError;
use crate::{
extensions::query::{ElementPollerWithTimeout, IntoElementPoller},
prelude::WebDriverResult,
};
use const_format::formatcp;
use http::HeaderValue;
use std::sync::Arc;
use std::time::Duration;
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct WebDriverConfig {
pub keep_alive: bool,
pub poller: Arc<dyn IntoElementPoller + Send + Sync>,
pub user_agent: HeaderValue,
pub request_timeout: Duration,
}
impl Default for WebDriverConfig {
fn default() -> Self {
Self::builder().build().expect("default values failed")
}
}
impl WebDriverConfig {
pub fn builder() -> WebDriverConfigBuilder {
WebDriverConfigBuilder::new()
}
pub const DEFAULT_USER_AGENT: HeaderValue = {
const RUST_VER: &str = match option_env!("RUSTC_VERSION") {
Some(ver) => ver,
None => "unknown",
};
const HEADER: &str = formatcp!(
"thirtyfour/{} (rust/{}; {})",
crate::VERSION,
RUST_VER,
std::env::consts::OS
);
HeaderValue::from_static(HEADER)
};
}
#[derive(Debug)]
pub struct WebDriverConfigBuilder {
keep_alive: bool,
poller: Option<Arc<dyn IntoElementPoller + Send + Sync>>,
user_agent: Option<WebDriverResult<HeaderValue>>,
request_timeout: Duration,
}
impl Default for WebDriverConfigBuilder {
fn default() -> Self {
Self::new()
}
}
impl WebDriverConfigBuilder {
pub fn new() -> Self {
Self {
keep_alive: true,
poller: None,
user_agent: None,
request_timeout: Duration::from_secs(120),
}
}
pub fn keep_alive(mut self, keep_alive: bool) -> Self {
self.keep_alive = keep_alive;
self
}
pub fn poller(mut self, poller: Arc<dyn IntoElementPoller + Send + Sync>) -> Self {
self.poller = Some(poller);
self
}
pub fn user_agent<V>(mut self, user_agent: V) -> Self
where
HeaderValue: TryFrom<V>,
<HeaderValue as TryFrom<V>>::Error: Into<WebDriverError>,
{
self.user_agent = Some(user_agent.try_into().map_err(Into::into));
self
}
pub fn request_timeout(mut self, timeout: Duration) -> Self {
self.request_timeout = timeout;
self
}
pub fn build(self) -> WebDriverResult<WebDriverConfig> {
Ok(WebDriverConfig {
keep_alive: self.keep_alive,
poller: self.poller.unwrap_or_else(|| Arc::new(ElementPollerWithTimeout::default())),
user_agent: self.user_agent.transpose()?.unwrap_or(WebDriverConfig::DEFAULT_USER_AGENT),
request_timeout: self.request_timeout,
})
}
}