Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 8 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,14 @@ eggfetch targets HTTPX 0.28.1 compatibility in measured phases. Phase 0 establis

Key differences from HTTPX:
- **Redirect default**: eggfetch does NOT follow redirects by default (HTTPX does)
- **Proxy env vars**: eggfetch does not read `HTTP_PROXY`/`HTTPS_PROXY` (HTTPX does)
- **Event hooks**: Not yet implemented (tracked as required-later)
- **WSGI/ASGI transports**: Not applicable (eggfetch is a network client)

Phase 1 (production semantics) closes these gaps:
- **Timeout defaults**: `Timeout::compat()` provides HTTPX's 5-second network timeout defaults; `Timeout::native()` provides eggfetch's 30-second defaults.
- **Resource limits**: `Limits` object provides HTTPX-compatible pool concurrency control (100 max connections, 20 keep-alive, 5s expiry).
- **Environment trust**: `trust_env=True` (default) reads `HTTP_PROXY`/`HTTPS_PROXY`/`ALL_PROXY`/`NO_PROXY` env vars.

See [`compat/httpx/0.28.1/`](compat/httpx/0.28.1/) for the full profile and [`docs/reference/compatibility.md`](docs/reference/compatibility.md) for the feature matrix.

## Target API Shapes
Expand All @@ -87,7 +91,7 @@ print(r.headers)
print(r.text)
r.raise_for_status()

with httpx.Client(headers={"User-Agent": "eggfetch"}) as client:
with httpx.Client(headers={"User-Agent": "eggfetch"}, limits=httpx.Limits(max_connections=100)) as client:
r = client.post(
"https://example.com/api",
json={"a": 1},
Expand Down Expand Up @@ -148,6 +152,7 @@ The core HTTP engine is implemented with the following capabilities:
Connection pooling and reuse is implemented with the following capabilities:

- **Connection pooling** -- HTTP/1.1 keep-alive connection reuse via hyper-util's built-in pool.
- **Limits model** -- `Limits` type provides HTTPX-compatible resource limits (`max_connections`, `max_keepalive_connections`, `keepalive_expiry`). `Limits::compat()` returns HTTPX defaults (100 connections, 20 keep-alive, 5s expiry).
- **Max connections per host** -- configurable limit via `PoolConfig::max_connections`.
- **Idle timeout** -- connections closed after a configurable idle period via `PoolConfig::idle_timeout`.
- **Pool metrics** -- `PoolMetrics` exposed via `Client::pool_metrics()` and `ClientBuilder::pool_metrics()`.
Expand All @@ -158,6 +163,7 @@ Connection pooling and reuse is implemented with the following capabilities:
Phase-aware timeout behavior is implemented with the following capabilities:

- **Timeout configuration** -- `Timeout` type with per-phase durations (pool, connect, write, read, total).
- **Named timeout defaults** -- `Timeout::compat()` (HTTPX-compatible 5s all phases) and `Timeout::native()` (eggfetch 30s per-phase, no total).
- **Client-level timeouts** -- set via `ClientBuilder::timeout()`.
- **Request-level timeouts** -- set via `RequestBuilder::timeout()`, overriding client defaults per-field.
- **Pool timeout** -- time waiting for a connection slot from the pool. Enforced via `tokio::time::timeout` around acquisition.
Expand Down
10 changes: 5 additions & 5 deletions compat/httpx/0.28.1/allowed-differences.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ tests = ["test_differential.py::TestRedirectDefault", "test_differential.py::Tes

[[difference]]
id = "PROXY-ENV-001"
category = "required-later"
category = "resolved"
symbol = "httpx.Client(proxy=...)"
behavior-case = "proxy-env-vars"
reference-behavior = "HTTPX reads HTTP_PROXY/HTTPS_PROXY/NO_PROXY env vars"
eggfetch-behavior = "eggfetch does not read proxy env vars; proxy= parameter is explicit only"
rationale = "Not yet implemented; tracked as roadmap item"
compatibility-stage-impact = "phase-0"
eggfetch-behavior = "eggfetch reads proxy env vars when trust_env=True (Phase 1)"
rationale = "Implemented in Phase 1; trust_env=True reads env vars by default"
compatibility-stage-impact = "phase-1"
security-improvement = false
migration-impact = "Users must pass proxy= explicitly"
migration-impact = "None; behavior now matches HTTPX"
owner = "eggfetch-team"
review-milestone = "phase-1"
tests = ["test_differential.py::TestKnownDifferences::test_proxy_config_differs"]
Expand Down
1 change: 1 addition & 0 deletions crates/eggfetch-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ tokio = { version = "1", features = ["rt", "net", "time", "sync", "macros", "fs"
tokio-rustls = { version = "0.26", default-features = false, features = ["logging", "tls12"] }
url = "2"
thiserror = "2"
tower-service = "0.3"
base64 = "0.22"
cookie = { version = "0.18", default-features = false, features = ["percent-encode"], optional = true }
async-compression = { version = "0.4", default-features = false, features = ["tokio"], optional = true }
Expand Down
49 changes: 45 additions & 4 deletions crates/eggfetch-core/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ use hyper_util::rt::TokioExecutor;
use crate::error::{Error, Result};
use crate::headers::Headers;
use crate::http_version::HttpVersionPolicy;
use crate::limits::Limits;
use crate::pool::{Pool, PoolConfig, PoolMetrics};
#[cfg(feature = "proxy")]
use crate::proxy::Proxy;
Expand All @@ -17,7 +18,7 @@ use crate::request::{Request, RequestBuilder};
use crate::response::Response;
use crate::retry::RetryPolicy;
use crate::timeout::Timeout;
use crate::transport::{Connector, HyperClient};
use crate::transport::Connector;

#[cfg(feature = "cookies")]
use crate::cookie::CookieJar;
Expand Down Expand Up @@ -86,7 +87,7 @@ impl std::fmt::Debug for Client {
}

pub(crate) struct ClientInner {
pub(crate) hyper_client: Option<HyperClient>,
pub(crate) hyper_client: Option<crate::transport::TimeoutHyperClient>,
pub(crate) config: ClientConfig,
pub(crate) pool: Pool,
#[cfg(feature = "http3")]
Expand Down Expand Up @@ -245,6 +246,7 @@ pub struct ClientBuilder {
user_agent: Option<String>,
pool_config: PoolConfig,
timeout: Option<Timeout>,
limits: Option<Limits>,
redirect: RedirectPolicy,
auth: Option<crate::auth::AuthScheme>,
#[cfg(feature = "cookies")]
Expand All @@ -268,6 +270,7 @@ impl ClientBuilder {
user_agent: None,
pool_config: PoolConfig::default(),
timeout: None,
limits: None,
redirect: RedirectPolicy::default(),
auth: None,
#[cfg(feature = "cookies")]
Expand Down Expand Up @@ -342,6 +345,17 @@ impl ClientBuilder {
self
}

/// Set resource limits for the connection pool.
///
/// Limits control logical request concurrency (pool permits) and
/// physical connection behavior (idle connection caps and expiry).
/// When set, the limits are applied to the pool configuration.
#[must_use]
pub fn limits(mut self, limits: Limits) -> Self {
self.limits = Some(limits);
self
}

/// Set the redirect policy for this client.
#[must_use]
pub fn follow_redirects(mut self, follow: bool) -> Self {
Expand Down Expand Up @@ -486,10 +500,32 @@ impl ClientBuilder {
/// unavailable, the client falls back to the packaged Mozilla root set
/// while retaining certificate and hostname verification.
#[must_use]
#[allow(clippy::too_many_lines)]
pub fn build(self) -> Client {
use crate::http_version::HttpVersionPolicyEnabler;
let enabler = HttpVersionPolicyEnabler::from_policy(self.http_version_policy);

let mut pool_config = self.pool_config;
if let Some(limits) = self.limits {
let limits_config: PoolConfig = limits.into();
if limits_config.max_connections.is_some() {
pool_config.max_connections = limits_config.max_connections;
}
if limits_config.max_connections_per_host.is_some() {
pool_config.max_connections_per_host = limits_config.max_connections_per_host;
}
if limits_config.max_idle_connections.is_some() {
pool_config.max_idle_connections = limits_config.max_idle_connections;
}
if limits_config.max_idle_connections_per_host.is_some() {
pool_config.max_idle_connections_per_host =
limits_config.max_idle_connections_per_host;
}
if limits_config.idle_timeout.is_some() {
pool_config.idle_timeout = limits_config.idle_timeout;
}
}

#[cfg(feature = "cookies")]
let cookie_jar = self.cookie_jar.unwrap_or_default();

Expand Down Expand Up @@ -530,8 +566,13 @@ impl ClientBuilder {
None => build_fallback_connector(enabler),
};

// Wrap the connector with connect-phase timeout if configured.
let connect_timeout = self.timeout.as_ref().and_then(|t| t.connect);
let https =
crate::transport::connect_timeout::ConnectTimeout::new(https, connect_timeout);

let mut builder = hyper_util::client::legacy::Client::builder(TokioExecutor::new());
if let Some(timeout) = self.pool_config.idle_timeout {
if let Some(timeout) = pool_config.idle_timeout {
builder.pool_idle_timeout(timeout);
}
Some(builder.build(https))
Expand Down Expand Up @@ -563,7 +604,7 @@ impl ClientBuilder {
http_version_policy: self.http_version_policy,
};

let pool = Pool::new(self.pool_config);
let pool = Pool::new(pool_config);

Client {
inner: Arc::new(ClientInner {
Expand Down
2 changes: 2 additions & 0 deletions crates/eggfetch-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub mod error;
mod h2_headers;
pub mod headers;
pub mod http_version;
pub mod limits;
#[cfg(feature = "multipart")]
pub mod multipart;
pub(crate) mod pipeline;
Expand All @@ -60,6 +61,7 @@ pub use error::{Error, Result};
pub use headers::Headers;
pub use http::Method;
pub use http_version::HttpVersionPolicy;
pub use limits::Limits;
#[cfg(feature = "multipart")]
pub use multipart::{Boundary, Multipart, MultipartEncoder, Part, PartBody};
pub use pool::{Pool, PoolConfig};
Expand Down
148 changes: 148 additions & 0 deletions crates/eggfetch-core/src/limits.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
//! Resource limits for the connection pool.
//!
//! Distinguishes between logical request concurrency (pool permits)
//! and physical connection behavior (hyper's internal pool).

use std::time::Duration;

use crate::pool::PoolConfig;

/// Resource limits for the connection pool.
///
/// Distinguishes between logical request concurrency (pool permits)
/// and physical connection behavior (hyper's internal pool).
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Limits {
/// Maximum concurrent logical requests (pool permits).
/// Maps to pool `max_connections`.
pub max_connections: Option<usize>,
/// Maximum concurrent logical requests per origin.
/// Maps to pool `max_connections_per_host`.
pub max_connections_per_host: Option<usize>,
/// Maximum number of idle (kept-alive) connections.
/// Maps to hyper's pool idle connection limit.
pub max_idle_connections: Option<usize>,
/// Maximum number of idle connections per host.
/// Maps to hyper's pool per-host idle limit.
pub max_idle_connections_per_host: Option<usize>,
/// Duration after which idle connections are closed.
pub keepalive_expiry: Option<Duration>,
}

impl Limits {
/// Create HTTPX-compatible limits.
///
/// HTTPX 0.28.1 defaults to 100 total connections with a 5-second
/// keepalive expiry. Per-host idle connections default to 20. No
/// per-host concurrency limit is set.
///
/// # Examples
///
/// ```
/// use eggfetch_core::Limits;
///
/// let limits = Limits::compat();
/// assert_eq!(limits.max_connections, Some(100));
/// assert!(limits.max_connections_per_host.is_none());
/// assert_eq!(limits.max_idle_connections, Some(20));
/// assert_eq!(limits.max_idle_connections_per_host, Some(20));
/// assert_eq!(limits.keepalive_expiry, Some(std::time::Duration::from_secs(5)));
/// ```
#[must_use]
pub fn compat() -> Self {
Self {
max_connections: Some(100),
max_connections_per_host: None,
max_idle_connections: Some(20),
max_idle_connections_per_host: Some(20),
keepalive_expiry: Some(Duration::from_secs(5)),
}
}

/// Create unlimited defaults (all `None`).
///
/// No concurrency limits or idle connection caps are applied. Idle
/// connections are never proactively closed.
///
/// # Examples
///
/// ```
/// use eggfetch_core::Limits;
///
/// let limits = Limits::native();
/// assert!(limits.max_connections.is_none());
/// assert!(limits.max_connections_per_host.is_none());
/// assert!(limits.max_idle_connections.is_none());
/// assert!(limits.max_idle_connections_per_host.is_none());
/// assert!(limits.keepalive_expiry.is_none());
/// ```
#[must_use]
pub fn native() -> Self {
Self::default()
}
}

impl From<Limits> for PoolConfig {
fn from(limits: Limits) -> Self {
Self {
max_connections: limits.max_connections,
max_connections_per_host: limits.max_connections_per_host,
max_idle_connections: limits.max_idle_connections,
max_idle_connections_per_host: limits.max_idle_connections_per_host,
idle_timeout: limits.keepalive_expiry,
}
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn default_limits_are_all_none() {
let limits = Limits::default();
assert!(limits.max_connections.is_none());
assert!(limits.max_connections_per_host.is_none());
assert!(limits.max_idle_connections.is_none());
assert!(limits.max_idle_connections_per_host.is_none());
assert!(limits.keepalive_expiry.is_none());
}

#[test]
fn compat_limits_match_httpx() {
let limits = Limits::compat();
assert_eq!(limits.max_connections, Some(100));
assert!(limits.max_connections_per_host.is_none());
assert_eq!(limits.max_idle_connections, Some(20));
assert_eq!(limits.max_idle_connections_per_host, Some(20));
assert_eq!(limits.keepalive_expiry, Some(Duration::from_secs(5)));
}

#[test]
fn native_limits_are_unlimited() {
let limits = Limits::native();
assert_eq!(limits, Limits::default());
}

#[test]
fn limits_into_pool_config() {
let limits = Limits::compat();
let config: PoolConfig = limits.into();
assert_eq!(config.max_connections, Some(100));
assert!(config.max_connections_per_host.is_none());
assert_eq!(config.max_idle_connections, Some(20));
assert_eq!(config.max_idle_connections_per_host, Some(20));
assert_eq!(config.idle_timeout, Some(Duration::from_secs(5)));
}

#[test]
fn native_limits_into_pool_config() {
let limits = Limits::native();
let config: PoolConfig = limits.into();
assert_eq!(config.max_connections, None);
assert_eq!(config.max_connections_per_host, None);
assert_eq!(config.max_idle_connections, None);
assert_eq!(config.max_idle_connections_per_host, None);
assert_eq!(config.idle_timeout, None);
}
}
Loading
Loading