actorlib 0.1.2

Indeed, an actor library, not a framework, written in Rust
Documentation
actorlib-0.1.2 has been yanked.

Actorlib

Project license Pull Requests welcome Rust crate

Indeed, an actor library, not a framework, written in Rust

Features

  • Async for sending messages
  • Async for messages processing in actor
  • Support messaging like send and forget
  • Support messaging like send and wait response
  • Mutable state of actor
  • Self reference in actor from context

Usage

Cargo.toml

[dependencies]

actorlib = "0.1.2"

echo.rs

pub struct Echo;

#[derive(Debug)]
pub enum Message {
    Ping,
}

#[derive(Debug)]
pub enum Response {
    Pong {counter: u32},
}

#[derive(Debug,Clone)]
pub struct State {
    pub counter: u32,
}

impl Echo {
    pub async fn new() -> Arc<Actor<Message, State, Response>> {

        let state = State {
            counter: 0,
        };

        Actor::new("echo".to_string(), move |ctx| {
            Box::pin(async move {
                match ctx.mgs {
                    Message::Ping => {
                        println!("Received Ping");
                        let mut state_lock = ctx.state.lock().await;
                        state_lock.counter += 1;
                        Ok(Response::Pong{counter: state_lock.counter})
                    }
                }

            })
        }, state, 100000).await
    }

}

main.rs

#[tokio::main]
async fn main() -> Result<(), BoxDynError> {
    let echo = Echo::new().await;

    println!("Sent Ping");
    echo.send(Message::Ping).await?;

    println!("Sent Ping and ask response");
    let pong = echo.ask(Message::Ping).await?;
    println!("Got {:?}", pong);

    println!("Sent Ping and wait response in callback");
    echo.callback(Message::Ping, move |result| {
        Box::pin(async move {
            let response = result?;
            println!("Got {:?}", response);
            Ok(())
        })
    }).await?;

    _ = echo.stop();
    thread::sleep(std::time::Duration::from_secs(1));
    Ok(())
}

Example output:

Sent Ping
Sent Ping and ask response
Received Ping
Received Ping
Got Pong { counter: 2 }
Sent Ping and wait response in callback
Received Ping
Got Pong { counter: 3 }

Example sources: https://github.com/evgenyigumnov/actor-lib/tree/main/examples/ping_pong