quarb_http/lib.rs
1//! The HTTP client the adapters share. Every request goes through
2//! one agent per thread with a connection timeout and a read/write
3//! timeout, so a service that stops answering fails the query with
4//! a message instead of hanging it. `QUARB_HTTP_TIMEOUT` (seconds)
5//! sets the read/write timeout; the connection timeout is 30 s.
6
7pub use ureq;
8
9/// The read/write timeout, in seconds, unless `QUARB_HTTP_TIMEOUT`
10/// says otherwise.
11const DEFAULT_TIMEOUT_SECS: u64 = 120;
12
13thread_local! {
14 static AGENT: ureq::Agent = build();
15}
16
17fn build() -> ureq::Agent {
18 let secs = std::env::var("QUARB_HTTP_TIMEOUT")
19 .ok()
20 .and_then(|s| s.trim().parse::<u64>().ok())
21 .filter(|&s| s > 0)
22 .unwrap_or(DEFAULT_TIMEOUT_SECS);
23 ureq::AgentBuilder::new()
24 .timeout_connect(std::time::Duration::from_secs(30))
25 .timeout_read(std::time::Duration::from_secs(secs))
26 .timeout_write(std::time::Duration::from_secs(secs))
27 .build()
28}
29
30/// The shared agent: `quarb_http::agent().get(url).call()`.
31pub fn agent() -> ureq::Agent {
32 AGENT.with(|a| a.clone())
33}