Web frameworks
Decode incoming WebSocket frames into validated values, validate what you send, and answer an invalid message with a text frame holding the HTTP error body. Two modules with the same three functions:
| Module | Feature | Message type |
|---|---|---|
vld_web::tungstenite | tungstenite | tungstenite::Message 0.26 – 0.30 — also what tokio-tungstenite and async-tungstenite re-export |
vld_web::axum::ws | axum-ws (= axum + axum's ws) | axum::extract::ws::Message |
Install
Cargo.toml
[dependencies]
vld = "0.8"
vld-web = { version = "0.8", features = ["tungstenite"] } # or "axum-ws"
The tungstenite dependency is >=0.26, <0.31 without default features: Cargo picks the version your tokio-tungstenite / async-tungstenite uses.
Example (axum)
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::{response::Response, routing::any, Router};
use vld_web::axum::ws::{decode, error_message};
vld::schema! {
#[derive(Debug)]
pub struct Chat {
pub room: String => vld::string().min(1),
pub text: String => vld::string().min(1).max(500),
}
}
async fn chat(ws: WebSocketUpgrade) -> Response {
ws.on_upgrade(handle)
}
async fn handle(mut socket: WebSocket) {
while let Some(Ok(msg)) = socket.recv().await {
let reply = match decode::<Chat>(&msg) {
Ok(Some(chat)) => Message::text(format!("{}: {}", chat.room, chat.text)),
Ok(None) => continue, // ping / pong / close
Err(err) => error_message(&err),
};
if socket.send(reply).await.is_err() {
break;
}
}
}
let app: Router = Router::new().route("/ws", any(chat));
With tokio-tungstenite the loop is the same, with vld_web::tungstenite::{decode, error_message} on tokio_tungstenite::tungstenite::Message.
An invalid message {"room": "", "text": "hi"} is answered with the text frame:
{"error":"Validation failed","issues":[{"path":".room","message":"String must be at least 1 character","code":"too_small"}]}
API
Both modules:
| Function | Purpose |
|---|---|
decode::<T>(&Message) | Ok(Some(T)) for a valid text / binary JSON frame, Ok(None) for ping, pong, close (and tungstenite's raw frames), Err(VldError) otherwise |
encode::<T>(&value) | T: Serialize + VldParse: serialize, check the JSON against T's own schema, return a text frame |
error_message(&VldError) | Text frame with the 422 body |
vld_web::tungstenite also has a prelude.
Gotchas
- Binary frames are parsed as JSON too; malformed JSON or non-UTF-8 is a single
parse_errorissue at path"". - No size limit of its own: set the WebSocket library's (
max_message_size, axum'sWebSocketUpgrade::max_message_size). error_messageonly builds the frame; whether to keep the socket open or close it is up to you.