Skip to main content

EventBus

Struct EventBus 

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

Thread-safe, async event bus backed by tokio broadcast channels.

§Overview

The EventBus provides a publish/subscribe pattern where:

  • Publishers send typed events via EventBus::publish.
  • Subscribers register async handlers via EventBus::subscribe.
  • Events are type-erased via Arc<dyn Any + Send + Sync> and sent through broadcast channels without serialization.
  • Each event type gets its own dedicated broadcast channel.
  • Pattern subscriptions use a global channel that receives all published events.

§Thread Safety

Channel bookkeeping uses std::sync::RwLock for fast, non-blocking HashMap lookups on the hot path. The bus is wrapped in Arc, making it safe to share across tasks. It implements Clone (cheap reference clone) and Send + Sync.

§Example

use anycms_event::prelude::*;

#[derive(Clone, Debug)]
struct UserCreated { name: String }

impl Event for UserCreated {
    fn event_name() -> &'static str { "user.created" }
}

let bus = EventBus::new();

bus.subscribe(|event: UserCreated| async move {
    println!("New user: {}", event.name);
    Ok(())
}).await?;

bus.publish(UserCreated { name: "Alice".into() }).await?;

Implementations§

Source§

impl EventBus

Source

pub fn new() -> Self

Create a new event bus with the default channel capacity (1024).

Source

pub fn with_capacity(capacity: usize) -> Self

Create a new event bus with the specified broadcast channel capacity.

The capacity controls how many messages can be buffered before slow subscribers start being lagged (dropping old messages).

Source

pub fn builder() -> EventBusBuilder

返回一个 [EventBusBuilder] 用于配置 EventBus。

Source

pub fn registry(&self) -> &Arc<EventRegistry>

获取事件注册表引用。

注册表跟踪所有已发布/订阅的事件类型及其元数据。

Source

pub fn execution_log(&self) -> Option<&Arc<ExecutionLog>>

获取执行日志引用(如果已配置)。

执行日志记录了事件发布和 Handler 执行的历史。

Source

pub fn register_publish_callback( &self, callback: Arc<dyn Fn(&str, Value) + Send + Sync>, )

Register a publish callback that is invoked after every event is published.

The callback receives the event name and its JSON representation. Events that return None from Event::to_json will not trigger callbacks.

This is the primary mechanism for TriggerRuleEngine to observe all events without needing a typed subscription.

Source

pub async fn publish<E: Event>(&self, event: E) -> Result<()>

Publish a typed event to the bus.

The event is type-erased via Arc<dyn Any + Send + Sync> and sent through the broadcast channel associated with its event type. If there are no subscribers, the publish is a no-op (not an error).

The event is also sent to the global channel for pattern subscribers.

§Errors

Returns EventBusError::PublishFailed if the channel returns an unexpected error.

Source

pub async fn subscribe<E, F, Fut>(&self, handler: F) -> Result<Subscription>
where E: Event, F: Fn(E) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<()>> + Send + 'static,

Subscribe to a specific event type with an async handler.

The handler is spawned as a background tokio task that listens for events on the broadcast channel. If the handler falls behind, lagged messages are logged as warnings but the subscriber continues.

Uses the bus-level RetryPolicy (default: no retry). For custom retry, use EventBus::subscribe_with_retry.

§Type Parameters
  • E: The event type to subscribe to (must implement Event).
  • F: The handler closure type.
  • Fut: The future returned by the handler closure.
§Returns

A Subscription handle with the event name and a unique ID. The subscription can be used to unsubscribe via Subscription::unsubscribe.

Source

pub async fn subscribe_with_retry<E, F, Fut>( &self, handler: F, retry_policy: RetryPolicy, ) -> Result<Subscription>
where E: Event, F: Fn(E) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<()>> + Send + 'static,

Subscribe with a custom retry policy (overrides the bus default).

Source

pub async fn subscribe_pattern<E, F, Fut>( &self, pattern: &str, handler: F, ) -> Result<Subscription>
where E: Event, F: Fn(E) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<()>> + Send + 'static,

Subscribe to a topic pattern with wildcard support.

Patterns support:

  • * matches a single segment (e.g., "user.*" matches "user.created")
  • ** matches multiple segments (e.g., "user.**" matches "user.foo.bar")
  • Exact match when no wildcards are present

Pattern subscribers listen on the global channel and filter events using crate::topic::matches. This allows a single subscriber to receive events of different types that share a topic namespace.

Uses the bus-level RetryPolicy (default: no retry). For custom retry, use EventBus::subscribe_pattern_with_retry.

Source

pub async fn subscribe_pattern_with_retry<E, F, Fut>( &self, pattern: &str, handler: F, retry_policy: RetryPolicy, ) -> Result<Subscription>
where E: Event, F: Fn(E) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<()>> + Send + 'static,

Subscribe to a pattern with a custom retry policy.

Source

pub fn shutdown(&self)

Shut down the event bus by aborting all subscriber tasks and clearing channels.

All active subscriber tasks are immediately aborted. This is useful for a fast shutdown during application termination.

Source

pub async fn shutdown_graceful(&self, timeout: Duration) -> usize

Gracefully shut down the event bus, waiting for subscriber tasks to complete.

Clears channels first so no new events arrive, then waits for all subscriber tasks to finish. If the timeout elapses before all tasks complete, returns the number of tasks that may still be running.

Returns 0 on success (all tasks completed within the timeout).

Trait Implementations§

Source§

impl Clone for EventBus

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Default for EventBus

Source§

fn default() -> Self

Returns the “default value” for a type. 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<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> 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<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