Event streams
With the sse feature, EventStream<T> sends a stream of T as server-sent events and documents what each event holds.
axum-autodoc = { version = "0.2", features = ["sse"] }Return a stream of values
Build it from any Stream<Item = T>. Each item goes out as one event whose data: is the JSON of the item:
#[api(
summary = "Follow user changes",
description = "One event for every user created or deleted while the stream is open."
)]
pub async fn user_events(State(state): State<AppState>) -> EventStream<UserEvent> {
let receiver = state.events.subscribe();
let events = stream::unfold(receiver, |mut receiver| async move {
match receiver.recv().await {
Ok(event) => Some((event, receiver)),
Err(RecvError::Lagged(_) | RecvError::Closed) => None,
}
});
EventStream::new(events).keep_alive(KeepAlive::default())
}keep_alive takes axum's KeepAlive, so idle connections stay open through proxies. An item that cannot be serialized is skipped and the stream goes on. This one ends the stream when a client falls so far behind that the channel dropped events, so the client reconnects and reads the current state instead of missing events without knowing.
What gets documented
The default document is OpenAPI 3.2.0, which has a place for the shape of one event. The 200 response has the media type text/event-stream and an itemSchema describing the parsed event: data is required, and event, id and retry are optional. data is a string whose contentMediaType is application/json and whose contentSchema is the schema of T, since each event carries the JSON of one item. There is no schema:
{
"200": {
"content": {
"text/event-stream": {
"itemSchema": {
"type": "object",
"required": ["data"],
"properties": {
"data": {
"type": "string",
"contentMediaType": "application/json",
"contentSchema": { "$ref": "#/components/schemas/UserEvent" }
},
"event": { "type": "string" },
"id": { "type": "string" },
"retry": { "type": "integer", "minimum": 0 }
}
}
}
}
}
}Older document versions
Under .openapi_version("3.1.0") or a 3.0 version, itemSchema does not exist, so the media type keeps schema: { "type": "string" } (what travels on the wire) and the schema of one event goes under the extension x-autodoc-item-schema. The document stays valid for linters such as Redocly, and the types it points at stay published.
axum's own Sse<S> is documented too, as text/event-stream; under 3.2 each event's data is a plain string, under 3.1 and 3.0 the schema is a string with no item schema.
The TypeScript client turns the response into an AsyncIterable<T>.