Skip to main content

Crate maiko

Crate maiko 

Source
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

TypeDescription
EventMarker trait for event types (use #[derive(Event)])
ActorTrait for implementing actors
TopicRoutes events to interested actors
SupervisorManages actor lifecycles and runtime
ContextAllows actors to send events and interact with runtime
EnvelopeWraps events with metadata (sender, correlation ID)
ActorIdUnique identifier for a registered actor
OverflowPolicyControls 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:

  1. Stage 1 (producer to broker) - per-actor channel, always blocks when full
  2. 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)] macros
  • monitoring - Event lifecycle hooks for debugging, metrics, and logging
  • test-harness - Test utilities for recording, spying, and asserting on event flow (enables monitoring)
  • serde - JSON serialization support (e.g. Supervisor::to_json())
  • recorder - Built-in Recorder monitor for writing events to JSON Lines files (enables monitoring and serde)

§Examples

See the examples/ directory:

  • pingpong.rs - Simple event exchange between actors
  • guesser.rs - Multi-actor game with topics and timing
  • arbitrage.rs - Test harness demonstration

Modules§

monitoringmonitoring
Monitoring API for observing event flow through the system.
monitorsmonitoring
Ready-to-use monitor implementations.
testingtest-harness
Test harness for observing and asserting on event flow.

Structs§

ActorBuilder
Builder for registering an actor with custom configuration.
ActorConfig
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.
DefaultTopic
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.
OverflowPolicy
Controls what happens when a subscriber’s channel is full.
StepAction
Action returned by an actor step to 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§

Eventmacros
Derives Event marker trait for the type.
Labelmacros
Derives Label trait for enums, returning variant names.
SelfRoutingmacros
Derives Topic<Self> for Self enabling event-as-topic routing.