|
| 1 | +--- |
| 2 | +title: CQRS, events, and scheduling |
| 3 | +description: Organize background collaboration with typed commands, queries, events, A3S Event providers, and lifecycle-managed schedulers. |
| 4 | +--- |
| 5 | + |
| 6 | +# CQRS, events, and scheduling |
| 7 | + |
| 8 | +Boot provides three related but distinct in-application collaboration models. `cqrs` dispatches types to handlers, `events` supplies named events and a provider boundary, and `schedule` triggers work by time. Each model registers through a module and uses the same provider graph. |
| 9 | + |
| 10 | +## CQRS buses |
| 11 | + |
| 12 | +Commands and queries declare their output type. Each command or query type has one handler, while an event can have multiple handlers. |
| 13 | + |
| 14 | +```rust |
| 15 | +use a3s_boot::{Command, CqrsContext, CqrsModule}; |
| 16 | + |
| 17 | +#[derive(Debug)] |
| 18 | +struct RenameUser { |
| 19 | + id: u64, |
| 20 | + name: String, |
| 21 | +} |
| 22 | + |
| 23 | +impl Command for RenameUser { |
| 24 | + type Output = String; |
| 25 | +} |
| 26 | + |
| 27 | +let module = CqrsModule::new("users-cqrs") |
| 28 | + .command_handler::<RenameUser, _>( |
| 29 | + |command: RenameUser, context: CqrsContext| async move { |
| 30 | + let users = context.get::<UserRepository>()?; |
| 31 | + users.rename(command.id, command.name).await |
| 32 | + }, |
| 33 | + ); |
| 34 | +``` |
| 35 | + |
| 36 | +`CommandBus::execute` and `QueryBus::execute` return the declared output. `EventBus::publish` calls all matching handlers and returns the call count. Duplicate command or query handlers fail during registration. A missing handler returns an error at dispatch. |
| 37 | + |
| 38 | +`CqrsContext` resolves providers from the declaring module scope, so handlers do not need a global service locator. Register buses at a business boundary and use `.global()` only when they genuinely span modules. |
| 39 | + |
| 40 | +## Application events |
| 41 | + |
| 42 | +With `events`, `EventModule` exports `EventEmitter` and an A3S Event bus. Event names use dot-separated lowercase form, such as `user.profile.updated`. |
| 43 | + |
| 44 | +```rust |
| 45 | +#[derive(Debug)] |
| 46 | +struct UserEventHandlers; |
| 47 | + |
| 48 | +#[a3s_boot::event_listener] |
| 49 | +impl UserEventHandlers { |
| 50 | + #[a3s_boot::on_event("user.created")] |
| 51 | + async fn created(&self, payload: UserCreated, context: EventContext) -> Result<()> { |
| 52 | + let audit = context.get::<AuditWriter>()?; |
| 53 | + audit.record(payload.id).await |
| 54 | + } |
| 55 | +} |
| 56 | +``` |
| 57 | + |
| 58 | +A listener can receive a typed payload or a complete `EventEnvelope`, and `user.*` wildcard patterns are supported. Registration order is call order. `EventModule::in_process` uses the memory provider. Use `from_provider` to attach another A3S Event provider. |
| 59 | + |
| 60 | +In-process event dispatch is not automatically durable cross-service messaging. Persistence, replay, deduplication, and cross-process delivery depend on the selected event provider. |
| 61 | + |
| 62 | +## Scheduling |
| 63 | + |
| 64 | +`ScheduleModule` supports one-shot timeouts, fixed intervals, and cron: |
| 65 | + |
| 66 | +```rust |
| 67 | +let module = ScheduleModule::in_process("schedule") |
| 68 | + .interval("cache.refresh", Duration::from_secs(30), |context| async move { |
| 69 | + let cache = context.module_ref.get::<CatalogCache>()?; |
| 70 | + cache.refresh().await |
| 71 | + }) |
| 72 | + .timeout("startup.warm", Duration::from_secs(2), |_| async move { |
| 73 | + Ok(()) |
| 74 | + }); |
| 75 | +``` |
| 76 | + |
| 77 | +The `#[schedule]` macro combines with `#[cron]`, `#[interval]`, and `#[timeout]` to generate the same `ScheduledJob` definitions. `ScheduleContext` contains the job name, trigger, run count, and `ModuleRef`. |
| 78 | + |
| 79 | +The scheduler starts during application bootstrap and stops during shutdown. The in-process scheduler does not elect a leader or catch up work missed while a process was stopped. Every instance runs the same job unless the application applies an external lease, leader election, or shared backend. |
| 80 | + |
| 81 | +## Select a model |
| 82 | + |
| 83 | +| Need | Select | |
| 84 | +| ------------------------------------------------------ | --------------------------------------------- | |
| 85 | +| One typed operation with one result | Command | |
| 86 | +| A typed read with a result | Query | |
| 87 | +| Several listeners responding to an in-process fact | CQRS Event or `events` | |
| 88 | +| A3S Event providers, named wildcards, or event queries | `events` | |
| 89 | +| Work triggered by time | `schedule` | |
| 90 | +| Retry, priority, persistence, and workers | [Queue](/protocols/queues-and-ilink) | |
| 91 | +| Delivery through a cross-service protocol | [Message transport](/protocols/microservices) | |
| 92 | + |
| 93 | +## Reliability boundaries |
| 94 | + |
| 95 | +- Handlers and listeners should return contextual errors and never panic for production input. |
| 96 | +- Design idempotency for event, schedule, and queue side effects that may repeat. |
| 97 | +- Put long work on a queue instead of blocking scheduler control paths. |
| 98 | +- Define timezone, overlapping-run policy, and shutdown behavior for every cron job. |
| 99 | +- Use stable schemas and compatibility rules for events that cross an external boundary. |
0 commit comments