Skip to main content

Crate wse

Crate wse 

Source
Expand description

§wse

A WebSocket engine for reactive user interfaces, run inside your Rust application: topics with recovery for clients that come back, presence, servers that form a cluster without a broker, JWT validation, end-to-end encryption and signed messages, delivered on every CPU core. The same engine runs the Python package wse-server; the clients are wse-client for Rust, wse-client for TypeScript and React, and wse-client for Python.

[dependencies]
wse = "3"
serde_json = "1"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal"] }

§A server

A server is a Config, a Handler (what the application hears of its clients) and a Publisher (what it sends them). It runs on the application’s own tokio runtime.

use wse::{Config, Connect, Handler, Inbound, JwtSettings, Server, Subscribe};

/// Every connection joins its user's topic.
struct App;

impl Handler for App {
    type Connection = String;

    fn connect(&self, connect: &Connect<'_>) -> Option<String> {
        let user = connect.user_id?.to_owned();
        connect.subscribe(vec![format!("user:{user}")], &Subscribe::default()).ok()?;
        Some(user)
    }

    fn message(&self, user: &mut String, message: Inbound, _size: usize) -> bool {
        if let Inbound::Json(message) = message {
            println!("{user}: {message}");
        }
        true
    }

    fn signed(&self, _user: &mut String, _message: serde_json::Value, _size: usize) -> bool {
        false
    }

    fn disconnect(&self, _user: String) {}
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut config = Config::default();
    config.jwt = Some(JwtSettings::new(std::env::var("JWT_SECRET")?));
    let server = Server::new(config)?;
    server.start(tokio::net::TcpListener::bind("0.0.0.0:5006").await?, App)?;

    let publisher = server.publisher();
    publisher.publish("user:42", r#"{"t":"order_filled","p":{"id":7}}"#)?;
    publisher.send_to_user("42", r#"{"t":"notice","p":{"text":"hello"}}"#)?;

    tokio::signal::ctrl_c().await?;
    server.stop().await;
    Ok(())
}

examples/chat.rs is a complete chat room; it prints a token to try it with, and the wse-client crate’s chat_client example talks to it.

§What a server does

  • Fan-out on every core. Each connection belongs to a delivery lane, one per core; a broadcast to 10,000 connections is delivered by every core at once. A publisher faster than its clients waits for room (Publisher::ready) instead of filling memory: past 65,536 queued sends, a send fails with Error::Full.
  • Topics. Exact names and glob patterns, queue groups (one member of a group gets each message), per-connection ACLs, from the JWT wse_topics claim or set by the application.
  • Recovery. Topics keep their last messages; a client that comes back with its position gets what it missed, or learns that it must reload.
  • Presence. Who is on a topic, with their data, across the cluster.
  • Users. send_to_user reaches every tab and device of a user, disconnect_user closes them all.
  • Cluster. Nodes link over a binary protocol in TLS, from the cluster’s secret (ClusterSettings::secret) or from certificates, and forward each topic only where it has subscribers. With recovery on, a link that drops and comes back loses nothing: each node gets what it missed from the other, in order, before anything new.
  • Security. JWT validation in the handshake (HS*, RS*, PS*, ES*, EdDSA, key rotation), origin checks, rate limits, end-to-end encryption with the server’s identity key, signed messages both ways. A token that names the client’s key (cnf) opens a session only for the client that proves the key (Config::bind_sessions; Publisher::accept_bound when the application authenticates connections itself).
  • Operations. Graceful drain, health snapshots and Prometheus metrics.

§Features

  • server (default): the server. Without it the crate is its protocol module alone: the crypto, end-to-end sessions and signed messages that the server and wse-client share, which is how the client depends on it, in the browser too.
  • fips: aws-lc-rs built from its FIPS 140-3 validated module (needs CMake and Go). The crypto is aws-lc-rs otherwise, for TLS, JWT, end-to-end encryption and signing.

The protocol, the close codes and the cluster wire format are documented in the repository.

§License

MIT

Modules§

protocol
The pieces of the protocol that the server and the Rust client (wse-client) share: the crypto, end-to-end sessions and signed messages, one implementation for both sides. On aws-lc-rs; in the browser, and with RUSTFLAGS="--cfg wse_rustcrypto", on RustCrypto.

Structs§

ClusterPeer
A peer this node is linked to.
ClusterSettings
How a server joins its cluster. Its links are TLS, always: from the cluster’s secret, or from certificate files (tls).
ClusterTls
The PEM files of a cluster’s mutual TLS, by their paths: this node’s certificate and key, and the CA every node’s certificate is checked against.
Config
What a server is configured with. Start from Config::default() and set the fields that differ: the defaults are those of the Python server. Its Debug print shows whether a key is set, never the key.
ConfigError
A configuration that cannot run, and why.
Connect
A connection, as the application first hears of it. It may subscribe the connection right away (subscribe, set_topic_acl).
DeadLetter
A message a peer did not take, kept for a retry.
Health
A snapshot of a server’s state.
JwtKeys
New keys for the tokens a server validates (key rotation). Its Debug print leaves the keys out.
JwtSettings
Tokens the server validates itself, from the cookie or the Authorization header. Its Debug print leaves the keys out.
Member
A user present on a topic.
PresenceSettings
Who is on a topic, for presence.
Publisher
What the application reaches its server with: send, publish, subscribe, close. Cheap to clone; every clone reaches the same server, across restarts. While the server is stopped, sends fail with Error::Stopped.
Recovered
Where a topic a connection subscribed to with recovery stands.
RecoverySettings
Each topic keeps its last messages for clients that come back.
Server
A WSE server: its configuration and state, from new until it is dropped. It serves on a listener once started, and can start again after stop. It speaks plain WebSocket (ws://): wss:// is a reverse proxy or a load balancer in front of it.
Subscribe
How a connection subscribes to its topics.

Enums§

Error
Why the server did not take a message or a request.
Inbound
A client’s message, as the server read it.
Presence
A user’s presence on a topic changed.

Traits§

Handler
What the server tells the application. Each connection’s calls come in order on the connection’s own task: connect, its messages, disconnect. They run on the runtime’s worker threads and should return fast; a handler hands long work to a task of its own.