ureq/agent.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
use std::convert::TryFrom;
use std::fmt::Debug;
use std::sync::Arc;
use http::{Method, Request, Response, Uri};
use crate::body::Body;
use crate::config::{AgentScope, Config, ConfigBuilder, HttpCrateScope, RequestLevelConfig};
use crate::middleware::MiddlewareNext;
use crate::pool::ConnectionPool;
use crate::resolver::{DefaultResolver, Resolver};
use crate::send_body::AsSendBody;
use crate::transport::{Connector, DefaultConnector};
use crate::{Error, RequestBuilder, SendBody};
use crate::{WithBody, WithoutBody};
/// Agents keep state between requests.
///
/// By default, no state, such as cookies, is kept between requests.
/// But by creating an agent as entry point for the request, we
/// can keep a state.
///
/// # Example
///
/// ```no_run
/// let mut agent = ureq::agent();
///
/// agent
/// .post("http://example.com/post/login")
/// .send(b"my password")?;
///
/// let secret = agent
/// .get("http://example.com/get/my-protected-page")
/// .call()?
/// .body_mut()
/// .read_to_string()?;
///
/// println!("Secret is: {}", secret);
/// # Ok::<_, ureq::Error>(())
/// ```
///
/// # About threads and cloning
///
/// Agent uses inner [`Arc`]. Cloning an Agent results in an instance
/// that shares the same underlying connection pool and other state.
///
/// The connection pool contains an inner [`Mutex`][std::sync::Mutex] which is (briefly)
/// held when borrowing a pooled connection, or returning a connection to the pool.
///
/// All request functions in ureq have a signature similar to this:
///
/// ```
/// # use ureq::{Body, AsSendBody, Error};
/// fn run(request: http::Request<impl AsSendBody>) -> Result<http::Response<Body>, Error> {
/// // <something>
/// # todo!()
/// }
/// ```
///
/// It follows that:
///
/// * An Agent is borrowed for the duration of:
/// 1. Sending the request header ([`http::Request`])
/// 2. Sending the request body ([`SendBody`])
/// 3. Receiving the response header ([`http::Response`])
/// * The [`Body`] of the response is not bound to the lifetime of the Agent.
///
/// A response [`Body`] can be streamed (for instance via [`Body::into_reader()`]). The [`Body`]
/// implements [`Send`], which means it's possible to read the response body on another thread than
/// the one that run the request. Behind the scenes, the [`Body`] retains the connection to the remote
/// server and it is returned to the agent's pool, once the Body instance (or reader) is dropped.
///
/// There is an asymmetry in that sending a request body will borrow the Agent instance, while receiving
/// the response body does not. This inconvencience is somewhat mitigated by that [`Agent::run()`] (or
/// going via the methods such as [`Agent::get()`]), borrows `&self`, i.e. not exclusive `mut` borrows.
///
/// That cloning the agent shares the connection pool is considered a feature. It is often useful to
/// retain a single pool for the entire process, while dispatching requests from different threads.
/// And if we want separate pools, we can create multiple agents via one of the constructors
/// (such as [`Agent::new_with_config()`]).
///
/// Note that both [`Config::clone()`] and [`Agent::clone()`] are "cheap" meaning they should not
/// incur any heap allocation.
#[derive(Debug, Clone)]
pub struct Agent {
pub(crate) config: Arc<Config>,
pub(crate) pool: Arc<ConnectionPool>,
pub(crate) resolver: Arc<dyn Resolver>,
#[cfg(feature = "cookies")]
pub(crate) jar: Arc<crate::cookies::SharedCookieJar>,
}
impl Agent {
/// Creates an agent with defaults.
pub fn new_with_defaults() -> Self {
Self::with_parts(
Config::default(),
DefaultConnector::default(),
DefaultResolver::default(),
)
}
/// Creates an agent with config.
pub fn new_with_config(config: Config) -> Self {
Self::with_parts(
config,
DefaultConnector::default(),
DefaultResolver::default(),
)
}
/// Shortcut to reach a [`ConfigBuilder`]
///
/// This is the same as doing [`Config::builder()`].
pub fn config_builder() -> ConfigBuilder<AgentScope> {
Config::builder()
}
/// Creates an agent with a bespoke transport and resolver.
///
/// _This is low level API that isn't for regular use of ureq._
pub fn with_parts(config: Config, connector: impl Connector, resolver: impl Resolver) -> Self {
let pool = Arc::new(ConnectionPool::new(connector, &config));
Agent {
config: Arc::new(config),
pool,
resolver: Arc::new(resolver),
#[cfg(feature = "cookies")]
jar: Arc::new(crate::cookies::SharedCookieJar::new()),
}
}
/// Access the shared cookie jar.
///
/// Used to persist and manipulate the cookies. The jar is shared between
/// all clones of the same [`Agent`], meaning you must drop the CookieJar
/// before using the agent, or end up with a deadlock.
///
/// ```no_run
/// use std::io::Write;
/// use std::fs::File;
///
/// let agent = ureq::agent();
///
/// // Cookies set by www.google.com are stored in agent.
/// agent.get("https://www.google.com/").call()?;
///
/// // Saves (persistent) cookies
/// let mut file = File::create("cookies.json")?;
/// let jar = agent.cookie_jar_lock();
///
/// jar.save_json(&mut file)?;
///
/// // Release the cookie jar to use agents again.
/// jar.release();
///
/// # Ok::<_, ureq::Error>(())
/// ```
#[cfg(feature = "cookies")]
pub fn cookie_jar_lock(&self) -> crate::cookies::CookieJar<'_> {
self.jar.lock()
}
/// Run a [`http::Request<impl AsSendBody>`].
///
/// Used to execute http crate [`http::Request`] directly on this agent.
///
/// # Example
///
/// ```
/// use ureq::Agent;
///
/// let agent: Agent = Agent::new_with_defaults();
///
/// let mut request =
/// http::Request::get("http://httpbin.org/get")
/// .body(())?;
///
/// let body = agent.run(request)?
/// .body_mut()
/// .read_to_string()?;
/// # Ok::<(), ureq::Error>(())
/// ```
pub fn run(&self, request: Request<impl AsSendBody>) -> Result<Response<Body>, Error> {
let (parts, mut body) = request.into_parts();
let body = body.as_body();
let request = Request::from_parts(parts, ());
self.run_via_middleware(request, body)
}
pub(crate) fn run_via_middleware(
&self,
request: Request<()>,
body: SendBody,
) -> Result<Response<Body>, Error> {
let (parts, _) = request.into_parts();
let request = http::Request::from_parts(parts, body);
let next = MiddlewareNext::new(self);
next.handle(request)
}
/// Get the config for this agent.
pub fn config(&self) -> &Config {
&self.config
}
/// Alter the configuration for an http crate request.
///
/// Notice: It's an error to configure a [`http::Request`] using
/// one instance of [`Agent`] and run using another instance. The
/// library does not currently detect this situation, but it is
/// not considered a breaking change if this is enforced in
/// the future.
pub fn configure_request<S: AsSendBody>(
&self,
mut request: Request<S>,
) -> ConfigBuilder<HttpCrateScope<S>> {
let exts = request.extensions_mut();
if exts.get::<RequestLevelConfig>().is_none() {
exts.insert(self.new_request_level_config());
}
ConfigBuilder(HttpCrateScope(request))
}
pub(crate) fn new_request_level_config(&self) -> RequestLevelConfig {
RequestLevelConfig(self.config.as_ref().clone())
}
}
macro_rules! mk_method {
($(($f:tt, $m:tt, $b:ty)),*) => {
impl Agent {
$(
#[doc = concat!("Make a ", stringify!($m), " request using this agent.")]
#[must_use]
pub fn $f<T>(&self, uri: T) -> RequestBuilder<$b>
where
Uri: TryFrom<T>,
<Uri as TryFrom<T>>::Error: Into<http::Error>,
{
RequestBuilder::<$b>::new(self.clone(), Method::$m, uri)
}
)*
}
};
}
mk_method!(
(get, GET, WithoutBody),
(post, POST, WithBody),
(put, PUT, WithBody),
(delete, DELETE, WithoutBody),
(head, HEAD, WithoutBody),
(options, OPTIONS, WithoutBody),
(connect, CONNECT, WithoutBody),
(patch, PATCH, WithBody),
(trace, TRACE, WithoutBody)
);
impl From<Config> for Agent {
fn from(value: Config) -> Self {
Agent::new_with_config(value)
}
}
#[cfg(test)]
impl Agent {
pub fn pool_count(&self) -> usize {
self.pool.pool_count()
}
}
#[cfg(test)]
mod test {
use super::*;
use assert_no_alloc::*;
#[test]
fn agent_clone_does_not_allocate() {
let a = Agent::new_with_defaults();
assert_no_alloc(|| a.clone());
}
}