Events
A typed in-process event bus — emit any Clone event, listeners declared as methods on any provider, activated by importing one module.
An event listener is a method on any #[injectable] provider, tagged
with #[on_event] inside a #[listeners] impl block. EventsModule, which
the port emitting the event imports to inject the bus, subscribes every
discovered listener
from the fully-assembled container as the boot ends, before the first
lifecycle hook — so an event an #[on_module_init] hook emits reaches its
listeners.
An event is any Clone + Send + 'static type. Dispatch is in-process and
awaited: bus.emit(event) clones the event for each listener registered
on that type and runs them in registration order — once the emitter’s
transaction has committed when it emits inside one, and never for a write
that rolled back. What stays open, a GraphQL subscription among them, reads
the same events at the same commit through
bus.stream(). There is no broker, no retries — for
cross-process or durable work, push a job on the Queue instead.
Install
Section titled “Install”cargo add nest-rs --features eventsA first listener
Section titled “A first listener”A regular #[injectable] provider with one decorated method. The
#[listeners] attribute marks the impl block; #[on_event] marks the
method as a listener for the event type read from its parameter. Here the
posts slice indexes a post it published for search:
use std::sync::Arc;
use nest_rs::core::injectable;use nest_rs::events::listeners;
use crate::posts::{PostPublishedEvent, SearchIndex};
#[injectable]pub struct PostsListener { #[inject] search: Arc<SearchIndex>,}
#[listeners]impl PostsListener { #[on_event] async fn on_post_published(&self, event: PostPublishedEvent) -> anyhow::Result<()> { self.search.index(&event.post).await?; tracing::debug!( target: crate::posts::TARGET, post_id = %event.post.id, "indexed a published post", ); Ok(()) }}#[injectable]makesPostsListenera regular DI provider. It is a plain provider, not a service: it reacts to a fact, it is not an entity’s DB gateway.#[listeners]on the impl block orchestrates the per-method#[on_event]attributes and submits one listener per decorated method.#[on_event]reads the event type from the method’s first parameter after&self. The bus enforcesClone + Send + 'staticon it through the call site. The method returns()or, as here, aResult<(), E>whose error converts intoBox<dyn Error + Send + Sync>—anyhow::Result<()>or a crate’s own error type. Its two keys,timeoutandtransactional, shape the call’s unit of work: Event dispatch.
A listener reacts in process, and a reaction lost to a crash is lost. Work that must survive one — the org’s notification of the same publish — is a queue job, and the service pushes it inside its own transaction rather than from a listener: the job is written into that transaction and filed once it commits, so a crash after the commit loses nothing and a refused push fails the request that made it.
Several listeners on the same provider
Section titled “Several listeners on the same provider”The pattern the framework is built for: one #[injectable] declares the
deps once, multiple decorated methods share them. Two methods can even
listen to the same event; both run, in registration order:
#[injectable]pub struct PostsListener { #[inject] search: Arc<SearchIndex>,}
#[listeners]impl PostsListener { #[on_event] async fn on_post_published(&self, event: PostPublishedEvent) -> anyhow::Result<()> { self.search.index(&event.post).await }
#[on_event] async fn refresh_suggestions(&self, event: PostPublishedEvent) { // refresh what search suggests for `event.post.title` }}Two inventory entries — PostsListener::on_post_published and
PostsListener::refresh_suggestions — both pointing at the same instance. Same
Arc<SearchIndex>, two subscriptions to PostPublishedEvent; both run, in
registration order.
Define an event
Section titled “Define an event”The payload is a plain Clone struct at the producer’s port
(event.rs) — the same feature that emits it owns its definition:
use super::entities::post::Post;
#[derive(Clone)]pub struct PostPublishedEvent { pub post: Post,}That is the whole event surface — any plain Clone + Send + 'static
type. No trait, no derive macro beyond Clone. Any listener method whose
parameter is PostPublishedEvent subscribes to it.
Emit an event
Section titled “Emit an event”The emitter injects Arc<EventBus> like any other dep and calls emit
once the work is done:
#[injectable]pub struct PostsService { #[inject] bus: Arc<EventBus>, #[inject] jobs: Arc<Jobs>, // …}
impl PostsService { pub async fn publish(&self, model: Model) -> Result<Post, PostError> { // … let receipt = self.jobs.push(NotifyQueue, notification).await?; // … let post = Post::from(&published); self.bus .emit(PostPublishedEvent { post: post.clone() }) .await; Ok(post) }}publish writes the post, its notification job and its publication row
inside the request’s transaction, so the listeners wait for it: emit hands
the dispatch to the unit of work, which runs it once the transaction has
committed and drops it if the transaction rolls back. Subscribers hear of a
post that is published, never of one a failed request un-published — and the
service did not have to say so. The job takes the same road through the
outbox: filed after the commit, never after a rollback. Where nothing is
waiting to commit — a safe request, a job running on the pool, an app with
no database — emit returns once every listener has run. Emitting an event
with no subscriber is a no-op (not an error), so adding a listener later does
not require touching the emitter.
A GraphQL subscription or a server-sent stream reads the same events as a stream: Event streams.
Wire it in
Section titled “Wire it in”The producer’s PostsModule lists imports = [EventsModule] to inject
Arc<EventBus>, and the listener’s events/ adapter imports its port, so the
bus arrives with it — a shared singleton, built once however many modules
import it:
use nest_rs::core::module;
use super::listener::PostsListener;use crate::posts::PostsModule;
#[module( imports = [PostsModule], providers = [PostsListener],)]pub struct PostsEventsModule;The app lists the adapter beside the edges it serves, so its imports say which reactions the binary runs:
#[module(imports = [PostsHttpModule, PostsEventsModule])]pub struct ApiModule;Run it
Section titled “Run it”As the boot ends, each wired listener files one mounted line, target
nest_rs::events, as every edge’s unit does:
INFO nest_rs::events: mounted host="PostsListener" method="on_post_published" event="PostPublishedEvent"Each listener call then runs as a unit of work of its own, events.dispatch,
and files one operation line naming the listener and the event, by the same
value.
Event dispatch covers that unit — its transaction, its
deadline, the order the bus keeps and what a failure changes.
Module-gated, even when the crate is shared
Section titled “Module-gated, even when the crate is shared”A worker app that links features for the data layer but only imports
PostsModule keeps PostsListener inert: the inventory entry is
present in the binary but skipped at boot because the provider is not reachable
from the worker’s module tree. The skip is said once on nest_rs::events — at
debug, since a listener in a shared crate whose module this app does not import
is another binary’s, and at warn with a hint naming the remedy when it is the
app’s own code. Same property as queue processors and scheduled jobs.
Reference
Section titled “Reference”crates/nest-rs-events/—EventBus,EventsModule,#[listeners],#[on_event].crates/features/src/posts/event.rs+service.rs— the producer: payload at the port, emitted from the service.crates/nest-rs-events/tests/integration/bus.rs— listener hosts driven end to end.
Going further
Section titled “Going further”- Event dispatch — each listener’s unit of work, its deadline, the order of dispatch and what a failure changes.
- Queue — durable, distributed, retried; the right tool when
the work must outlive the request or run on another binary. A bus event
shares the past-tense
…Eventnaming; the difference is delivery (in-process best-effort vs durable cross-process). - Schedule — for recurring system work, no event needed.
- Providers — the
#[injectable]model#[listeners]builds on (same#[inject]fields, same boot-time access graph).