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
//! Validated explicit client policy; construction performs no network I/O.
use super::ClientError;
use axum::http::HeaderMap;
use std::time::Duration;
/// Independent active-operation, queue, time, and byte allowances.
#[derive(Clone, Copy, Debug)]
pub struct ClientLimits {
/// Active exchanges, held through response-body completion/drop; default 32.
pub max_in_flight: usize,
/// Waiting callers before immediate rejection; default 64, zero disables waiting.
pub max_waiters: usize,
/// Capacity-wait budget within the original total deadline; default 100 ms.
pub capacity_timeout: Duration,
/// Native connection/TLS establishment allowance; default three seconds.
pub connect_timeout: Duration,
/// Native read and caller-held body progress allowance; default five seconds.
pub read_timeout: Duration,
/// Entire operation from capacity wait through body consumption; default ten seconds.
pub total_timeout: Duration,
/// Reusable idle connections per origin, independent of active capacity; default eight.
pub max_idle_connections: usize,
/// Maximum supplied request bytes; default 1 MiB.
pub max_request_bytes: usize,
/// Maximum total delivered response bytes, decoded when enabled; default 1 MiB.
pub max_response_bytes: usize,
/// Maximum encoded/wire response-body bytes, independent of decoding; default 1 MiB.
pub max_response_wire_bytes: usize,
}
impl Default for ClientLimits {
fn default() -> Self {
Self {
max_in_flight: 32,
max_waiters: 64,
capacity_timeout: Duration::from_millis(100),
connect_timeout: Duration::from_secs(3),
read_timeout: Duration::from_secs(5),
total_timeout: Duration::from_secs(10),
max_idle_connections: 8,
max_request_bytes: 1024 * 1024,
max_response_bytes: 1024 * 1024,
max_response_wire_bytes: 1024 * 1024,
}
}
}
impl ClientLimits {
fn validate(self) -> Result<(), ClientError> {
if !(1..=1024).contains(&self.max_in_flight)
|| self.max_waiters > 1024
|| self.max_idle_connections > 1024
|| !(1..=16 * 1024 * 1024).contains(&self.max_request_bytes)
|| !(1..=16 * 1024 * 1024).contains(&self.max_response_bytes)
|| !(1..=16 * 1024 * 1024).contains(&self.max_response_wire_bytes)
|| [
self.capacity_timeout,
self.connect_timeout,
self.read_timeout,
self.total_timeout,
]
.iter()
.any(|duration| duration.is_zero() || *duration > Duration::from_secs(86400))
{
return Err(ClientError::Configuration);
}
Ok(())
}
}
/// One explicit HTTP(S) origin, bounded transport policy, and optional credentials.
#[derive(Clone)]
pub struct ClientConfig {
pub(super) origin: url::Url,
pub(super) limits: ClientLimits,
pub(super) headers: HeaderMap,
root: Option<reqwest::Certificate>,
pub(super) gzip: bool,
#[cfg(feature = "otel")]
pub(super) trace_context: bool,
}
impl std::fmt::Debug for ClientConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ClientConfig")
.field("origin", &"[redacted]")
.field("headers", &"[redacted]")
.field("limits", &self.limits)
.field("explicit_trust_root", &self.root.is_some())
.field("gzip", &self.gzip)
.finish()
}
}
impl ClientConfig {
/// Approve an origin such as `https://catalog.example:443` (no userinfo/path/query).
/// HTTPS verifies hostnames and platform trust. An explicit `http://` origin
/// selects plaintext; there is no silent downgrade or redirect following.
pub fn new(origin: &str) -> Result<Self, ClientError> {
Ok(Self {
origin: super::target::origin(origin)?,
limits: ClientLimits::default(),
headers: HeaderMap::new(),
root: None,
gzip: false,
#[cfg(feature = "otel")]
trace_context: false,
})
}
/// Set finite allowances; timeouts must be positive and at most 24 hours.
pub fn with_limits(mut self, limits: ClientLimits) -> Result<Self, ClientError> {
limits.validate()?;
self.limits = limits;
Ok(self)
}
/// Use only the supplied PEM root (at most 64 KiB) instead of platform roots.
/// Hostname/certificate verification remains enabled.
pub fn with_root_certificate(mut self, pem: &[u8]) -> Result<Self, ClientError> {
if pem.is_empty() || pem.len() > 65536 {
return Err(ClientError::Configuration);
}
self.root =
Some(reqwest::Certificate::from_pem(pem).map_err(|_| ClientError::Configuration)?);
Ok(self)
}
/// Add a fixed header, applied only after destination validation. Values are
/// sensitive in Debug. Headers are bounded to 32 names and 16 KiB total.
pub fn with_header(mut self, name: &str, value: &str) -> Result<Self, ClientError> {
super::target::header(&mut self.headers, name, value)?;
Ok(self)
}
/// Explicitly approve W3C trace-context propagation to this client's origin.
/// Disabled by default, even with `otel`. Baggage is never propagated; redirects
/// remain disabled. Trace identity is diagnostic metadata, not authentication.
#[cfg(feature = "otel")]
pub fn with_trace_context(mut self, enabled: bool) -> Self {
self.trace_context = enabled;
self
}
/// Opt into gzip negotiation and native multi-member decoding. Disabled by default.
/// Response limits count decoded bytes for both buffered and chunked consumption.
/// Requests are not compressed. Native decoding removes Content-Encoding and
/// Content-Length metadata from decoded responses; other formats stay disabled.
pub fn with_gzip(mut self, enabled: bool) -> Self {
self.gzip = enabled;
self
}
pub(super) fn build(&self) -> Result<reqwest::Client, ClientError> {
if self.root.is_none()
&& ["SSL_CERT_FILE", "SSL_CERT_DIR"]
.iter()
.any(|name| std::env::var_os(name).is_some())
{
return Err(ClientError::AmbientConfiguration);
}
let mut builder = reqwest::Client::builder()
.no_proxy()
.http1_only()
.redirect(reqwest::redirect::Policy::none())
.retry(reqwest::retry::never())
.connect_timeout(self.limits.connect_timeout)
.read_timeout(self.limits.read_timeout)
.timeout(self.limits.total_timeout)
.pool_max_idle_per_host(self.limits.max_idle_connections)
.pool_idle_timeout(Duration::from_secs(60))
.no_gzip()
.no_brotli()
.no_deflate()
.no_zstd();
if let Some(root) = &self.root {
builder = builder.tls_certs_only([root.clone()]);
}
builder.build().map_err(|_| ClientError::Configuration)
}
}