sprite-core 0.1.7

Sprite Engine — a fault-tolerant actor runtime for Rust
Documentation
use sprite_core::{Engine, Message, Pool};
use std::time::Duration;

#[test]
fn test_message_roundtrip() {
    let engine = Engine::new();
    let ponger = engine.spawn("ponger", |ctx| {
        ctx.on_message(|msg| {
            if msg == "ping" {
                println!("pong!");
            }
        });
    });
    std::thread::sleep(Duration::from_millis(20));
    ponger.send(Message::text("ping"));
    std::thread::sleep(Duration::from_millis(50));
}

#[test]
fn test_stateful_counter() {
    let engine = Engine::new();
    let counter = engine.spawn("counter", |ctx| {
        let count = ctx.use_state("count", 0i64);
        ctx.on_message(move |msg| {
            if msg == "inc" {
                count.update(|c| c + 1);
            }
        });
    });
    std::thread::sleep(Duration::from_millis(20));
    for _ in 0..100 {
        counter.send(Message::text("inc"));
    }
    std::thread::sleep(Duration::from_millis(100));
}

#[test]
fn test_pool_round_robin() {
    let engine = Engine::new();
    let pool = Pool::new(&engine, "worker", 4, |ctx| {
        let name = ctx.name().to_string();
        ctx.on_message(move |msg| {
            println!("{} got {:?}", name, msg);
        });
    });
    std::thread::sleep(Duration::from_millis(20));
    for i in 0..8 {
        pool.send(Message::int(i));
    }
    std::thread::sleep(Duration::from_millis(100));
}

#[test]
fn test_panic_recovery_preserves_state() {
    let engine = Engine::new();
    let handle = engine.spawn("fragile", |ctx| {
        let data = ctx.use_state("data", "alive".to_string());
        ctx.on_message(move |msg| {
            if msg == "panic" { panic!("intentional"); }
            if msg == "check" { assert_eq!(data.get(), "alive"); }
        });
    });
    std::thread::sleep(Duration::from_millis(20));
    handle.send(Message::text("panic"));
    std::thread::sleep(Duration::from_millis(50));
    handle.send(Message::text("check"));
    std::thread::sleep(Duration::from_millis(50));
}

#[test]
fn test_named_messaging() {
    let engine = Engine::new();
    let _ = engine.spawn("logger", |ctx| {
        ctx.on_message(|msg| println!("{:?}", msg));
    });
    std::thread::sleep(Duration::from_millis(20));
    engine.send_named("logger", Message::text("hi"));
    std::thread::sleep(Duration::from_millis(50));
}