Rust

Client

An HTTP/1.1 client with immutable configuration, destination checks on every connection, redirects, retries with backoff, streaming and pooling.
Rust 3,891 lines (2,483 code)split
PartCodeCommentsBlankTotalFiles
Rust source2,4831,1003083,89112
Rust tests1260121382

Comments include doc comments. Rust tests are tests/ and #[cfg(test)] modules.

Install#

The crate lives in the Appwrite repository; depend on it from Git.

Cargo.toml
[dependencies]
utopia-client = { git = "https://github.com/appwrite/appwrite" }

Getting started#

Common tasks with Client, each a complete program you can copy and run.

Getting started

utopia-client sends HTTP/1.1 requests over TCP or TLS on tokio. A Client wraps a transport (Http) with request defaults; every with_* returns a configured copy, so a client can be shared and specialised freely. Responses with a 4xx or 5xx status are returned, not raised: only a failure to get a response is an Error.

Send a request

Build a Request, send it, and read the response's status, headers and body.

Rust
use utopia_client::{Client, Http, Request};

let client = Client::new(Http::new());
let request = Request::new("POST", "https://api.example.com/users")?
    .header("Content-Type", "application/json")?
    .body(r#"{"name":"Ada"}"#);

let response = client.send(request).await?;
println!("{} {}", response.status(), response.headers().line("content-type"));
println!("{}", response.text());
Compiles in CI; needs a running service to execute.

Configure defaults

A base URI resolves relative requests, default headers fill in what a request does not set, and timeouts are in seconds (0 is no limit).

Rust
use utopia_client::{Client, Http, Request};

let client = Client::new(Http::new())
    .with_base_uri("https://api.example.com/v1")?
    .with_headers([("Accept", vec!["application/json"])])
    .with_bearer_auth("token")
    .with_timeout(10.0)?
    .with_connect_timeout(2.0)?;

// GET https://api.example.com/v1/users?page=2
let users = client.send(Request::new("GET", "users?page=2")?).await?;
Compiles in CI; needs a running service to execute.

Fetch a URL a user chose

PublicInternet refuses private, loopback, link-local and reserved addresses. The transport checks the address each connection actually reached, on every redirect hop, so DNS cannot answer differently between a check and the connection.

Rust
use utopia_client::{Client, Error, Http, PublicInternet, Request};

let client = Client::new(Http::new())
    .with_destinations(PublicInternet::default())
    .with_follow_redirects(true, 5)?;

match client.send(Request::new("GET", "http://169.254.169.254/latest/meta-data")?).await {
    Err(Error::Destination(message)) => println!("refused: {message}"),
    other => println!("{other:?}"),
}
Compiles in CI; needs a running service to execute.

Stream a large response

stream passes each body chunk to a sink as it arrives, so memory stays bounded; the returned response carries the status and headers.

Rust
use utopia_client::{Client, Http, Request};

let client = Client::new(Http::new());
let mut size = 0usize;
let mut count = |chunk: &[u8]| size += chunk.len();
let response = client.stream(Request::new("GET", "https://example.com/large.bin")?, &mut count).await?;
println!("{} bytes, status {}", size, response.status());
Compiles in CI; needs a running service to execute.

Retry transient failures

Retry decorates a transport. The default Backoff retries idempotent methods on network failures and 429, 502, 503 and 504 responses, with exponential backoff and full jitter, honouring a numeric Retry-After.

Rust
use utopia_client::{Backoff, Error, Outcome, Request, Strategy};

let backoff = Backoff::new(3, 0.1, 10.0, 2.0).with_randomizer(|| 1.0);
let request = Request::new("GET", "https://example.com/")?;
let reset = Error::Connection("Connection reset".into());

assert_eq!(backoff.delay(&request, 1, Outcome::Error(&reset)), Some(0.1));
assert_eq!(backoff.delay(&request, 2, Outcome::Error(&reset)), Some(0.2));
assert_eq!(backoff.delay(&request, 3, Outcome::Error(&reset)), None);

Reference#

An HTTP/1.1 client: immutable configuration, destination checks on every connection, redirects, retries with backoff, streaming and pooling.

A Client sends Requests through an [Adapter]: the Http transport, or a decorator around it such as Retry. Responses come back whole (Client::send) or streamed chunk by chunk to a Sink (Client::stream); a 4xx or 5xx response is a response, not an error. Redirects are followed only when asked (Client::with_follow_redirects), and Destinations decide which addresses a request may reach, checked on the address each connection actually reached.

Rust
use utopia_client::{Client, Http, PublicInternet, Request};

let client = Client::new(Http::new())
    .with_destinations(PublicInternet::default())
    .with_follow_redirects(true, 5)?;
let response = client.send(Request::new("GET", "https://example.com/feed.xml")?).await?;
println!("{} {} bytes", response.status(), response.bytes().len());
Compiles in CI; needs a running service to execute.

Modules#

Each module groups one concept of the library. Internal ones hold items the crate re-exports at its root.

API#

What utopia_client exports at its root.

Structs

AnywhereAny address, through any proxy: for services whose address the operator configured, never for a URL a user supplied. The default.BackoffThe default, best-practice strategy: retry only idempotent methods (`GET`, `HEAD`, `PUT`, `DELETE`, `OPTIONS`, `TRACE`), only on network failures (`Error::is_network`) and overloaded responses (429, 502, 503, 504), with exponential backoff and full jitter. A numeric `Retry-After` is honoured, capped to the maximum delay.CertificateA client certificate for mutual TLS.ClientAn HTTP client: an `Adapter` (the transport, possibly decorated) plus defaults applied to every request: a base URI for relative requests, default headers (never overriding a header the request sets), and W3C trace propagation.ErrorA part whose file cannot be read.HeadersHTTP header fields in order, each name with its values.HttpThe HTTP/1.1 transport: TCP and TLS (rustls) on tokio.IpRangeAn IPv4 or IPv6 address or CIDR range. A single address is its /32 or /128, so every spelling of an address (`::1`, `0:0:0:0:0:0:0:1`) is the same range.OptionsUndocumented.PoolA client that borrows a pooled adapter for the duration of each request and returns it once the request completes, so concurrent callers share a bounded set of connections. An adapter whose request failed is discarded (its connection may be broken) and replaced on demand.PublicInternetGlobally routable addresses only: never a private, loopback, link-local, multicast or otherwise reserved one (cloud metadata, the host, the internal network), unless one of the given ranges admits it. Never through a proxy. For fetching a URL a user supplied.RequestAn HTTP request: method, URI, headers and body.ResponseAn HTTP response: protocol version, status, reason phrase, headers and body.RetryAn adapter that retries another according to a `Strategy`. The strategy owns every decision (which outcomes to retry, how long to wait, when to stop); the decorator only loops and sleeps. A stream is retried only while no byte has reached its sink: replaying would duplicate them.TimerSleeps on tokio's timer.UriA URI: scheme, user info, host, port, path, query and fragment.