use crate::SmolTransport;
use async_net::TcpStream;
use std::{
future::Future,
io::{Error, ErrorKind, Result},
};
use trillium_server_common::{
async_trait,
url::{Host, Url},
Connector, Transport,
};
#[derive(Default, Debug, Clone, Copy)]
pub struct ClientConfig {
pub nodelay: Option<bool>,
pub ttl: Option<u32>,
}
impl ClientConfig {
pub const fn new() -> Self {
Self {
nodelay: None,
ttl: None,
}
}
pub const fn with_nodelay(mut self, nodelay: bool) -> Self {
self.nodelay = Some(nodelay);
self
}
pub const fn with_ttl(mut self, ttl: u32) -> Self {
self.ttl = Some(ttl);
self
}
}
#[async_trait]
impl Connector for ClientConfig {
type Transport = SmolTransport<TcpStream>;
async fn connect(&self, url: &Url) -> Result<Self::Transport> {
if url.scheme() != "http" {
return Err(Error::new(
ErrorKind::InvalidInput,
format!("unknown scheme {}", url.scheme()),
));
}
let port = url
.port_or_known_default()
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("{url} missing port")))?;
let host = url
.host()
.ok_or_else(|| Error::new(ErrorKind::InvalidInput, format!("{url} missing host")))?;
let mut tcp = match host {
Host::Domain(domain) => Self::Transport::connect((domain, port)).await?,
Host::Ipv4(ip) => Self::Transport::connect((ip, port)).await?,
Host::Ipv6(ip) => Self::Transport::connect((ip, port)).await?,
};
if let Some(nodelay) = self.nodelay {
tcp.set_nodelay(nodelay)?;
}
if let Some(ttl) = self.ttl {
tcp.set_ip_ttl(ttl)?;
}
Ok(tcp)
}
fn spawn<Fut: Future<Output = ()> + Send + 'static>(&self, fut: Fut) {
async_global_executor::spawn(fut).detach();
}
}