Below is a Rust implementation that mimics an Erlang/OTP-style runtime using Tokio for async operations, Wasmer for executing WebAssembly (WASM) modules, and Cap'n Proto over QUIC for distributed node communication. This runtime allows spawning WASM functions as actors, each with an inbox for message passing. Actors can communicate locally or across nodes, with messages serialized using Cap'n Proto and transported over QUIC using the Quinn library.
Key Features:
- Actor Model: Actors are lightweight, concurrent entities represented as Tokio tasks. Each actor has an inbox (a message queue) and can process messages by calling a WASM-exported function (e.g.,
handle_message).
- WASM Integration: WASM modules are loaded and instantiated with Wasmer. A host function
send_message is imported into the WASM module to allow actors to send messages to other actors.
- Distributed Communication: Nodes communicate over QUIC (using Quinn). Messages are serialized with Cap'n Proto. Actor references include node addresses for routing.
- Message Handling: Messages are payloads (bytes) that can be sent to local or remote actors. The system uses a registry to route messages locally and QUIC for remote sends.
- Serialization and Framing: Cap'n Proto is used for serializing network messages, with a length-prefix for framing over QUIC streams.
- Error Handling: Basic error handling is included (e.g., for missing actors or network errors). In a production system, you'd add more robust fault tolerance (e.g., supervision trees).
Dependencies
Add the following to your Cargo.toml:
[dependencies]
tokio = { version = "1", features = ["full", "sync", "rt-multi-thread"] }
wasmer = "2.3"
wasmer-compiler-cranelift = "2.3" # For the Cranelift compiler
quinn = "0.8"
rustls = "0.20" # Required for Quinn's TLS
rcgen = "0.9" # For self-signed certificates in Quinn
capnp = "0.14.5"
capnpc = "0.14.5" # For code generation
uuid = { version = "0.8", features = ["v4"] }
crossbeam-channel = "0.5"
anyhow = "1.0" # For error handling
Cap'n Proto Schema
Create a file named message.capnp:
@0xb6e3a7d8f2e3b4c5;
struct NetworkMessage {
targetActorId @0 :Text; # Actor ID as a string (e.g., UUID)
payload @1 :Data; # Message payload as bytes
}
Generate Rust code for the schema using Cap'n Proto:
- Run
capnp compile -orust message.capnp to generate message_capnp.rs.
- Include the generated file in your code.
Rust Code
The code is organized into a OtpRuntime struct that manages the actor system, including spawning actors, handling local and remote communication, and setting up the QUIC endpoint.
use anyhow::{Context, Result};
use capnp::serialize_packed; // For serializing Cap'n Proto messages
use crossbeam_channel::{bounded, Sender as CrossbeamSender, Receiver as CrossbeamReceiver};
use quinn::{Endpoint, VarInt, RecvStream, SendStream};
use rustls::Certificate;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::sync::{mpsc, Mutex as TokioMutex};
use wasmer::{Store, Module, Instance as WasmerInstance, Value, Function, Imports, Exportable, Memory};
use wasmer_compiler_cranelift::Cranelift; // Use Cranelift compiler for Wasmer
use wasmer::sys::Engine; // For Universal engine
use uuid::Uuid;
// Generated Cap'n Proto code (from message.capnp)
mod message_capnp {
include!(concat!(env!("OUT_DIR"), "/message_capnp.rs"));
}
type ActorId = Uuid; // Unique ID for each actor
type Payload = Vec<u8>; // Message payload as bytes
type ActorRegistry = HashMap<ActorId, mpsc::Sender<Payload>>; // Map of actor ID to inbox sender
// Actor reference for sending messages
#[derive(Clone)]
struct ActorRef {
node_addr: String, // Node address, e.g., "127.0.0.1:5000"
actor_id: ActorId, // Actor ID
}
impl ActorRef {
fn to_string(&self) -> String {
format!("{}:{}", self.node_addr, self.actor_id)
}
}
// Runtime struct mimicking Erlang/OTP
struct OtpRuntime {
local_node_addr: String, // Local node address for QUIC
registry: Arc<TokioMutex<ActorRegistry>>, // Shared registry of local actors
quic_endpoint: Endpoint, // QUIC endpoint for listening and connecting
}
impl OtpRuntime {
// Create a new runtime, setting up QUIC endpoint
async fn new(local_addr: SocketAddr) -> Result<Arc<Self>> {
// Set up QUIC server with self-signed certificate (for simplicity)
let cert = rcgen::generate_simple_self_signed(vec!["localhost".into()]).unwrap();
let cert_der = cert.serialize_der().unwrap();
let priv_key = cert.serialize_private_key_der();
let priv_key = rustls::PrivateKey(priv_key);
let cert_chain = vec![rustls::Certificate(cert_der.clone())];
let server_config = quinn::ServerConfig::with_single_cert(cert_chain, priv_key).unwrap();
let endpoint = Endpoint::server(server_config, local_addr).context("Failed to create QUIC server endpoint")?;
let runtime = Arc::new(Self {
local_node_addr: local_addr.to_string(),
registry: Arc::new(TokioMutex::new(HashMap::new())),
quic_endpoint: endpoint,
});
// Spawn QUIC server task to handle incoming connections
let runtime_clone = runtime.clone();
tokio::spawn(async move {
while let Some(conn) = runtime_clone.quic_endpoint.accept().await {
let runtime_clone2 = runtime_clone.clone();
tokio::spawn(handle_quic_connection(conn, runtime_clone2));
}
});
Ok(runtime)
}
// Spawn a WASM actor with an inbox and send capabilities
async fn spawn_actor(&self, wasm_bytes: &[u8]) -> Result<ActorRef> {
let actor_id = Uuid::new_v4();
let (inbox_sender, inbox_receiver) = mpsc::channel(100); // Async channel for inbox
let (send_req_tx, send_req_rx) = bounded(100); // Sync channel for send requests (using crossbeam)
// Create Wasmer store and module with Universal engine for Send compatibility
let engine = wasmer::Universal::new(Cranelift::default()).engine();
let store = Store::new(&engine);
let module = Module::new(&store, wasm_bytes).context("Failed to compile WASM module")?;
// Define WASM imports, including host function for sending messages
let import_object = Imports::new();
let send_req_tx_clone = send_req_tx.clone();
let runtime_clone = self.clone_inner(); // Clone the runtime for the host function
let send_message_fn = Function::new_typed_with_env(&store, &runtime_clone, move |env: &OtpRuntime, caller, target_ptr: i32, target_len: i32, payload_ptr: i32, payload_len: i32| {
// Read data from WASM memory (assume "memory" export exists)
let memory = caller.get_export("memory").and_then(|e| e.into_memory()).unwrap();
let memory_view = memory.view(&caller);
// Read target bytes
let target_slice = memory_view.read(target_ptr as usize, target_len as usize).unwrap();
let target_bytes = target_slice.to_vec();
// Read payload bytes
let payload_slice = memory_view.read(payload_ptr as usize, payload_len as usize).unwrap();
let payload_bytes = payload_slice.to_vec();
// Enqueue send request (sync operation)
send_req_tx_clone.send((target_bytes, payload_bytes)).unwrap(); // Ignore errors for simplicity
Ok(vec![]) // Return empty result (void function)
});
let mut import_object = import_object.namespace("env").insert("send_message", send_message_fn).into_import_object(&store);
// Instantiate WASM module
let instance = WasmerInstance::new(&module, &import_object).context("Failed to instantiate WASM module")?;
// Insert actor into registry
{
let mut registry = self.registry.lock().await;
registry.insert(actor_id, inbox_sender.clone());
}
// Spawn task to handle send requests asynchronously
let runtime_clone = self.clone_inner();
tokio::spawn(handle_send_requests(send_req_rx, runtime_clone, actor_id)); // Pass actor ID if needed for logging
// Spawn the actor task to process inbox messages
let instance_clone = instance.clone(); // Clone instance if possible, or use Arc
let store_clone = store.clone(); // Clone store if Send
tokio::spawn(async move {
while let Some(payload) = inbox_receiver.recv().await {
// Write payload to WASM memory at offset 0 (simple approach, assume memory is large enough)
let memory = instance_clone.exports.get_memory("memory").unwrap().clone();
let mut data = unsafe { memory.data_unchecked_mut(&store_clone) };
data[0..payload.len()].copy_from_slice(&payload);
// Call WASM handle_message function with length
let handle_message = instance_clone.exports.get_function("handle_message").unwrap();
handle_message.call(&store_clone, &[Value::I32(payload.len() as i32)]).unwrap(); // Ignore errors for simplicity
}
});
// Return ActorRef for the new actor
Ok(ActorRef {
node_addr: self.local_node_addr.clone(),
actor_id,
})
}
// Clone the runtime for use in closures (wrap in Arc if not already)
fn clone_inner(&self) -> Arc<Self> {
Arc::new(self.clone()) // Assuming OtpRuntime is Clone or use Arc internally
}
}
// Handle QUIC connections for incoming messages
async fn handle_quic_connection(conn: quinn::Connecting, runtime: Arc<OtpRuntime>) {
match conn.await {
Ok(conn) => {
while let Ok((send, recv)) = conn.accept_bi().await {
let runtime_clone = runtime.clone();
tokio::spawn(handle_quic_stream(send, recv, runtime_clone));
}
}
Err(e) => eprintln!("QUIC connection error: {}", e),
}
}
// Handle a single QUIC bidirectional stream
async fn handle_quic_stream(mut send: SendStream, mut recv: RecvStream, runtime: Arc<OtpRuntime>) {
// Read length-prefixed Cap'n Proto message
let len_bytes = recv.read_exact(&mut [0u8; 4]).await.unwrap(); // Read u32 length
let len = u32::from_be_bytes(len_bytes.try_into().unwrap()) as usize;
let mut msg_bytes = vec![0u8; len];
recv.read_exact(&mut msg_bytes).await.unwrap();
// Deserialize Cap'n Proto message
let message_reader = capnp::serialize_packed::read_message(&mut std::io::Cursor::new(msg_bytes), ::capnp::message::ReaderOptions::new()).unwrap();
let network_msg: message_capnp::network_message::Reader = message_reader.get_root().unwrap();
let target_actor_id_str = network_msg.get_target_actor_id()?.to_string().unwrap();
let payload = network_msg.get_payload()?.to_vec();
// Parse actor ID (assume UUID string)
let actor_id = Uuid::parse_str(&target_actor_id_str).unwrap(); // Handle parsing errors in production
// Look up actor in registry and send payload
let registry = runtime.registry.lock().await;
if let Some(sender) = registry.get(&actor_id) {
sender.send(payload).await.unwrap(); // Ignore errors for simplicity
} else {
eprintln!("Actor not found: {}", actor_id);
}
}
// Handle send requests from WASM host function
async fn handle_send_requests(rx: CrossbeamReceiver<(Vec<u8>, Vec<u8>)>, runtime: Arc<OtpRuntime>, actor_id: ActorId) {
while let Ok((target_bytes, payload_bytes)) = rx.recv() { // Blocking recv in sync context
let target_str = String::from_utf8(target_bytes).unwrap(); // Assume UTF-8 string
let parts: Vec<&str> = target_str.split(':').collect();
if parts.len() != 2 {
eprintln!("Invalid target string: {}", target_str);
continue;
}
let node = parts[0].to_string();
let actor_id_str = parts[1];
let actor_id = Uuid::parse_str(actor_id_str).unwrap(); // Handle errors
if node == runtime.local_node_addr {
// Local actor, send directly
let registry = runtime.registry.lock().await;
if let Some(sender) = registry.get(&actor_id) {
sender.send(payload_bytes.clone()).await.ok();
}
} else {
// Remote actor, send over QUIC with Cap'n Proto
send_remote(&runtime, &node, &actor_id, &payload_bytes).await;
}
}
}
// Send a message to a remote node over QUIC
async fn send_remote(runtime: &OtpRuntime, node_addr: &str, actor_id: &ActorId, payload: &[u8]) {
// Parse node address to SocketAddr
let addr: SocketAddr = node_addr.parse().unwrap(); // Handle parsing errors
// Connect to remote QUIC endpoint (assume self-signed cert for simplicity)
let client_cert = Certificate(runtime.quic_endpoint.certificate().unwrap().0.clone()); // Use server's cert or proper CA
let mut client_config = quinn::ClientConfig::new(Arc::new(rustls::ClientConfig::builder()
.with_safe_defaults()
.with_root_certificates(root_cert_store) // Add root cert if needed
.with_no_client_auth()));
let endpoint = Endpoint::client(addr).unwrap(); // Create client endpoint
match endpoint.connect(addr, "localhost").await { // Use domain from cert
Ok(new_conn) => {
match new_conn.connection.open_bi().await {
Ok((mut send, mut recv)) => {
// Create Cap'n Proto message
let mut message = capnp::message::Builder::new_default();
{
let mut net_msg = message.init_root::<message_capnp::network_message::Builder>();
net_msg.set_target_actor_id(&actor_id.to_string());
net_msg.set_payload(payload);
}
// Serialize with length prefix
let mut buf = Vec::new();
let len = serialize_packed::write_message(&mut buf, &message).unwrap() as u32; // Get serialized size
let len_bytes = len.to_be_bytes();
send.write_all(&len_bytes).await.unwrap();
send.write_all(&buf).await.unwrap();
send.finish().await.unwrap();
}
Err(e) => eprintln!("Failed to open QUIC stream: {}", e),
}
}
Err(e) => eprintln!("QUIC connection failed: {}", e),
}
}
// Example main function to demonstrate usage
#[tokio::main]
async fn main() -> Result<()> {
let runtime = OtpRuntime::new("127.0.0.1:5000".parse().unwrap()).await.unwrap();
// Load a WASM module (example: a simple module with handle_message and using send_message)
let wasm_bytes = include_bytes!("path/to/wasm/module.wasm"); // Replace with actual WASM bytes
let actor_ref = runtime.spawn_actor(wasm_bytes).await.unwrap();
// Send a message to the actor (locally or remotely)
// For remote, create an ActorRef with remote node address
let remote_actor_ref = ActorRef { node_addr: "127.0.0.1:5001".to_string(), actor_id: actor_ref.actor_id }; // Example remote ref
// To send a message, you need a way to call send; add a method to ActorRef or use runtime
Ok(())
}
Explanation of Components:
- WASM Actor Spawning: The
spawn_actor method loads a WASM module, instantiates it with a host function send_message, and spawns two tasks: one for processing inbox messages and another for handling send requests from WASM.
- Host Function
send_message: Imported into WASM, it allows actors to send messages. It enqueues requests using a crossbeam channel, which are processed asynchronously.
- Message Routing: Local messages are sent directly via Tokio mpsc channels. Remote messages are serialized with Cap'n Proto and sent over QUIC.
- QUIC Server and Client: The QUIC endpoint listens for incoming connections and handles streams. For sending, a new connection is made for each remote send (in a real system, use connection pooling).
- Serialization: Cap'n Proto is used for network messages with a length-prefix for framing. Locally, messages are sent as bytes for simplicity.
- Limitations and Improvements:
- WASM Memory Handling: Writing to memory at offset 0 is simplistic and may cause issues; consider adding WASM exports for memory management.
- Error Handling: Basic; add more robust handling for WASM calls, network errors, and actor failures.
- Actor References: Currently, ActorRef is manual; add a method to send messages directly from ActorRef.
- Distributed Discovery: Nodes don't discover each other; assume addresses are known. Add a discovery mechanism in a full implementation.
- Performance: Crossbeam channels bridge sync and async; optimize if needed. Wasmer calls are synchronous, so keep WASM functions fast.
- Security: Uses self-signed certificates; use proper TLS in production.
This implementation provides a foundation for an Erlang/OTP-like runtime in Rust. For a complete system, add supervision, monitoring, and more advanced features.