WebSockets
A #[tool(socket)] tool takes the events of the WebSocket connections opened on it: open, each text message, and close.
use berm_lang::{Result, socket::{self, Event}, tool};
/// Keeps a room of connections
#[tool(socket)]
pub fn room(event: Event) -> Result<()> {
let mut room: Vec<String> = berm_lang::get("room")?.unwrap_or_default();
match event {
Event::Open { connection } => room.push(connection),
Event::Message { data, .. } => {
let all: Vec<&str> = room.iter().map(String::as_str).collect();
socket::send_all(&all, &data)?;
}
Event::Close { connection, .. } => room.retain(|held| *held != connection),
}
berm_lang::set("room", &room)?;
Ok(())
}- The host holds each connection and calls the tool once per event, in order:
Open, eachMessagethe client sends, thenClose, from either end. Between events the service holds nothing. - Each event is a call by whoever opened the connection:
berm_lang::caller()reads them, and the tool's access decides who may connect. - A tool that fails on
Openrefuses the connection. A failedMessagecloses it with code1008. socket::send(connection, text)sends to one connection andsocket::send_all(&connections, text)to several.socket::close(connection, code)closes one, and the tool then takes itsClose. Any call of the service may send, to its own connections only; a connection that closed is skipped.- What a service remembers about a connection, such as the room it joined, it keeps in its own storage under the connection's ID.
- Messages are text. A binary message closes the connection with code
1003. - A socket tool takes no calls, and is never a
query. Its budget, logs and writes work as in any other tool. - A deploy that removes one, or takes
socketoff it, is a breaking change.
How a client connects, on Cloud and the local host: WebSockets.