Crate vin

Source
Expand description

§vin

A lightweight, ergonomic and unconventional actor crate.

§Overview

Vin’s goal is to be an ergonomic, unconventional actor library. Vin doesn’t follow the conventional implementations for actor libraries, but tries to be as simple as possible, while still providing an ergonomic and rich interface by integrating itself with tokio as much as possible. Each actor gets its own task to poll messages and execute handlers on. Its address is shared by a simple Arc. Vin also provides a way to gracefully shutdown all actors without having to do the manual labour yourself. Actor data is stored in its actor context and is retrievable for reading with Actor::ctx() and for writing with Actor::ctx_mut() which acquire a RwLock to the data. Vin also provides a “task actor” which is simply a tokio task spun up and synchronized with Vin’s shutdown system.

Vin completely relies on tokio (for the async runtime), log (for diagnostics) and async_trait.

§Examples

§Regular actors

Basic usage of [vin].

use vin::prelude::*;
use std::time::Duration;
use tracing::Level;
 
#[vin::message]
#[derive(Debug, Clone)]
pub enum Msg {
    Foo,
    Bar,
    Baz,
}
 
#[vin::message(result = u32, error = String)]
struct MsgWithResult(bool);
 
#[vin::actor]
#[vin::handles(Msg)]
#[vin::handles(MsgWithResult)]
struct MyActor {
    pub number: u32,
}
 
#[async_trait]
impl vin::Hooks for MyActor {}
 
#[async_trait]
impl vin::Handler<Msg> for MyActor {
    async fn handle(&self, msg: Msg) -> Result<(), ()> {
        let ctx = self.ctx().await;
        println!("The message is: {:?} and the number is {}", msg, ctx.number);
 
        Ok(())
    }
}
 
#[async_trait]
impl vin::Handler<MsgWithResult> for MyActor {
    async fn handle(&self, MsgWithResult(should_err): MsgWithResult) -> Result<u32, String> {
		if should_err { Err("error".to_string()) }
        else { Ok(42) }
    }
}
 
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(Level::TRACE)
        .init();
 
    let ctx = VinContextMyActor { number: 42 };
    let actor = MyActor::start("test", ctx).unwrap();
    actor.send(Msg::Bar).await;
    tokio::time::sleep(Duration::from_millis(500)).await;
	let res = actor.send_and_wait(MsgWithResult(false)).await.unwrap();
	assert_eq!(res, 42);
    vin::shutdown();
    vin::wait_for_shutdowns().await;
}

§Task actors

Basic usage of task actors in [vin].

use vin::*;
use std::time::Duration;
use tracing::Level;
 
#[vin::task]
#[derive(Debug, Clone, PartialEq, Eq)]
struct MyTaskActor {
    pub number: u32,
}
#[async_trait]
impl vin::Task for MyTaskActor {
    async fn task(&self, ctx: Self::Context) -> anyhow::Result<()> {
        for i in 0..ctx.number {
            log::info!("{}. iteration", i);
        }
 
        Ok(())
    }
}
 
#[tokio::main]
async fn main() {
    tracing_subscriber::fmt()
        .with_max_level(Level::TRACE)
        .init();
 
	let ctx = VinContextMyTaskActor { number: 5 };
    let actor = MyTaskActor::start("test_task", ctx);
    tokio::time::sleep(Duration::from_millis(100)).await;
	actor.close();
    vin::shutdown();
    vin::wait_for_shutdowns().await;
}

Re-exports§

pub use vin_core;

Structs§

ActorStartError
Error returned by start().

Enums§

ActorQueryError
Error returned by the actor query functions.
State
Actor lifecycle states.

Traits§

Actor
Actor trait that all generic (non-specialized) actors must implement.
Addr
A restricted interface of Actor that provides send mechanics and state reads.
Forwarder
Forwards the message to the respective mailbox.
Handler
Handler for specifying message handling logic.
Hooks
Used to call arbitrary code on state changes.
Message
Trait indicating that the type is a message.
Task
Used to call arbitrary code on a task actor.
TaskActor
Actor trait that all generic (non-specialized) actors must implement.
TaskAddr
A restricted interface of TaskActor that provides closing and state reads.

Functions§

add_actor
Registers an actor in the actor counter.
query_actor
Queries a typed actor from the registry.
query_actor_erased
Queries an erased actor from the registry.
remove_actor
Unregisters an actor in the actor counter.
send
Sends a typed message to an actor with the corresponding id.
send_and_wait
Sends a typed message to an actor with the corresponding id.
shutdown
Sends a shutdown signal to all actors.
shutdown_future
Registers a shutdown future.
wait_for_shutdowns
Waits for all actors to shutdown gracefully.

Type Aliases§

ActorId
Actor id type for the actor registry.
StrongAddr
A strong typed reference to the spawned actor.
StrongErasedAddr
A strong erased reference to the spawned actor.
WeakAddr
A weak typed reference to the spawned actor.
WeakErasedAddr
A weak erased reference to the spawned actor.

Attribute Macros§

actor
Generates the actor impls and forms necessary fields.
handles
A noop macro attribute used to specify messages to handle. Check [actor] for more information.
message
Implements the [Message] trait for a type. Enables specifying the result type easily.
task
Generates a [vin]-managed [tokio] task. It’s a specialized actor with no handler that runs some piece of code until it’s completed or [vin] has shutdown.