Skip to main content

Pub

Struct Pub 

Source
pub struct Pub<T, SerErr: EncErr + Send + Sync> { /* private fields */ }
Expand description

Publisher for serializable messages using a pluggable encoder and context.

The publisher encodes messages using the provided Encoder and delegates the actual publish call to an injected PubBrokerTrait so it can work with different backends. The encoder is passed at construction time, enabling runtime format selection and supporting the “any-format” design.

§Example with JSON

use std::sync::Arc;
use serde::Serialize;
use object_transfer::{
  encoders::JSONEncoder,
  Pub,
  traits::PubTrait,
};

#[derive(Serialize)]
struct UserCreated {
  id: u64,
  name: 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<UserCreated, _> = Pub::new(
    js,
    "events.user_created",
    Arc::new(JSONEncoder::new()),
  );

  let event = UserCreated {
    id: 42,
    name: "Jane Doe".to_string(),
  };

  publisher.publish(&event).await?;
  Ok(())
}

§Example with Custom Format

use std::sync::Arc;
use serde::Serialize;
use bytes::Bytes;
use object_transfer::{
  encoders::Encoder,
  Pub,
  traits::PubTrait,
};

#[derive(Serialize)]
struct Message {
  text: String,
}

struct CustomEncoder;

impl Encoder for CustomEncoder {
  type Item = Message;
  type Error = std::fmt::Error;

  fn encode(&self, item: &Self::Item) -> Result<Bytes, Self::Error> {
    Ok(Bytes::from(item.text.clone()))
  }
}

#[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));

  let publisher: Pub<Message, _> = Pub::new(
    js,
    "events.custom",
    Arc::new(CustomEncoder),
  );

  publisher.publish(&Message { text: "Hello".to_string() }).await?;
  Ok(())
}

Implementations§

Source§

impl<T, SerErr> Pub<T, SerErr>
where T: Serialize + Send + Sync, SerErr: EncErr + Send + Sync,

Source

pub fn new( ctx: Arc<dyn PubBrokerTrait + Send + Sync>, subject: impl Into<String>, encoder: Arc<dyn Encoder<Item = T, Error = SerErr> + Send + Sync>, ) -> Self

Creates a new publisher for the given subject with a pluggable encoder.

§Parameters
  • ctx: Backend publish context that delivers serialized bytes.
  • subject: Destination subject or topic to send messages to.
  • encoder: A trait object implementing Encoder for your format. Pass Arc::new(JSONEncoder::new()), Arc::new(MessagePackEncoder::new()), or your custom encoder implementation.
§Encoder Selection

The encoder is passed at construction time, allowing for:

  • Compile-time format selection: Create different publisher instances with different types
  • Runtime format selection: Use Arc<dyn Encoder<...>> to select format dynamically
§Error Types

The generic SerErr type parameter is the error type of your encoder. Different encoders can use different error types (e.g., serde_json::Error, custom error types).

Trait Implementations§

Source§

impl<T, SerErr> PubTrait for Pub<T, SerErr>
where T: Serialize + Send + Sync, SerErr: EncErr + Send + Sync,

Source§

fn publish<'life0, 'life1, 'async_trait>( &'life0 self, obj: &'life1 T, ) -> Pin<Box<dyn Future<Output = Result<(), PubError<Self::EncodeErr>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Serializes the provided object and publishes it to the configured subject using the underlying context.

§Parameters
  • obj: The typed value to encode and send to the subject.
Source§

type Item = T

Source§

type EncodeErr = SerErr

Auto Trait Implementations§

§

impl<T, SerErr> Freeze for Pub<T, SerErr>

§

impl<T, SerErr> !RefUnwindSafe for Pub<T, SerErr>

§

impl<T, SerErr> Send for Pub<T, SerErr>
where T: Send,

§

impl<T, SerErr> Sync for Pub<T, SerErr>
where T: Sync,

§

impl<T, SerErr> Unpin for Pub<T, SerErr>
where T: Unpin,

§

impl<T, SerErr> UnsafeUnpin for Pub<T, SerErr>

§

impl<T, SerErr> !UnwindSafe for Pub<T, SerErr>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.