Struct BroccoliQueue

Source
pub struct BroccoliQueue { /* private fields */ }
Expand description

Main queue interface for interacting with the message broker.

BroccoliQueue provides methods for publishing and consuming messages, as well as processing messages with custom handlers.

Implementations§

Source§

impl BroccoliQueue

Source

pub fn builder(broker_url: impl Into<String>) -> BroccoliQueueBuilder

Creates a new BroccoliQueueBuilder with the specified broker URL.

§Arguments
  • broker_url - The URL of the broker.
§Returns

A new BroccoliQueueBuilder instance.

Source

pub async fn publish<T: Clone + Serialize + DeserializeOwned>( &self, topic: &str, disambiguator: Option<String>, message: &T, options: Option<PublishOptions>, ) -> Result<BrokerMessage<T>, BroccoliError>

Publishes a message to the specified topic.

§Arguments
  • topic - The name of the topic.
  • message - The message to be published.
§Returns

A Result indicating success or failure.

§Errors

If the message fails to publish, a BroccoliError will be returned.

Source

pub async fn publish_batch<T: Clone + Serialize + DeserializeOwned>( &self, topic: &str, disambiguator: Option<String>, messages: impl IntoIterator<Item = T>, options: Option<PublishOptions>, ) -> Result<Vec<BrokerMessage<T>>, BroccoliError>

Publishes a batch of messages to the specified topic.

§Arguments
  • topic - The name of the topic.
  • messages - An iterator over the messages to be published.
§Returns

A Result indicating success or failure.

§Errors

If the messages fail to publish, a BroccoliError will be returned.

Source

pub async fn consume<T: Clone + Serialize + DeserializeOwned>( &self, topic: &str, options: Option<ConsumeOptions>, ) -> Result<BrokerMessage<T>, BroccoliError>

Consumes a message from the specified topic. This method will block until a message is available. This will not acknowledge the message, use acknowledge to remove the message from the processing queue, or reject to move the message to the failed queue.

§Arguments
  • topic - The name of the topic.
§Returns

A Result containing the consumed message, or a BroccoliError on failure.

§Errors

If the message fails to consume, a BroccoliError will be returned.

Source

pub async fn consume_batch<T: Clone + Serialize + DeserializeOwned>( &self, topic: &str, batch_size: usize, timeout: Duration, options: Option<ConsumeOptions>, ) -> Result<Vec<BrokerMessage<T>>, BroccoliError>

Consumes a batch of messages from the specified topic. This method will block until the specified number of messages are consumed. This will not acknowledge the message, use acknowledge to remove the message from the processing queue, or reject to move the message to the failed queue.

§Arguments
  • topic - The name of the topic.
  • batch_size - The number of messages to consume.
  • timeout - The timeout duration for consuming messages.
§Returns

A Result containing a vector of consumed messages, or a BroccoliError on failure.

§Errors

If the messages fail to consume, a BroccoliError will be returned.

Source

pub async fn try_consume<T: Clone + Serialize + DeserializeOwned>( &self, topic: &str, options: Option<ConsumeOptions>, ) -> Result<Option<BrokerMessage<T>>, BroccoliError>

Attempts to consume a message from the specified topic. This method will not block, returning immediately if no message is available. This will not acknowledge the message, use acknowledge to remove the message from the processing queue, or reject to move the message to the failed queue.

§Arguments
  • topic - The name of the topic.
§Returns

A Result containing an Option with the consumed message if available, or a BroccoliError on failure.

§Errors

If the message fails to consume, a BroccoliError will be returned.

Source

pub async fn acknowledge<T: Clone + Serialize + DeserializeOwned>( &self, topic: &str, message: BrokerMessage<T>, ) -> Result<(), BroccoliError>

Acknowledges the processing of a message, removing it from the processing queue.

§Arguments
  • topic - The name of the topic.
  • message - The message to be acknowledged.
§Returns

A Result indicating success or failure.

§Errors

If the message fails to acknowledge, a BroccoliError will be returned.

Source

pub async fn reject<T: Clone + Serialize + DeserializeOwned>( &self, topic: &str, message: BrokerMessage<T>, ) -> Result<(), BroccoliError>

Rejects the processing of a message, moving it to the failed queue.

§Arguments
  • topic - The name of the topic.
  • message - The message to be rejected.
§Returns

A Result indicating success or failure.

§Errors

If the message fails to reject, a BroccoliError will be returned.

Source

pub async fn cancel( &self, topic: &str, message_id: String, ) -> Result<(), BroccoliError>

Cancels the processing of a message, deleting it from the queue.

§Arguments
  • topic - The name of the topic.
  • message_id - The ID of the message to cancel.
§Returns

A Result indicating success or failure.

§Errors

If the message fails to cancel, a BroccoliError will be returned.

Source

pub async fn process_messages<T, F, Fut>( &self, topic: &str, concurrency: Option<usize>, consume_options: Option<ConsumeOptions>, handler: F, ) -> Result<(), BroccoliError>
where T: DeserializeOwned + Send + Clone + Serialize + 'static, F: Fn(BrokerMessage<T>) -> Fut + Send + Sync + Clone + 'static, Fut: Future<Output = Result<(), BroccoliError>> + Send + 'static,

Processes messages from the specified topic with the provided handler function.

§Example
use broccoli_queue::queue::BroccoliQueue;
use broccoli_queue::brokers::broker::BrokerMessage;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct JobPayload {
   id: String,
   task_name: String,
   created_at: chrono::DateTime<chrono::Utc>,
}

#[tokio::main]
async fn main() {
   let queue = BroccoliQueue::builder("redis://localhost:6379")
      .failed_message_retry_strategy(Default::default())
      .pool_connections(5)
      .build()
      .await
      .unwrap();

  queue.process_messages("jobs", None, None, |message: BrokerMessage<JobPayload>| async move {
        println!("Received message: {:?}", message);
        Ok(())
    }).await.unwrap();

}
§Arguments
  • topic - The name of the topic.
  • concurrency - The number of concurrent message handlers.
  • handler - The handler function to process messages. This function should return a BroccoliError on failure.
§Returns

A Result indicating success or failure.

§Errors

If the message fails to process, a BroccoliError will be returned.

Source

pub async fn process_messages_with_handlers<T, F, MessageFut, SuccessFut, ErrorFut, S, E, R>( &self, topic: &str, concurrency: Option<usize>, consume_options: Option<ConsumeOptions>, message_handler: F, on_success: S, on_error: E, ) -> Result<(), BroccoliError>
where T: DeserializeOwned + Send + Clone + Serialize + 'static, F: Fn(BrokerMessage<T>) -> MessageFut + Send + Sync + Clone + 'static, MessageFut: Future<Output = Result<R, BroccoliError>> + Send + 'static, R: Send + Clone + 'static, S: Fn(BrokerMessage<T>, R) -> SuccessFut + Send + Sync + Clone + 'static, SuccessFut: Future<Output = Result<(), BroccoliError>> + Send + 'static, E: Fn(BrokerMessage<T>, BroccoliError) -> ErrorFut + Send + Sync + Clone + 'static, ErrorFut: Future<Output = Result<(), BroccoliError>> + Send + 'static,

Processes messages from the specified topic with the provided handler functions for message processing, success, and error handling.

§Example
use broccoli_queue::queue::BroccoliQueue;
use broccoli_queue::brokers::broker::BrokerMessage;
use broccoli_queue::error::BroccoliError;

#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
struct JobPayload {
    id: String,
    task_name: String,
    created_at: chrono::DateTime<chrono::Utc>,
}

#[tokio::main]
async fn main() {
    let queue = BroccoliQueue::builder("redis://localhost:6379")
        .failed_message_retry_strategy(Default::default())
        .pool_connections(5)
        .build()
        .await
        .unwrap();

    // Define handlers
    async fn process_message(message: BrokerMessage<JobPayload>) -> Result<(), BroccoliError> {
        println!("Processing message: {:?}", message);
        Ok(())
    }

    async fn on_success(message: BrokerMessage<JobPayload>, _result: ()) -> Result<(), BroccoliError> {
        println!("Successfully processed message: {}", message.task_id);
        Ok(())
    }

    async fn on_error(message: BrokerMessage<JobPayload>, error: BroccoliError) -> Result<(), BroccoliError> {
        println!("Failed to process message {}: {:?}", message.task_id, error);
        Ok(())
    }

    // Process messages with 3 concurrent workers
    queue.process_messages_with_handlers(
        "jobs",
        Some(3),
        None,    
        process_message,
        on_success,
        on_error
    ).await.unwrap();
}
§Arguments
  • topic - The name of the topic.
  • concurrency - The number of concurrent message handlers.
  • message_handler - The handler function to process messages. This function should return a BroccoliError on failure.
  • on_success - The handler function to call on successful message processing. This function should return a BroccoliError on failure.
  • on_error - The handler function to call on message processing failure. This function should return a BroccoliError on failure.
§Returns

A Result indicating success or failure.

§Errors

If the message fails to process, a BroccoliError will be returned.

Source

pub async fn queue_status( &self, queue_name: String, disambiguator: Option<String>, ) -> Result<QueueStatus, BroccoliError>

Retrieves the status of the specified queue.

§Arguments
  • queue_name - The name of the queue.
§Returns

A Result containing the status of the queue, or a BroccoliError on failure.

§Errors

If the queue status fails to be retrieved, a BroccoliError will be returned.

Trait Implementations§

Source§

impl Clone for BroccoliQueue

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more

Auto Trait Implementations§

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<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,