Messaging
vld_data::socketio validates the arguments of the socketio-next Socket.IO v4 client as JSON: values before they are emitted or sent as an ack, event arguments and ack replies after they arrive.
socketio-next is at 0.2: its API may change in a minor release, and this module follows it.Install
Cargo.toml
[dependencies]
vld = "0.8"
vld-data = { version = "0.8", features = ["socketio"] }
socketio-next = "0.2"
| Feature | Module | Notes |
|---|---|---|
socketio | vld_data::socketio | socketio-next 0.2 with default features off (no TLS backend); your own socketio-next dependency with its default rustls (or native-tls) feature adds https / wss |
Example
use std::time::Duration;
use socketio_next::{Client, ClientBuilder, Event};
use vld_data::socketio::prelude::*;
vld::schema! {
#[derive(Debug, serde::Serialize)]
pub struct ChatMessage {
pub text: String => vld::string().min(1).max(500),
}
}
vld::schema! {
#[derive(Debug, serde::Serialize)]
pub struct Saved {
pub id: i64 => vld::number().int().min(1),
}
}
async fn run() -> Result<(), VldSocketIoError> {
let client = ClientBuilder::new("http://localhost:3000")
// Runs only with a valid first argument; invalid ones are logged.
.on("chat", validated(|msg: ChatMessage, _client: Client| async move {
println!("{}", msg.text);
}))
// The server emits `save` with a callback: the return value is
// validated and sent as the ack.
.on("save", answer(|msg: ChatMessage, _client: Client| async move {
Saved { id: 1 }
}))
// Invalid data: tell the server instead of logging.
.on("strict", validated_or(
|msg: ChatMessage, _client: Client| async move { /* … */ },
|event: Event, client: Client, error: VldSocketIoError| async move {
let _ = client.emit("rejected", event.name().to_owned());
},
))
.connect()
.await?;
emit(&client, "chat", &ChatMessage { text: "hi".into() })?;
let saved: Saved = emit_with_ack(
&client, "save", &ChatMessage { text: "keep".into() }, Duration::from_secs(5),
).await?;
Ok(())
}
API
emit(&client, event, &value)— validate,Client::emitwith the value as the one argument.emit_with_ack::<Req, Resp>(&client, event, &req, timeout)— validatereq,Client::emit_with_ack, then validate the ack's first argument asResp.validated(handler)/validated_or(handler, on_invalid)— wrap anonhandlerFn(T, Client) -> Future: it runs only when the first argument is a validT. On invalid datavalidatedcallslog_invalid(atracingwarning);on_invalid(event, client, error)is yours.answer(handler)/answer_or(handler, on_invalid)— for events the server emits with a callback: the handler returnsR: Serialize + VldParse, which is validated and sent as the ack. Invalid input, an invalid return value or an event without callback go toon_invalid(the event still holds the callback, so it can ack an error value).ack(&event, &value)— answer a server callback by hand;NoAckwhen the server asked for none.decode::<T>(&event)(first argument),decode_arg::<T>(&event, index),decode_args::<T>(&event)(all arguments as one array);decode_payload_arg/decode_payload_argson aPayload(an ack reply);encode(&value).VldSocketIoError—Validation,Serialization,NoArgument(index),NoAck,SocketIo(socketio_next::Error).
Gotchas
- The value type is the schema: emitted values must be
Serialize + VldParse; a value is sent as one argument. For several arguments calldecode_argswith a schema over the array, orClient::emitwith your ownPayload. - Binary data is not validated: a binary argument is missing from the JSON arguments (
NoArgument), a buffer inside an argument is the placeholder{"_placeholder":true,"num":n}; read buffers withevent.payload().binary(). - Namespaces need nothing extra: the helpers work on the client of any namespace.
- An invalid value never reaches the client; a valid one can still fail there (
SocketIo(Error::NotConnected),AckTimeout, …).