Server
A server is your type that implements the generated server::Api. It has one method per operation:
/// The catalog in memory. The ID of a product is its index.
#[derive(Default)]
pub struct Catalog(Mutex<Vec<types::Product>>);
impl Catalog {
fn products(&self) -> Result<MutexGuard<'_, Vec<types::Product>>, api::ApiError> {
self.0
.lock()
.map_err(|_| api::ApiError::new(api::http::StatusCode::INTERNAL_SERVER_ERROR, "catalog lock poisoned"))
}
}
impl api::Api for Catalog {
type Principal = ();
async fn list_products(
&self,
params: ops::list_products::Params,
_: &api::Context<'_>,
) -> Result<ops::list_products::Response, api::ApiError> {
let limit = params.limit.and_then(|n| usize::try_from(n).ok()).unwrap_or(usize::MAX);
let body = self.products()?.iter().take(limit).cloned().collect();
Ok(ops::list_products::Response::Ok { body, x_next: None })
}
async fn create_product(
&self,
params: ops::create_product::Params,
_: &api::Context<'_>,
) -> Result<ops::create_product::Response, api::ApiError> {
self.products()?.push(params.body.clone());
Ok(ops::create_product::Response::Created(params.body))
}
async fn get_product(
&self,
params: ops::get_product::Params,
_: &api::Context<'_>,
) -> Result<ops::get_product::Response, api::ApiError> {
let found = usize::try_from(params.product_id).ok().and_then(|i| self.products().ok()?.get(i).cloned());
Ok(match found {
Some(product) => ops::get_product::Response::Ok(product),
None => ops::get_product::Response::NotFound(types::Error::new(404, "no such product".to_owned())),
})
}
}
api::Server::new(Catalog::default()) builds the server. into_axum() serves it as an axum Router. into_service() serves it as a tower Service for hyper and other servers. See Adapters.
The server keeps your Api in an Arc and shares it across requests without cloning it. To share the same state with code outside the server, such as a websocket route or a background job, pass an Arc you keep a clone of: api::Server::new(Arc::clone(&catalog)).
A request goes through these steps. When a step refuses the request it answers in the error schema of the description:
- Routing: an undeclared path is 404. An undeclared method is 405. A
HEADtakes theGETof its path and gets its headers without the body. - Credentials: the
securityof the operation. If none of its requirements are present then the answer is 401. - Your layers as an
http::Request<Body>in the order that you add them. The first one is the outermost. Its extensions hold the generatedOperation, theRequestEventand the credentials (Secured). The body is not read yet. So a refused request costs no body read.read_bodyreads it for a layer that needs it. - The body: read whole up to
max_body_bytes(413). An operation that streams its body skips this step. - Decoding and validation (400 and 415). Then your handler runs and its response is encoded.
Server::authenticate finds who is calling and puts the principal in the extensions. When your Api names a
Principal the server builds into a service only once it does.
Validation
Requests are checked against every constraint of their schemas. A failing request gets 400 with every violation and its JSON pointer:
{"violations": [{"path": "/body/name", "message": "at least 2 characters required, found 1"}]}
A body whose Content-Type the operation does not declare gets 415.
Content negotiation
An operation may answer in several media types. It answers in the one that the Accept of the request prefers (RFC 9110 section 12.5.1). If Accept takes none of them then it answers 406. When every media type holds the same type the handler returns that type. The server then picks the encoding. When they hold different types Params carries the choice as a typed media.
Streams
Binary responses take api::Blob. Return bytes. Or pass any Stream of chunks to Blob::stream for a large download:
fn get_export(
&self,
p: ops::get_export::Params,
_: &api::Context<'_>,
) -> impl Future<Output = Result<ops::get_export::Response, api::ApiError>> + Send {
let r = match p.id.as_str() {
"big" => {
ops::get_export::Response::Ok(api::Blob::stream(futures_util::stream::iter(CHUNKS.map(<[u8]>::to_vec))))
}
"small" => ops::get_export::Response::Ok(b"zip".to_vec().into()),
// A file read from where the range starts. The bytes before it are never read.
"archive" => ops::get_export::Response::Ok(api::Blob::ranged(ARCHIVE.len() as u64, |first, last| {
let (first, last) = (usize::try_from(first).unwrap_or(0), usize::try_from(last).unwrap_or(0));
futures_util::stream::iter(ARCHIVE.get(first..=last).map(<[u8]>::to_vec))
})),
_ => ops::get_export::Response::NotFound,
};
std::future::ready(Ok(r))
}
A response declared as a range, such as image/* or */*, has no one type to send. Give the blob its type with Blob::with_media. It goes out as that type when it fits the range, else as application/octet-stream. The client reads it back with Blob::media:
fn get_thumbnail(
&self,
p: ops::get_thumbnail::Params,
_: &api::Context<'_>,
) -> impl Future<Output = Result<ops::get_thumbnail::Response, api::ApiError>> + Send {
// `image/*` declares a range: the blob says which image it is.
let preview = api::Blob::from(PNG.to_vec());
let preview = match p.id.as_str() {
"png" => preview.with_media("image/png"),
"zip" => preview.with_media("application/zip"),
_ => preview,
};
std::future::ready(Ok(ops::get_thumbnail::Response::Ok(preview)))
}
Binary request bodies reach the handler as they arrive. A Blob is a Stream of its chunks. So the server never holds a whole upload. A body past max_body_bytes fails its chunk. Then ? answers 413:
let mut body = params.body;
if !body.is_streamed() {
return Err(api::ApiError::new(
api::http::StatusCode::INTERNAL_SERVER_ERROR,
"the body was read before the handler",
));
}
let (mut bytes, mut chunks) = (0, 0);
while let Some(chunk) = body.next().await {
bytes += chunk?.len();
chunks += 1;
}
Sequential responses take api::Items<T> in the same way. These are JSON Lines and JSON text sequences and server-sent events. Return Items::List(vec). Or pass any Stream of items to Items::stream. A sequential request body is a Stream of its items too.
Server-sent events can also take Items::events. Its records carry the id and name of an event. They also carry a retry and comments. A client that reconnects sends the last id back as Last-Event-ID:
/// The feed after the event that a reconnecting client read last. Each event carries its `id`. The client sends it
/// back as `Last-Event-ID`. `retry` tells clients how long to wait before they reconnect. On a quiet minute a
/// comment goes out. So proxies keep the connection open.
fn feed(
events: &[(String, types::ProductEvent)],
last_event_id: Option<&str>,
retry: Duration,
) -> api::Items<types::ProductEvent> {
let after = last_event_id.and_then(|id| events.iter().position(|(e, _)| e == id)).map_or(0, |i| i + 1);
let events = events.iter().skip(after);
let records = std::iter::once(api::Sse::Retry(retry)).chain(events.map(|(id, item)| api::Sse::Event {
id: Some(id.clone()),
event: None,
item: item.clone(),
}));
api::Items::events(futures_util::stream::iter(records.collect::<Vec<_>>())).heartbeat(Duration::from_secs(60))
}
Answer 204 to a client that should stop reconnecting.
Conditional requests
Some GET and HEAD requests get 304 Not Modified (RFC 9110 section 13). This happens when the success response carries an ETag or a Last-Modified. The If-None-Match or If-Modified-Since of the request must also say that the client already holds it. The 304 keeps the validators and caching headers and drops the body. Your handler still runs.
Before a handler changes a resource ctx.preconditions checks If-Match, If-Unmodified-Since and If-None-Match against its current validators. It refuses with 412:
async fn replace_manifest(
&self,
p: ops::replace_manifest::Params,
ctx: &api::Context<'_>,
) -> Result<ops::replace_manifest::Response, api::ApiError> {
let mut manifest = self
.manifest
.lock()
.map_err(|_| api::ApiError::new(api::http::StatusCode::INTERNAL_SERVER_ERROR, "manifest lock poisoned"))?;
let etag = format!("\"v{}\"", manifest.0);
// 412 unless the client changed the version it read.
ctx.preconditions(Some(api::Validators { etag: Some(&etag), last_modified: Some(LAST_MODIFIED) }))?;
*manifest = (manifest.0 + 1, p.body);
Ok(ops::replace_manifest::Response::NoContent)
}
Pass None for a resource that does not exist yet. If-None-Match: * then lets a create through. If-Match: * refuses it.
Range requests
Range requests (RFC 9110 section 14): one byte range of a binary response, for a download that resumes or a player that seeks.
The server answers Range itself on a GET whose success response is binary, such as application/zip or an
image. Your handler returns the whole body as usual:
| Request | Response |
|---|---|
No Range | 200 with Accept-Ranges: bytes |
Range: bytes=1000-, bytes=0-499 or bytes=-500 | 206 Partial Content: those bytes and Content-Range: bytes 1000-4999/5000 |
| A range that starts past the end | 416 Range Not Satisfiable with Content-Range: bytes */5000 |
If-Range next to it with an ETag or date that the body no longer has | 200: the whole new body |
Only a body whose length is known can be cut. That is a body held whole (shared bytes of a crate::Blob are cut
without a copy) or a crate::Blob::ranged. The server calls the open(first, last) of a ranged blob once with
the bytes it sends. So the bytes before the range are never read.
These go out whole with no Accept-Ranges, as RFC 9110 allows: a crate::Blob::stream of unknown length, JSON
and other structured bodies, several ranges in one request and a Range that does not parse. An operation that
declares a 206 (or 2XX) or a Range parameter of its own answers ranges in its handler
(Op::ranges). The server leaves it alone.
Errors
The error of a handler can be the error schema of the description. honig generates From<types::Problem> for api::ApiError for it. Errors that the server raises itself go through error_response:
/// Every error that the server raises itself as plain text. The own typed errors of a handler go out as they are.
fn plain_text_errors() -> axum::Router {
api::Server::new(Catalog::default())
.error_response(|rejection: api::Rejection| {
let reason = &rejection.reason;
if let Some(own) = reason.own() {
return own;
}
let mut response = reason.head();
response
.headers_mut()
.insert(api::http::header::CONTENT_TYPE, api::http::HeaderValue::from_static("text/plain"));
*response.body_mut() = api::Body::from(reason.detail().unwrap_or_default());
response
})
.into_axum()
}
Returns the body that your handler or a layer set (ApiError::with_body). Otherwise the reason in the error
schema of the description (Rejection::schema). Otherwise RFC 9457 problem+json.
The fields of an error schema that the server fills:
| Variant | Meaning |
|---|---|
Status | The HTTP status as a number (code or status). |
StatusText | The HTTP status as text (code declared as a string). |
Title | The reason phrase (title). |
Detail | What went wrong (message, detail or error). |
Type | about:blank (type). |
Violations | Every violation as {path, message} (errors or violations). |
ViolationMessages | Every violation as one string each (errors of strings). |
Const | A required const (object: {const: error}): its one value, as JSON text. |
Empty | A required field nothing maps to: its type’s empty value. |
Server options
The options of honig::Server, from its rustdoc:
A server for the operations O with the tower layers L between routing and each operation. A is whether it
finds who is calling (Authentication).
The generated api::Server::new(api) starts one. Layers run in the order that they are added. The first one is the
outermost as with the ServiceBuilder of tower. Each one is a tower Service of http::Request<Body>. It
answers with a Response or with an error that converts into an ApiError. That error goes out in the error
schema that the description declares. Generic tower layers (Timeout, LoadShed and ConcurrencyLimit) fit
too. Their BoxError becomes a 503.
max_body_bytes
Sets the largest request body in bytes that the server reads. Larger ones get 413. Default: 16 MiB.
The limit is a setting of the server and not a layer outside it, such as RequestBodyLimitLayer of
tower-http:
- The server reads the body itself to decode it. It holds the body in memory. So it needs a limit even with no layer around it.
- A streamed
Blobfails the chunk that goes past the limit. The handler gets that error, and?answers413in the error schema of the description. read_bodyin a layer reads up to the same limit. A layer that checks a signature over the body and the operation that decodes it agree on one number.
A layer outside can only lower the limit. It refuses a request early when its Content-Length is too large.
Its answer then has its own body: map it through Errors::response. A body without Content-Length fails
while the server reads it. The server sees a broken body and answers 400, not 413.
error_response
Sets the response for a request that the server answers without the response of your handler. The cause is no
route, bad input, missing credentials, the Err of a layer, validation, a handler Err or an encoding failure.
Default: Rejection::response.
on_event
Sets the sink that receives the wide event (RequestEvent) of each request once the response is ready. By
default the event is logged with tracing when the server lists the tracing adapter, and dropped otherwise.
errors
Returns the error responses of the description for a layer outside the server. Such a layer is a timeout, a body limit or an IP flood guard. It then answers in the same error schema as the operations.