Skip to main content

Crate tez

Crate tez 

Source
Expand description

§tez

tez is a lightweight, ergonomic, and fast high-level HTTP client for Rust.

The name comes from the Hindi word तेज़ (tez): fast.

Tez owns its public API and uses Hyper only as its HTTP/1.1 and HTTP/2 protocol engine. It does not require Reqwest or a particular asynchronous runtime. Applications can select a first-party runtime integration or provide the four capabilities Tez needs: execution, time, DNS, and TCP. The blocking facade uses the same transport, policies, and connection pool.

§Quick start

[dependencies]
tez = "0.0.3"
serde = { version = "1", features = ["derive"] }
#[derive(serde::Serialize)]
struct NewUser {
    name: String,
}

async fn create_user() -> tez::Result<()> {
    let client = tez::Client::builder()
        .base_url("https://api.example.com/v1")
        .timeout(std::time::Duration::from_secs(20))
        .build()?;

    let response = client
        .post("/users")
        .json(&NewUser {
            name: "Ada".into(),
        })
        .send()
        .await?;

    if response.status().is_success() {
        println!("{}", response.text().await?);
    }
    Ok(())
}

The equivalent blocking path differs only where waiting occurs:

fn fetch_user() -> tez::Result<String> {
    tez::blocking::Client::new()?
        .get("https://api.example.com/users/1")
        .send()?
        .text()
}

§Runtime model

Runtime is a coherent capability bundle. It supplies the executor, timer, resolver, and TCP connector used by one client. Tez’s portable default uses async-io, async-net, and a small process-wide connection-driver executor, so it works when polled by any standard Futures executor.

For the shortest runtime-native path, select the application’s runtime:

#[cfg(feature = "runtime-tokio")]
fn tokio_client() -> tez::Result<tez::Client> {
    tez::Client::builder()
        .runtime(tez::runtime::Tokio::current()?.runtime())
        .build()
}

#[cfg(feature = "runtime-smol")]
fn smol_client() -> tez::Result<tez::Client> {
    tez::Client::builder()
        .runtime(tez::runtime::Smol::runtime())
        .build()
}

Custom integrations compose Runtime::builder, Executor::new, Timer::new, a dns::Resolver, and a runtime::Connector. Runtime features are additive and do not change request, response, body, error, or Yokai-facing API types. A library can therefore accept a configured tez::Client or Runtime from its application without becoming tied to Tokio or Smol.

Runtime::with_executor retains a runtime’s native timer, resolver, and connector while replacing only the executor used for connection tasks.

The reusable Client keeps Send request futures so it can cross worker threads in applications and libraries such as Yokai. Any executor can poll those futures, including a Glommio executor. Runtime-native adapters also require Send task, timer, and stream handles; a reactor whose native I/O is deliberately thread-local can use Tez’s portable connector instead of smuggling local resources across threads.

The optional tez command is an application built on this interface. It uses the complete Smol integration; Smol is not enabled for library-only builds.

§Architecture

Tez follows one downward dependency direction:

client, request, response, body, stream
                  |
dispatch: authentication, compression, redirects, retries, cookies
                  |
connection::Client, handshake, pool
                  |
transport, proxy, DNS, TLS
                  |
runtime, resolver, connector, timer, I/O

Modules own layers; focused Rust types and traits are the building blocks inside them. The private Dispatch state owns one logical request across its wire attempts; it is deliberately not a public transport trait. Transport composes DNS, TCP, proxy routing, and TLS. connection::Client is the lower-level exchange client between the ergonomic client and Hyper. It accepts a complete http::Request<tez::Body>, owns HTTP/1.1 and HTTP/2 connection reuse, and returns http::Response<tez::Body> with connection metadata in its extensions. The high-level Client adds authentication, defaults, compression, redirects, retries, cookies, and bounded response consumers.

async fn exchange() -> tez::Result<()> {
    let client = tez::connection::Client::new()?;
    let request = tez::HttpRequest::get("https://example.com/health")
        .body(tez::Body::empty())?;
    let response = client.send(request).await?;

    if let Some(info) = response.extensions().get::<tez::connection::Info>() {
        println!("connected to {}", info.remote_addr());
    }
    Ok(())
}

Connection, Origin, and Protocol describe established HTTP connections. Pool owns reuse and retirement. Runtime capabilities stay below protocol behavior, and runtime-specific types never enter request or response APIs.

Content encoding stays at the request and response boundary. Tez uses Serde’s existing Serialize and DeserializeOwned traits rather than introducing a parallel serializer abstraction. content owns complete text, HTML, JSON, and form bodies; multipart owns MIME composition; stream::json and stream::sse own incremental framing; body owns only bytes and backpressure.

§Client and body model

  • Client is immutable, cheap to clone, and owns shared policy and a bounded connection pool.
  • RequestBuilder builds one request. Its build method performs no I/O.
  • Request is http::Request<tez::Body>.
  • Response keeps status, version, headers, final URL, connected peer, and a one-shot streaming body.
  • Body implements http_body::Body; buffered bodies are replayable and streaming bodies preserve frames and trailers.

Collecting helpers accept at most 16 MiB by default. Configure Limits::response_body, override one response with Response::bytes_with_limit, or use Response::body_mut, Response::into_body, or Response::stream for larger or incremental responses.

§Connections and HTTP versions

HTTPS offers HTTP/2 and HTTP/1.1 through ALPN. Plain HTTP uses HTTP/1.1 unless cleartext HTTP/2 prior knowledge is enabled for a server known to accept the HTTP/2 connection preface. HTTP/1.1 connections return to the pool only after the response body ends; abandoning a partial body retires that connection. HTTP/2 responses can be abandoned independently without poisoning other streams. A successful HTTP Upgrade or CONNECT response can transfer its runtime-neutral byte stream to another protocol:

async fn upgraded(client: &tez::Client) -> tez::Result<tez::Upgraded> {
    let response = client
        .get("http://example.com/custom")
        .header(tez::header::CONNECTION, "upgrade")
        .header(tez::header::UPGRADE, "custom")
        .send()
        .await?;
    response.upgrade().await
}

The pool defaults to 16 active or opening connections and 8 idle HTTP/1.1 connections per origin. Resource policy is grouped in Limits:

fn bounded_client() -> tez::Result<tez::Client> {
    tez::Client::builder()
        .limits(
            tez::Limits::default()
                .connections_per_origin(32)
                .idle_connections_per_origin(8)
                .response_body(32 * 1024 * 1024),
        )
        .build()
}

Waiting for pool capacity is part of the request’s total deadline. Socket and HTTP/2 policy is grouped independently:

fn tuned_client() -> tez::Result<tez::Client> {
    let http2 = tez::connection::Http2::default()
        .adaptive_window(true)
        .keepalive_interval(std::time::Duration::from_secs(30))
        .keepalive_timeout(std::time::Duration::from_secs(10));
    let connection = tez::connection::Settings::default()
        .keepalive(std::time::Duration::from_secs(60))
        .http2(http2);
    tez::Client::builder().connection(connection).build()
}

§Deadlines, redirects, and retries

The default 30-second total deadline covers pool waiting, DNS, TCP, TLS, upload, response headers, redirects, retry delays, and response-body reads. Connection setup is capped at 10 seconds and idle HTTP/1 connections remain pooled for 90 seconds. A read inactivity timeout is opt-in. Group these values with Timeouts, use timeout(None) to remove only the default total deadline, or override a single request:

fn time_bounded_client() -> tez::Result<tez::Client> {
    tez::Client::builder()
        .timeouts(
            tez::Timeouts::default()
                .total(std::time::Duration::from_secs(20))
                .connect(std::time::Duration::from_secs(5))
                .read(std::time::Duration::from_secs(10)),
        )
        .build()
}

Redirects are returned unchanged by default. redirect::Policy::SameOrigin follows at most ten same-origin redirects, implements the standard POST-to-GET rewrites, and replays only bodies Tez knows are replayable. Cross-origin redirects are never followed by that policy. redirect::Policy::Follow allows bounded cross-origin redirects while removing authorization, cookie, proxy authorization, caller-provided host, and any explicitly sensitive headers before crossing an origin boundary.

Retries are disabled by default. Opt-in retry policy is limited to eligible idempotent requests with replayable bodies and capped Retry-After or jittered backoff. An ambiguous failure after a request may have reached the peer is not silently replayed.

§TLS and proxies

HTTPS uses rustls with platform certificate verification. A client can replace platform roots with an isolated PEM bundle, add roots while retaining platform trust, bound TLS protocol versions, add an unencrypted PEM client identity, or reject every non-HTTPS target:

fn private_client(ca: &[u8], identity: &[u8]) -> tez::Result<tez::Client> {
    tez::Client::builder()
        .trust_pem(ca)
        .identity_pem(identity)
        .https_only()
        .build()
}

Configured trust roots also authenticate an HTTPS proxy. A client identity is used only for the destination TLS connection and is never offered to the proxy.

Clients connect directly unless configured with proxy::Policy::all. HTTP requests use absolute form through the proxy; HTTPS uses a bounded CONNECT handshake and preserves bytes read beyond its headers. HTTP and HTTPS proxy origins, SOCKS5h with proxy-side DNS, proxy credentials, and domain, port, IPv4, IPv6, and CIDR NO_PROXY matching are supported. Explicit policies can carry an independent bypass list with proxy::Policy::exclude.

With the system-proxy feature, proxy::Policy::system snapshots HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY, and their lowercase forms when the client is built. It does not currently read operating-system GUI proxy settings.

§DNS

The default dns::SystemResolver uses the platform resolver through runtime-agnostic async networking. Applications can implement dns::Resolver to supply cached, service discovery, or test addresses. Tez continues to own address-family interleaving, staggered connection attempts, deadlines, and socket setup.

§Compression and cookies

Automatic response decoding is streaming and removes stale Content-Encoding and Content-Length metadata. Gzip is enabled by default; Brotli, deflate, and Zstandard are feature-gated. An explicit Accept-Encoding header is respected. Tez does not add one to range requests, because transparent content coding can change byte-range semantics. disable_compression preserves the encoded bytes and headers.

The optional cookies feature adds an in-memory CookieJar. It applies normal domain, path, secure, and expiry rules and is shared by client clones. An explicit request Cookie header wins for that request. A jar may be shared explicitly between otherwise independent clients.

§Authentication and request bodies

Built-in API-key, Basic, and Bearer authentication values validate their input, mark generated headers sensitive, and redact credential data from errors and debug output. Custom authentication can refresh credentials asynchronously after the URL and ordinary headers have been resolved.

Request builders support bytes, text, HTML, JSON, streamed JSON arrays, URL-encoded forms, raw byte streams, NDJSON, server-sent events, asynchronous readers, and multipart bodies. Part::file streams files with an exact form length; other multipart fields may be buffered or streamed. The blocking builder similarly accepts std::io::Read. Tez rejects ambiguous manual Content-Length and Transfer-Encoding combinations before opening a connection.

Response bodies can be consumed one chunk at a time, exposed as a standard http_body::Body, copied directly to a blocking writer, collected under an explicit bound, or decoded as JSON, URL-encoded forms, or text. Text decoding honors a declared character set and rejects malformed data rather than silently replacing it. ResponseInfo reports attempts, followed redirects, and time to final response headers.

§Structured streams

Response::stream() retains raw bytes and HTTP trailers. Choose the framing explicitly when the body contains structured streaming data:

  • .json::<T>() decodes one complete JSON document;
  • .ndjson::<T>() decodes each completed NDJSON or JSON Lines record;
  • .sse() decodes server-sent events and preserves their metadata.

Use .json::<T>() on an SSE stream when every event data field is JSON, or .json_until_done::<T>() for APIs with a conventional [DONE] sentinel. The client’s Limits::stream_item bound applies while one record or event is being assembled; raw streaming remains backpressured and uncollected. Structured streams observe the response deadline.

§Cargo features

FeatureEffect
gzip (default)Streaming gzip response decoding
brotliStreaming Brotli response decoding
deflateStreaming zlib/deflate response decoding
zstdStreaming Zstandard response decoding
cookiesShareable in-memory cookie jar
system-proxyConventional proxy environment variables
runtime-smolComplete Smol runtime integration
runtime-tokioComplete Tokio runtime integration
cliSmol-powered tez command and all codecs

HTTP/1.1, HTTP/2, rustls, the async client, and the blocking facade are always available. HTTP/3 is intentionally not implemented yet.

§Command line and benchmarks

The optional command-line client has HTTPie-style request syntax:

cargo run -p tez --features cli -- example.com

See CLI.md for its complete contract.

Tez’s regression suite is separate from its ecosystem comparison:

cargo bench -p tez --features runtime-tokio --bench tez
just tez-benchmark

The comparison measures reused round trips and fresh connection setup against Reqwest and Ureq through each library’s normal high-level path. Async Tez and Reqwest use the same Tokio scheduler, timer, resolver, and TCP reactor.

§Scope

This release targets high-level HTTP/1.1 and HTTP/2 clients. The transport boundaries are deliberately reusable by future WebSocket and HTTP/3 work, but those protocols are not exposed through Tez today.

Re-exports§

pub use runtime::Executor;
pub use runtime::Runtime;
pub use runtime::Timer;

Modules§

auth
Authentication for Tez clients and requests.
blocking
Blocking HTTP client APIs backed by Tez’s asynchronous connection core.
connection
Low-level HTTP/1.1 and HTTP/2 connections, pooling, and protocol policy.
dns
Host resolution and address connection policy.
header
Standard HTTP types used throughout Tez’s public API. HTTP header types
proxy
Routing policies for HTTP(S) proxies.
redirect
Redirect behavior configured for a client.
retry
Retry behavior configured for a client.
runtime
Runtime capabilities used by Tez without choosing an application runtime.
tls
TLS protocol policy for Tez clients.

Structs§

Body
An owned body for Tez requests and responses. An owned body for Tez requests and responses.
Bytes
An efficient immutable byte buffer for buffered HTTP data. A cheaply cloneable and sliceable chunk of contiguous memory.
Client
The reusable HTTP client and its configuration builder. The reusable HTTP client and its configuration builder. The reusable HTTP client and its configuration builder. A reusable asynchronous HTTP client.
ClientBuilder
The reusable HTTP client and its configuration builder. The reusable HTTP client and its configuration builder. The reusable HTTP client and its configuration builder. A builder for configuring a Client.
CookieJar
A thread-safe in-memory HTTP cookie store.
Error
Tez’s owned error type and specialized result alias. Tez’s owned error type and specialized result alias. Tez’s owned error type and specialized result alias. An error from building, sending, or consuming an HTTP message.
Event
One logical event decoded from a streaming response. One server-sent event received from or sent in an HTTP body.
EventStream
One-shot response byte, JSON, and server-sent event streams. One-shot response byte, JSON, and server-sent event streams. One-shot response byte, JSON, and server-sent event streams. A one-shot stream of server-sent events.
Frame
The standard streaming body trait and frame types implemented by Body. A frame of any kind related to an HTTP stream (body).
HeaderMap
Standard HTTP types used throughout Tez’s public API. A specialized multimap for header names and values.
HeaderName
Standard HTTP types used throughout Tez’s public API. Represents an HTTP header field name
HeaderValue
Standard HTTP types used throughout Tez’s public API. Represents an HTTP header field value.
HttpRequest
The standard HTTP request type for explicit request construction before it carries a Body. Represents an HTTP request.
JsonStream
One-shot response byte, JSON, and server-sent event streams. One-shot response byte, JSON, and server-sent event streams. One-shot response byte, JSON, and server-sent event streams. A one-shot stream of JSON values.
Limits
Validated resource and time bounds for a client. Validated resource and time bounds for a client. Validated resource and time bounds for a client. Resource bounds enforced by a client.
Method
Standard HTTP types used throughout Tez’s public API. The Request Method (VERB)
Multipart
Owned multipart request bodies and their parts. Owned multipart request bodies and their parts. Owned multipart request bodies and their parts. An owned multipart/form-data request body.
Part
Owned multipart request bodies and their parts. Owned multipart request bodies and their parts. Owned multipart request bodies and their parts. One field in a Multipart request body.
RequestBuilder
Fluent construction of one request sent through a Client. A fluent builder for one request.
Response
A final response with streaming body access and bounded consumers. A final response with streaming body access and bounded consumers. A final response with streaming body access and bounded consumers. A final HTTP response with a one-shot streaming Tez body.
ResponseInfo
A final response with streaming body access and bounded consumers. A final response with streaming body access and bounded consumers. A final response with streaming body access and bounded consumers. Stable metadata about the work that produced a response.
ResponseStream
One-shot response byte, JSON, and server-sent event streams. One-shot response byte, JSON, and server-sent event streams. One-shot response byte, JSON, and server-sent event streams. A one-shot response body consumed as backpressured byte chunks.
SizeHint
The standard streaming body trait and frame types implemented by Body. A Body size hint
StatusCode
Standard HTTP types used throughout Tez’s public API. An HTTP status code (status-code in RFC 9110 et al.).
Timeouts
Validated resource and time bounds for a client. Validated resource and time bounds for a client. Validated resource and time bounds for a client. Time bounds applied to one logical request and its connections.
Upgrade
Runtime-neutral HTTP protocol upgrade types. Runtime-neutral HTTP protocol upgrade types. Runtime-neutral HTTP protocol upgrade types. Completion of an HTTP protocol switch.
Upgraded
Runtime-neutral HTTP protocol upgrade types. Runtime-neutral HTTP protocol upgrade types. Runtime-neutral HTTP protocol upgrade types. A connection after an HTTP Upgrade or successful CONNECT.
Uri
Standard HTTP types used throughout Tez’s public API. The URI component of a request.
Version
Standard HTTP types used throughout Tez’s public API. Represents a version of the HTTP spec.

Traits§

BodyExt
Extensions for reading frames from a standard streaming body. An extension trait for http_body::Body adding various combinators and adapters
HttpBody
The standard streaming body trait and frame types implemented by Body. Trait representing a streaming body of a Request or Response.

Type Aliases§

Request
A detached standard HTTP request carrying a Tez Body.
Result
Tez’s owned error type and specialized result alias. Tez’s owned error type and specialized result alias. Tez’s owned error type and specialized result alias. A specialized std::result::Result for Tez operations.