Skip to main content

HttpClientConfig

Struct HttpClientConfig 

Source
pub struct HttpClientConfig {
Show 13 fields pub request_timeout: Duration, pub total_timeout: Option<Duration>, pub max_body_size: usize, pub user_agent: String, pub retry: Option<RetryConfig>, pub rate_limit: Option<RateLimitConfig>, pub transport: TransportSecurity, pub tls_roots: TlsRootConfig, pub otel: bool, pub buffer_capacity: usize, pub redirect: RedirectConfig, pub pool_idle_timeout: Option<Duration>, pub pool_max_idle_per_host: usize,
}
Expand description

Overall HTTP client configuration

Fields§

§request_timeout: Duration

Per-request timeout (default: 30 seconds)

This timeout applies to each individual HTTP request/attempt. If retries are enabled, each retry attempt gets its own timeout.

§total_timeout: Option<Duration>

Total timeout spanning all retry attempts (default: None)

When set, the entire operation (including all retries and backoff delays) must complete within this duration. If the deadline is exceeded, the request fails with HttpError::DeadlineExceeded(total_timeout).

When None, there is no total deadline - each attempt can take up to request_timeout, and retries can continue indefinitely within their limits.

§max_body_size: usize

Maximum response body size in bytes (default: 10 MB)

§user_agent: String

User-Agent header value (default: “modkit-http/1.0”)

§retry: Option<RetryConfig>

Retry policy configuration

§rate_limit: Option<RateLimitConfig>

Rate limiting / concurrency configuration

§transport: TransportSecurity

Transport security mode (default: TlsOnly)

Use AllowInsecureHttp only for testing with local mock servers.

§tls_roots: TlsRootConfig

TLS root certificate strategy (default: WebPki)

§otel: bool

Enable OpenTelemetry tracing layer (default: false) Creates spans for outbound requests and injects trace context headers.

§buffer_capacity: usize

Buffer capacity for concurrent request handling (default: 1024)

The HTTP client uses an internal buffer to allow multiple concurrent requests without external locking. This sets the maximum number of requests that can be queued waiting for processing.

§redirect: RedirectConfig

Redirect policy configuration (default: same-origin only with header stripping)

Controls how 3xx redirect responses are handled with security protections:

  • Same-origin enforcement (SSRF protection)
  • Sensitive header stripping on cross-origin redirects
  • HTTPS downgrade protection

Use RedirectConfig::permissive() for general-purpose HTTP client behavior that allows cross-origin redirects with header stripping.

Use RedirectConfig::disabled() to turn off redirect following entirely.

§pool_idle_timeout: Option<Duration>

Timeout for idle connections in the pool (default: 90 seconds)

Connections that remain idle (unused) for longer than this duration will be closed and removed from the pool. This prevents resource leaks and ensures connections don’t become stale.

Set to None to use hyper-util’s default idle timeout.

§pool_max_idle_per_host: usize

Maximum number of idle connections per host (default: 32)

Limits how many idle connections are kept in the pool for each host. Setting this to 0 disables connection reuse entirely. Setting this too high may waste resources on rarely-used connections.

Note: This only limits idle connections. Active connections are not limited by this setting.

Implementations§

Source§

impl HttpClientConfig

Source

pub fn minimal() -> Self

Create minimal configuration (no retry, no rate limit, small timeout)

Source

pub fn infra_default() -> Self

Create configuration for infrastructure services (aggressive retry, large timeout)

Source

pub fn token_endpoint() -> Self

Create configuration for OAuth2 token endpoints (conservative retry)

Token endpoints use POST but are effectively idempotent for retry purposes:

  • Getting a token twice is safe (you’d just use the second one)
  • Transport errors before response mean no token was issued

This config retries on transport errors, timeout, and 429 for all methods.

Source

pub fn for_testing() -> Self

Create configuration for testing with mock servers (allows insecure HTTP)

WARNING: This configuration allows plain HTTP connections. Use only for local testing with mock servers, never in production.

Source

pub fn sse() -> Self

Create configuration optimized for Server-Sent Events (SSE) streaming.

SSE connections are long-lived HTTP requests where the server holds the connection open and pushes events. This preset disables retry and rate limiting, and sets a permissive request timeout.

§Timeout behavior

request_timeout is set to 24 hours rather than truly unlimited, because TimeoutLayer requires a finite Duration. Override if needed:

let mut config = HttpClientConfig::sse();
config.request_timeout = Duration::from_secs(3600); // 1 hour
let client = HttpClientBuilder::with_config(config).build()?;
§Streaming

Use [HttpResponse::into_body()] for streaming — it bypasses the max_body_size limit. SSE reconnection with Last-Event-ID is the caller’s responsibility.

let client = HttpClientBuilder::with_config(HttpClientConfig::sse()).build()?;

let response = client
    .get("https://api.example.com/events")
    .header("accept", "text/event-stream")
    .send()
    .await?;

let mut body = response.into_body();
while let Some(frame) = body.frame().await {
    let frame = frame?;
    if let Some(chunk) = frame.data_ref() {
        // parse SSE event data
    }
}

Trait Implementations§

Source§

impl Clone for HttpClientConfig

Source§

fn clone(&self) -> HttpClientConfig

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HttpClientConfig

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for HttpClientConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ServiceExt for T

Source§

fn decompression(self) -> Decompression<Self>
where Self: Sized,

Decompress response bodies. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
Source§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the Standard policy. Read more
Source§

fn set_request_id<M>( self, header_name: HeaderName, make_request_id: M, ) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension. Read more
Source§

fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension, using x-request-id as the header name. Read more
Source§

fn propagate_request_id( self, header_name: HeaderName, ) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses. Read more
Source§

fn propagate_x_request_id(self) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses, using x-request-id as the header name. Read more
Source§

fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>
where Self: Sized,

Intercept requests with over-sized payloads and convert them into 413 Payload Too Large responses. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more