Stateroom is a minimalist framework for building lightweight, single-threaded services that send and receive messages through WebSockets.
Services can either be native Rust code that runs in the server process, or be compiled into WebAssembly modules and loaded dynamically.
To create a Stateroom service, implement the
SimpleStateroomService trait. There's only one function that you must implement, the constructor
Let's implement a simple shared counter. Any connected client will be able to increment or decrement it by sending
decrement messages (other messages will be ignored). Whenever the value is changed, we'll broadcast it
to every connected client.
To serve this service, we will compile it into a WebAssembly module. We import the
annotation macro and apply it to the existing
use stateroom_wasm; ;
Then, install the
stateroom command-line tool and the
wasm32-wasi target, and run
stateroom dev will build your app and serve it on port
:8080. Then, open
http://localhost:8080/status in your browser -- if all went well, you should see the
ok. Open up developer tools in your browser and type:
let ws = ; ws console.log;
This connects to your service, creating a new room with the id
1 if one doesn't exist
(under default server settings, any string is a vaild room ID and connecting to a non-existant
room will create it).
Now, you can increment the counter by sending the
increment message using the
If everything is set up correctly, the result will be printed out:
new value: 1
If multiple clients are connected, each one will receive this message. Just like that, we have a mechanism for sharing some (very basic) application state between clients.
Using without WebAssembly
If you don't want to compile your service to WebAssembly (for example, if you want to use
capabilities that are
not exposed by WASI), you can use
Stateroom has a modular architecture. If all you want to do is generate a Stateroom service to
be served with an existing Stateroom WebAssembly server, the main crates you will interact with
will probably be
stateroom-cli, which provides a command-line tool, and
stateroom-wasm, the main Cargo dependency for building services.
stateroomis the core, minimal implementation of the service interface.
stateroom-cliis a command-line interface for interacting with WebAssembly-compiled Stateroom services.
stateroom-serverprovides Actix actors to facilitate serving Stateroom services in a WebSocket server.
stateroom-wasmprovides a macro for generating WebAssembly modules from Stateroom services.
stateroom-wasm-hostprovides a way to import Stateroom services from WebAssembly modules.
Aper is a state synchronization library which works with Stateroom.