Skip to content

WebSockets ​

With the ws feature, Socket<In, Out> upgrades a request to a WebSocket and types the messages in both directions. In is what the client sends and Out what the server sends. Messages are JSON text frames.

toml
axum-autodoc = { version = "0.2", features = ["ws"] }

A typed connection ​

The handler takes Socket<In, Out> and returns SocketUpgrade, which on_upgrade gives back. The callback receives a SocketConnection<In, Out>:

rust
#[api(
    summary = "Chat",
    description = "Every message sent is answered with its number and the same text."
)]
pub async fn chat(socket: Socket<ChatIn, ChatOut>) -> SocketUpgrade {
    socket.on_upgrade(converse)
}

async fn converse(mut connection: SocketConnection<ChatIn, ChatOut>) {
    let mut number = 0;
    loop {
        let message = match connection.recv().await {
            Some(Ok(message)) => message,
            Some(Err(SocketError::Decode(_))) => continue,
            Some(Err(_)) | None => break,
        };
        number += 1;
        let reply = ChatOut {
            number,
            text: message.text,
        };
        if connection.send(&reply).await.is_err() {
            break;
        }
    }
}

recv returns None when the client closes, and Some(Err(..)) for a frame that is not the JSON of In (SocketError::Decode), so one bad frame does not end the connection unless you stop on it. The example skips a Decode error and stops on a transport error or a close. Ping and pong frames are handled for you. send serializes Out. close sends a close frame, and into_inner hands back axum's WebSocket when you need the raw frames.

Socket also has protocols and max_message_size, which pass through to axum.

What gets documented ​

The route gets a 101 Switching Protocols response and the extension x-autodoc-websocket, with the schema of each direction:

json
{
  "x-autodoc-websocket": {
    "send": { "$ref": "#/components/schemas/ChatIn" },
    "receive": { "$ref": "#/components/schemas/ChatOut" }
  }
}

send is what the client sends, receive what it gets back. Both types are published under components.schemas. A plain WebSocketUpgrade is documented as 101 with empty schemas on both sides.

The TypeScript client opens the socket with a typed subscribe().

Released under the MIT or Apache-2.0 license.