Expand description
This library provides a simple and efficient way to transfer objects between different parts of an application or between different applications through message brokers like NATS. It supports serialization and/or deserialization of various data formats, making it easy to send and/or receive complex data structures.
§Pluggable Encoder/Decoder Architecture
A key feature of this library is its “any-format” design: you can use any
serialization format by implementing the encoders::Encoder and encoders::Decoder traits.
The library doesn’t restrict you to built-in formats—JSON, MessagePack, Protocol Buffers,
CBOR, or custom formats all work seamlessly.
§Quick Example
use std::sync::Arc;
use serde::{Serialize, Deserialize};
use object_transfer::{
encoders::{JSONEncoder, JSONDecoder},
Pub, Sub, SubOpt,
traits::PubTrait,
};
#[derive(Serialize, Deserialize, Clone, Debug)]
struct Event {
id: u32,
message: String,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = async_nats::connect("demo.nats.io").await?;
let js = Arc::new(async_nats::jetstream::new(client));
// Create a publisher with JSON encoder
let publisher: Pub<Event, _> = Pub::new(
js.clone(),
"events",
Arc::new(JSONEncoder::new()),
);
let event = Event { id: 1, message: "Hello".to_string() };
publisher.publish(&event).await?;
Ok(())
}§Implementing Custom Formats
Implement encoders::Encoder and encoders::Decoder for your format:
use bytes::Bytes;
use serde::Serialize;
use object_transfer::encoders::Encoder;
struct MyFormat;
#[derive(serde::Serialize)]
struct MyData { id: u32 }
impl Encoder for MyFormat {
type Item = MyData;
type Error = std::fmt::Error;
fn encode(&self, item: &Self::Item) -> Result<Bytes, Self::Error> {
Ok(Bytes::from(format!("id:{}", item.id)))
}
}Then pass your encoder/decoder to Pub::new() or Sub::new().
§CI/CD Status
Re-exports§
pub use traits::PubTrait;pub use traits::SubTrait;pub use traits::UnSubTrait;
Modules§
- brokers
- Broker implementations and trait abstractions for message publishing and subscription.
- encoders
- Serialization and deserialization traits and implementations.
- errors
- Error definitions shared across the crate. Defines high-level error types (AckError, PubError, SubError, UnSubError) that use BrokerError as a common wrapper for NATS, JetStream, and serialization errors.
- traits
- Core trait abstractions for publish-subscribe messaging with strongly-typed items.