Skip to main content

Crate trillium_sse

Crate trillium_sse 

Source
Expand description

§Trillium tools for server sent events

There are two ways to use this crate.

§The Sse handler

sse builds a Handler from any SseHandler, which produces a Stream of Eventable items per connected client. This is the fuller-featured of the two, because a handler is initialized by the server and so can send heartbeats.

Requests whose Accept header excludes text/event-stream are passed through to subsequent handlers untouched.

use broadcaster::BroadcastChannel;
use std::time::Duration;
use trillium::Conn;
use trillium_sse::sse;

let channel = BroadcastChannel::<String>::new();

let handler = sse(move |_: &mut Conn| channel.clone()).with_heartbeat(Duration::from_secs(15));

§SseConnExt

SseConnExt is an extension trait for trillium::Conn whose with_sse_stream chainable method takes a Stream where the Item implements Eventable. Use it when you already have a conn in hand and want to respond with an event stream.

use broadcaster::BroadcastChannel;
use trillium::{Conn, conn_unwrap};
use trillium_sse::SseConnExt;

type Channel = BroadcastChannel<String>;

fn get_sse(mut conn: Conn) -> Conn {
    let broadcaster = conn_unwrap!(conn.take_state::<Channel>(), conn);
    conn.with_sse_stream(broadcaster)
}

Often, you will want this stream to be something like a channel, but the specifics of that are dependent on the event fanout characteristics of your application.

§Events

This crate implements Eventable for an Event type that you can use in your application, for String, and for &'static str. You can also implement Eventable for any type in your application.

In addition to data events, the stream can carry comments — messages that clients ignore, sent periodically so that an idle stream is still producing traffic. See Event::new_comment, or Sse::with_heartbeat / with_sse_stream_and_heartbeat to have them sent automatically whenever the stream goes quiet.

Structs§

Event
Events are a concrete implementation of the Eventable trait.
Sse
A Handler that responds to requests with a server-sent event stream.

Traits§

Eventable
A trait that allows any Unpin + Send + Sync type to act as an event.
SseConnExt
Extension trait for server sent events
SseHandler
The trait that defines an event source for the Sse handler.

Functions§

sse
Builds a new Sse handler. Alias for Sse::new.