Messaging
vld_data::nats validates NATS payloads as JSON: publish checks a value before it is sent, request checks the request and the reply, respond checks a service's answer, decode checks a received Message.
Install
Cargo.toml
[dependencies]
vld = "0.8"
vld-data = { version = "0.8", features = ["nats"] }
async-nats = "0.53"
| Feature | Module | Notes |
|---|---|---|
nats | vld_data::nats | async-nats 0.53, needs Rust 1.89; vld-data enables none of its default features |
Example
use futures_util::StreamExt;
use vld_data::nats::prelude::*;
vld::schema! {
#[derive(Debug, serde::Serialize)]
pub struct Add {
pub a: i64 => vld::number().int(),
pub b: i64 => vld::number().int(),
}
}
vld::schema! {
#[derive(Debug, serde::Serialize)]
pub struct Sum {
pub sum: i64 => vld::number().int(),
}
}
async fn run() -> Result<(), Box<dyn std::error::Error>> {
let client = async_nats::connect("127.0.0.1:4222").await?;
// Service: answer valid requests.
let mut requests = client.subscribe("math.add").await?;
let service = client.clone();
tokio::spawn(async move {
while let Some(msg) = requests.next().await {
if let Ok(add) = decode::<Add>(&msg) {
let _ = respond(&service, &msg, &Sum { sum: add.a + add.b }).await;
}
}
});
// Caller: both directions are validated.
let sum: Sum = request(&client, "math.add", &Add { a: 2, b: 3 }).await?;
assert_eq!(sum.sum, 5);
Ok(())
}
API
publish(&client, subject, &value)— validate, encode as JSON,Client::publish.request::<Req, Resp>(&client, subject, &req)— validatereq,Client::request, then parse and validate the reply asResp.respond(&client, &message, &value)— validate and publish to the message's reply subject.decode::<T>(&message),decode_bytes::<T>(&bytes),encode(&value).VldNatsError—Validation,Serialization,Deserialization,Publish(PublishError),Request(RequestError),NoReply.
Gotchas
- The value type is the schema: published values must be
Serialize + VldParse. respondto a message that was published (not sent withrequest) isNoReply; the value is validated first.- JetStream is not wrapped; decode
jetstream::Messagepayloads withdecode_bytes.