Adapters
The cargo features of the runtime turn on its adapters and codecs. The table lists what turns each one on. generate writes them all but simd, which is yours to list or leave out. cargo honig check reports them when they are out of date.
| Feature | Crate | Adds | On when |
|---|---|---|---|
client | tower-service | The generated client: the Transport bound over tower services and TowerTransport | You generate the client |
server | tower-service | The generated server: a tower Service, routing, conditional requests and the wide event | You generate the server |
reqwest | reqwest | ReqwestTransport: async client with streaming bodies | client = { adapters = ["reqwest"] } |
reqwest-middleware | reqwest-middleware | ReqwestMiddlewareTransport: retries, tracing and caching from your middleware stack | client = { adapters = ["reqwest-middleware"] } |
ureq | ureq | UreqTransport: blocking client | client = { adapters = ["ureq"] } |
gloo-net | gloo-net | GlooTransport: browser fetch on wasm32 only | client = { adapters = ["gloo-net"] } |
axum | axum | Server::into_axum and the address of the client from the ConnectInfo of axum | server = { adapters = ["axum"] } |
tracing | tracing | A span per request and a log line for each wide event | server = { adapters = ["tracing"] } |
tracing-opentelemetry | opentelemetry | W3C Trace Context: traceparent and tracestate | adapters = ["tracing-opentelemetry"] in client or server |
ipnet | ipnet | format: ipv4-cidr and ipv6-cidr checks | The description calls for it |
idn | idna | email, idn-email, hostname and idn-hostname checks | The description calls for it |
regress | regress | pattern and patternProperties checks (ECMA-262) | The description calls for it |
oauth | The OAuth 2.0 flows of the client: token grants, device authorization and discovery | The description calls for it | |
pkce | sha2 | Pkce, authorization_url and exchange_code: the OAuth 2.0 authorization code flow. Outside wasm32 Pkce::new makes a verifier from OS randomness | The description calls for it |
cookie | cookie | Cookie parameters and API keys | The description calls for it |
multipart | multer | multipart/* bodies and parts | The description calls for it |
base64 | base64 | Binary data in JSON (format: byte, contentEncoding, base64url) and http basic credentials | The description calls for it |
xml | quick-xml | XML bodies and parts | The description calls for it |
simd | sonic-rs | SIMD for large bodies: JSON with sonic-rs (x86_64 and aarch64), the UTF-8 check of text with simdutf8 and base64 with base64-simd. Multipart boundaries use memchr with or without it | You or cargo honig init add it |
An adapter is compiled whenever its half lists it, also when its library is an optional dependency that is off. Depend on the major version that the table names. Otherwise cargo builds two copies whose types do not match.
axum
into_axum() returns a Router with a route per path template. It merges next to your own routes or nests under a prefix:
async fn serve(addr: &str) -> std::io::Result<()> {
let listener = tokio::net::TcpListener::bind(addr).await?;
println!("serving the catalog on http://{addr}/v1");
let app = api::Server::new(Catalog::default())
// One JSON line per request: the operation, the status, the duration, the body sizes and more.
.on_event(|event: &api::RequestEvent| println!("{}", event.to_json()))
.into_axum();
axum::serve(listener, app).await
}
A path that the description does not declare falls through to the fallback of the router: a bare 404 with no body and no wide event. To answer it in the error schema with a wide event, give the router a fallback that is the server:
/// An axum router whose undeclared paths reach the server too. They then get its 404 in the error schema and a wide
/// event. Leave the fallback out to give those paths to routes of your own.
fn with_fallback(lines: Arc<Mutex<Vec<String>>>) -> axum::Router {
let server = || {
let lines = Arc::clone(&lines);
api::Server::new(Catalog::default()).on_event(move |event: &api::RequestEvent| {
if let Ok(mut lines) = lines.lock() {
lines.push(event.to_json());
}
})
};
server().into_axum().fallback_service(server().into_service())
}
axum refuses to merge two routers that both have a fallback. Set it once, on the router that you serve.
Recipes serves a web app next to the API and a WebSocket next to the generated routes.
hyper and other servers
into_service() is a tower Service over http requests:
async fn serve_with_hyper(listener: tokio::net::TcpListener) -> std::io::Result<()> {
let service = api::Server::new(Catalog::default()).into_service();
loop {
let (stream, _) = listener.accept().await?;
let service = hyper_util::service::TowerToHyperService::new(service.clone());
let io = hyper_util::rt::TokioIo::new(stream);
tokio::spawn(hyper::server::conn::http1::Builder::new().serve_connection(io, service));
}
}
Blocking client
UreqTransport sends with ureq. block_on runs the call with no async runtime:
/// The blocking client. `block_on` returns once the response is read with no async runtime.
fn list_products(base_url: &str) -> Result<ops::list_products::Response, api::Error> {
let client = api::Client::new(api::UreqTransport::new(base_url)).with_api_key("secret");
api::block_on(client.list_products(ops::list_products::Params::new()))
}
Testing without a socket
A server’s into_service() is a transport too. The client then sends each request straight to the server in memory:
/// A client wired straight to the server with no socket. A test of your server needs this.
fn in_memory_client() -> api::Client<impl api::Transport> {
let service = api::Server::new(Catalog::default()).into_service();
api::Client::new(service).with_api_key("secret")
}
Your own transport
A transport is any tower Service of http requests. Write one to send with any HTTP client. Wrap one with tower’s layers:
/// A transport is any tower `Service`, so tower's layers wrap one: this one adds a request ID to every request.
fn with_request_id(transport: impl api::Transport) -> impl api::Transport {
tower::ServiceBuilder::new()
.map_request(|mut req: api::Request| {
req.headers_mut().insert("x-request-id", api::http::HeaderValue::from_static("req-1"));
req
})
.service(transport)
}
TLS
TLS comes from your own dependency. honig depends on reqwest and ureq without default features. Cargo adds the features that your crate turns on. The default is rustls. If your crate turns them off then add rustls or native-tls. Otherwise every https request fails.