Skip to main content

Crate actor_helper

Crate actor_helper 

Source
Expand description

Lightweight, runtime-agnostic actor pattern with dynamic error types.

Works with tokio, async-std, or blocking threads. Uses flume channels.

§Quick Start

use std::io;
use actor_helper::{Handle, act_ok};

// Public API
pub struct Counter {
    handle: Handle<CounterActor, io::Error>,
}

impl Counter {
    pub fn new() -> Self {
        Self { handle: Handle::spawn(CounterActor { value: 0 }).0 }
    }

    pub async fn increment(&self, by: i32) -> io::Result<()> {
        self.handle.call(act_ok!(actor => async move {
            actor.value += by;
        })).await
    }

    pub async fn get(&self) -> io::Result<i32> {
        self.handle.call(act_ok!(actor => async move { actor.value })).await
    }

    pub async fn is_running(&self) -> bool {
        self.handle.state() == ActorState::Running
    }
}

// Private actor
struct CounterActor {
    value: i32,
}

§Error Types

Use any error type implementing ActorError:

  • io::Error (default)
  • anyhow::Error (with anyhow feature)
  • String
  • Box<dyn Error>

§Blocking/Sync

// Use spawn_blocking and call_blocking instead of spawn and call
let (handle, _) = Handle::<MyActor, io::Error>::spawn_blocking(MyActor { value: 0 });
handle.call_blocking(act_ok!(actor => async move { actor.value }))?;

§Custom Loops

Use spawn_with / spawn_blocking_with for custom receive loops (e.g. tokio::select!):

use actor_helper::{Handle, Receiver, Action};

let (handle, _) = Handle::<MyActor, io::Error>::spawn_with(
    MyActor { value: 0 },
    |mut actor, rx| async move {
        loop {
            tokio::select! {
                Ok(action) = rx.recv_async() => action(&mut actor).await,
                _ = some_background_task() => { /* ... */ },
                else => break Ok(()),
            }
        }
    },
);

§Notes

  • Actions run sequentially, long tasks block the mailbox
  • Panics are caught and converted to errors with location info
  • call requires tokio or async-std feature
  • call_blocking has no feature requirements

Macros§

act
Create action returning Result<T, E>.
act_ok
Create action returning T, auto-wrapped as Ok(T).

Structs§

Handle
Cloneable handle to send actions to actor A with error type E.

Enums§

ActorState
Represents the current state of an actor.

Traits§

ActorError
Convert panic/actor-stop messages into your error type.

Functions§

block_on
Execute async futures in blocking context. Run a future to completion on the current thread.

Type Aliases§

Action
Action sent to an actor: FnOnce(&mut A) -> Future<()>.
ActorFut
Pinned, boxed future used by action helpers and macros.
PreBoxActorFut
Unboxed future type for actor actions.
Receiver
Flume unbounded receiver. Actors receive actions via Receiver<Action<Self>>.
Sender
Flume unbounded sender.