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
impl EventBus
Sourcepub fn with_capacity(capacity: usize) -> Self
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).
Sourcepub fn builder() -> EventBusBuilder
pub fn builder() -> EventBusBuilder
返回一个 [EventBusBuilder] 用于配置 EventBus。
Sourcepub fn registry(&self) -> &Arc<EventRegistry> ⓘ
pub fn registry(&self) -> &Arc<EventRegistry> ⓘ
获取事件注册表引用。
注册表跟踪所有已发布/订阅的事件类型及其元数据。
Sourcepub fn execution_log(&self) -> Option<&Arc<ExecutionLog>>
pub fn execution_log(&self) -> Option<&Arc<ExecutionLog>>
获取执行日志引用(如果已配置)。
执行日志记录了事件发布和 Handler 执行的历史。
Sourcepub fn register_publish_callback(
&self,
callback: Arc<dyn Fn(&str, Value) + Send + Sync>,
)
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.
Sourcepub async fn publish<E: Event>(&self, event: E) -> Result<()>
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.
Sourcepub async fn subscribe<E, F, Fut>(&self, handler: F) -> Result<Subscription>
pub async fn subscribe<E, F, Fut>(&self, handler: F) -> Result<Subscription>
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 implementEvent).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.
Sourcepub async fn subscribe_with_retry<E, F, Fut>(
&self,
handler: F,
retry_policy: RetryPolicy,
) -> Result<Subscription>
pub async fn subscribe_with_retry<E, F, Fut>( &self, handler: F, retry_policy: RetryPolicy, ) -> Result<Subscription>
Subscribe with a custom retry policy (overrides the bus default).
Sourcepub async fn subscribe_pattern<E, F, Fut>(
&self,
pattern: &str,
handler: F,
) -> Result<Subscription>
pub async fn subscribe_pattern<E, F, Fut>( &self, pattern: &str, handler: F, ) -> Result<Subscription>
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.
Sourcepub async fn subscribe_pattern_with_retry<E, F, Fut>(
&self,
pattern: &str,
handler: F,
retry_policy: RetryPolicy,
) -> Result<Subscription>
pub async fn subscribe_pattern_with_retry<E, F, Fut>( &self, pattern: &str, handler: F, retry_policy: RetryPolicy, ) -> Result<Subscription>
Subscribe to a pattern with a custom retry policy.
Sourcepub fn shutdown(&self)
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.
Sourcepub async fn shutdown_graceful(&self, timeout: Duration) -> usize
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).