Payload Formats
Encode text or JSON, validate received data, and adapt a serializer with no change to the SDK.
Before you start: obtain a connected chat segment with the setup from Messaging. Each format below is an alternative. Both the sender and the receiver must agree on the format.
1. Start with text
use useceleris_client::{read_text, text_payload};
let text_listener = chat.on_message(|payload, _metadata| {
if let Ok(text) = read_text(payload) {
println!("{text}");
}
});
chat.publish(text_payload("Hello")).await?;
// Later, when this receiver is no longer needed:
text_listener.remove();
Celeris carries opaque bytes. It does not infer a content type, compress JSON automatically, or translate formats for recipients. text_payload encodes a &str as UTF-8. read_text returns CelerisError::Configuration for bytes that are not valid UTF-8.
2. Send and validate JSON
The crate depends on no serializer, so it has no JSON helper. Give serde_json to PayloadCodec, as step 3 explains:
cargo add serde --features derive
cargo add serde_json
use serde::{Deserialize, Serialize};
use useceleris_client::PayloadCodec;
#[derive(Serialize, Deserialize)]
struct TypingEvent {
r#type: String,
active: bool,
}
let typing: PayloadCodec<TypingEvent, serde_json::Error> =
PayloadCodec::new(serde_json::to_vec, |payload| serde_json::from_slice(payload));
let receiver = typing.clone();
let json_listener = chat.on_message(move |payload, _metadata| {
match receiver.read_payload(payload) {
Ok(event) if event.r#type == "typing" => println!("Peer typing: {}", event.active),
_ => println!("Ignored an invalid typing event."),
}
});
let payload = typing.encode_payload(&TypingEvent {
r#type: "typing".to_owned(),
active: true,
})?;
chat.publish(payload).await?;
The type that you decode into is an assertion, not a validation. By default, serde ignores unknown fields. It fails for an absent field, unless the field is an Option or has #[serde(default)]. Validate anything received from a publisher that you do not control. serde_json::to_vec writes compact JSON with fields in declaration order. Compare decoded values across SDKs, not bytes. Render received text safely. Do not insert it as HTML.
3. Bring your own serializer
The SDK includes one adapter, not a separate bundled library for every format. PayloadCodec::new(encode, decode) takes two functions:
encodetakes a&Valueand returnsResult<Vec<u8>, Failure>.decodetakes the received&[u8]and returnsResult<Value, Failure>.
The codec has encode_payload and read_payload, which call your functions directly. The adapter does not validate values. Errors from your encoder or decoder propagate unchanged. A PayloadCodec is cheap to clone, so you can move a clone into a listener. The sender and the receiver must use compatible codecs.
MessagePack
cargo add rmp-serde
#[derive(Serialize, Deserialize)]
struct Reading {
sensor: String,
value: f64,
}
let readings: PayloadCodec<Reading, Box<dyn std::error::Error + Send + Sync>> = PayloadCodec::new(
|reading| Ok(rmp_serde::to_vec_named(reading)?),
|payload| Ok(rmp_serde::from_slice(payload)?),
);
let receiver = readings.clone();
let binary_listener = chat.on_message(move |payload, _metadata| {
if let Ok(reading) = receiver.read_payload(payload) {
println!("{} {}", reading.sensor, reading.value); // Validate the decoded value before trusting it.
}
});
let payload = readings.encode_payload(&Reading {
sensor: "temperature".to_owned(),
value: 21.5,
})?;
chat.publish(payload).await?;
MessagePack keeps binary fields, and it distinguishes integers from floats. JSON cannot do this. to_vec_named writes the field names, so other SDKs can decode a map.
Protobuf
This example uses prost and the type that prost-build generates from a schema such as this one:
syntax = "proto3";
package demo;
message Reading {
string sensor = 1;
double value = 2;
}
use prost::Message;
let readings: PayloadCodec<demo::Reading, prost::DecodeError> = PayloadCodec::new(
|reading: &demo::Reading| Ok(reading.encode_to_vec()),
|payload| demo::Reading::decode(payload),
);
let payload = readings.encode_payload(&demo::Reading {
sensor: "temperature".to_owned(),
value: 21.5,
})?;
Publish payload as in the MessagePack example. The numbers in the schema identify fields on the wire. Keep them stable when you change your schema. A Rust receiver and a JavaScript or Python sender interoperate when all parties use the same schema.
A custom format
You can also write the encoder and the decoder yourself. The codec only needs the types to match:
encodetakes your value and returns the payload bytes.decodetakes the received bytes and returns your value.
// Takes your value. Returns the payload bytes.
fn encode_position(position: &Position) -> Result<Vec<u8>, String> {
// Your own logic: write the position into bytes.
Ok(payload)
}
// Takes the received bytes. Returns your value.
fn decode_position(payload: &[u8]) -> Result<Position, String> {
// Your own logic: read the position from the bytes.
Ok(position)
}
let positions = PayloadCodec::new(encode_position, decode_position);
Both ends must agree on your format. If the format can change, include a version number so that a receiver can tell the formats apart.
Mix text, JSON, MessagePack, and Protobuf receivers on one segment only when your application can distinguish the formats. Separate segments or an explicit envelope can provide that distinction. A successful decode does not prove who sent the message.
4. Handle timestamps
The SDK's metadata and your message payload are separate. Your serializer decides the types inside a payload. The SDK uses these Rust types for its own values:
| Value | Rust type |
|---|---|
Presence request page and per_page | i32 |
Presence page total, per_page, current_page, from, to | i32 |
connect_timeout and presence_query_timeout | Option<Duration>, None for the default |
Reconnect reason disconnected_at and replay_lookback | SystemTime and Duration, only in CredentialReason::Reconnect |
Recovery event retry_index | u32 |
Message, notice, presence-event, and presence-record timestamp | i64, Unix milliseconds |
Convert a timestamp to a SystemTime value with the standard library. The timestamp serializes to JSON as a number with no loss:
use std::time::{Duration, SystemTime, UNIX_EPOCH};
let metadata_listener = chat.on_message(|_payload, metadata| {
let sent_at: SystemTime = UNIX_EPOCH + Duration::from_millis(metadata.timestamp.max(0) as u64);
println!("{sent_at:?}");
let encoded = serde_json::json!({
"message_id": metadata.message_id,
"timestamp": metadata.timestamp,
});
println!("{encoded}");
});
A JavaScript consumer that needs the exact value must read large timestamps as bigint values. Do not log sensitive payloads, identities, or error resources in production.
Next: Presence. For format tradeoffs, see Binary Messaging.