Expand description
§Maiko
A topic-based pub/sub actor runtime for Tokio.
Maiko helps you build multi-task Tokio applications without manually wiring channels or spawning tasks. Declare actors and subscriptions, and Maiko handles event routing and lifecycle management. Think Kafka-style pub/sub, but embedded in your Tokio application.
§Quick Start
use maiko::*;
#[derive(Event, Clone, Debug)]
enum MyEvent {
Hello(String),
}
struct Greeter;
impl Actor for Greeter {
type Event = MyEvent;
async fn handle_event(&mut self, envelope: &Envelope<Self::Event>) -> Result<()> {
if let MyEvent::Hello(name) = envelope.event() {
println!("Hello, {}!", name);
}
Ok(())
}
}
#[tokio::main]
async fn main() -> Result<()> {
let mut sup = Supervisor::<MyEvent>::default();
sup.add_actor("greeter", |_ctx| Greeter, &[DefaultTopic])?;
sup.start().await?;
sup.send(MyEvent::Hello("World".into())).await?;
sup.stop().await
}§Core Types
| Type | Description |
|---|---|
Event | Marker trait for event types (use #[derive(Event)]) |
Actor | Trait for implementing actors |
Topic | Routes events to interested actors |
Supervisor | Manages actor lifecycles and runtime |
Context | Allows actors to send events and interact with runtime |
Envelope | Wraps events with metadata (sender, correlation ID) |
ActorId | Unique identifier for a registered actor |
OverflowPolicy | Controls behavior when a subscriber’s channel is full |
§Topic-Based Routing
Actors subscribe to topics, and events are automatically routed to all interested subscribers.
Use DefaultTopic when you don’t need routing, or implement Topic for custom filtering:
#[derive(Debug, Hash, Eq, PartialEq, Clone)]
enum MyTopic { Data, Control }
impl Topic<MyEvent> for MyTopic {
fn from_event(event: &MyEvent) -> Self {
match event {
MyEvent::Data(_) => MyTopic::Data,
MyEvent::Control(_) => MyTopic::Control,
}
}
}
sup.add_actor("processor", |ctx| Processor::new(ctx), &[MyTopic::Data])?;§Flow Control
Events pass through two channel stages:
- Stage 1 (producer to broker) - per-actor channel, always blocks when full
- Stage 2 (broker to subscriber) - per-actor channel, governed by
OverflowPolicy
Override Topic::overflow_policy() to control stage 2 behavior per topic:
fn overflow_policy(&self) -> OverflowPolicy {
match self {
MyTopic::Data => OverflowPolicy::Block, // wait for space
MyTopic::Metrics => OverflowPolicy::Drop, // discard if slow
}
}Producers can check Context::is_sender_full() to skip non-essential
sends when stage 1 is congested:
if !ctx.is_sender_full() {
ctx.send(Event::Telemetry(stats)).await?;
}See OverflowPolicy for details on each variant and trade-offs.
§Features
macros(default) -#[derive(Event)],#[derive(Label)], and#[derive(SelfRouting)]macrosmonitoring- Event lifecycle hooks for debugging, metrics, and loggingtest-harness- Test utilities for recording, spying, and asserting on event flow (enablesmonitoring)serde- JSON serialization support (e.g.Supervisor::to_json())recorder- Built-inRecordermonitor for writing events to JSON Lines files (enablesmonitoringandserde)
§Examples
See the examples/ directory:
pingpong.rs- Simple event exchange between actorsguesser.rs- Multi-actor game with topics and timingarbitrage.rs- Test harness demonstration
Modules§
- monitoring
monitoring - Monitoring API for observing event flow through the system.
- monitors
monitoring - Ready-to-use monitor implementations.
- testing
test-harness - Test harness for observing and asserting on event flow.
Structs§
- Actor
Builder - Builder for registering an actor with custom configuration.
- Actor
Config - Per-actor configuration.
- ActorId
- Unique identifier for a registered actor.
- Config
- Runtime configuration for the supervisor and actors.
- Context
- Runtime-provided context for an actor to interact with the system.
- Default
Topic - Unit topic for systems that don’t need topic-based routing.
- Envelope
- The unit carried through all Maiko channels.
- Meta
- Metadata attached to every
Envelope. - Subscribe
- Specifies which topics an actor subscribes to.
- Supervisor
- Coordinates actors and the broker, and owns the top-level runtime.
Enums§
- Error
- The single error type for all Maiko operations.
- Overflow
Policy - Controls what happens when a subscriber’s channel is full.
- Step
Action - Action returned by an actor
stepto influence scheduling.
Traits§
- Actor
- Core trait implemented by user-defined actors.
- Event
- Marker trait for events processed by Maiko.
- Label
- Human-readable label for an event variant.
- Topic
- Maps events to routing topics.
Type Aliases§
- EventId
- Unique event identifier. Currently a UUID v4 stored as
u128. - Result
- Convenience alias for
Result<T, maiko::Error>.
Derive Macros§
- Event
macros - Derives
Eventmarker trait for the type. - Label
macros - Derives
Labeltrait for enums, returning variant names. - Self
Routing macros - Derives
Topic<Self> for Selfenabling event-as-topic routing.