2 个版本

0.1.1 2021年3月21日
0.1.0 2021年3月20日

#1169 in 并发

Apache-2.0/MIT

9KB
71

Wactor

基于 lunatic 的 WASM Actor 系统。

Actor 在隔离的绿色线程上运行。它们不能共享内存,只能通过输入和输出消息进行通信。因此,消息必须在线程之间进行序列化。

示例

use serde::{Deserialize, Serialize};
use wactor::*;

struct Counter {
    count: u32,
}

#[derive(Serialize, Deserialize)]
enum Input {
    AddOne,
}

#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum Output {
    Count(u32),
}

impl Actor for Counter {
    type Input = Input;
    type Output = Output;

    fn create() -> Self {
        Self { count: 0 }
    }

    fn handle(&mut self, msg: Self::Input, link: &Link<Self>) {
        match msg {
            Input::AddOne => {
                // Increment count by 1.
                self.count += 1;
                // Respond with new count. This fails if our recipient has been dropped.
                link.respond(Output::Count(self.count)).ok();
            }
        }
    }
}

fn main() {
    // Spawn our actor. We get a bridge for sending and receiving messages. Can be cloned for
    // multiple owners. Actor is dropped after all bridges have been dropped.
    let bridge = wactor::spawn::<Counter>();
    // Send our input message. This fails if our actor has panicked (unrecoverable error).
    bridge.send(Input::AddOne).expect("Dead actor");
    // Block until a response is received. This also fails if our actor has panicked.
    let result = bridge.receive();
    // Assert we received the correct value.
    assert_eq!(result, Ok(Output::Count(1)));
}

如何运行

安装 lunatic,然后构建和运行

cargo build --release --target=wasm32-wasi --example basic
lunatic target/wasm32-wasi/release/examples/basic.wasm

依赖项

~1–1.7MB
~36K SLoC