Streams
A stream keeps its response open and sends patches as changes happen on the server, and opens again when the connection drops.
Declaring a stream
A StreamAction<S, A = ()>, declared on a stream line of routes!, runs a handler that returns a stream of patches, and is always served on GET: stream TICKS: StreamAction<Clock> = "/ticks" => ticks;. Its path follows the rules of an action's path. The handler is a plain fn(state, args) or fn(state, extractor, args) that returns an impl Stream<Item = Patches<S>> + Send + 'static, such as one futures::stream::unfold builds. Each item of the stream is one batch, sent when the stream yields it.
An async fn returns a future of the stream rather than a stream, so it is a compile error, E0277, at the routes! line that names it.
use futures::{Stream, stream};
use hypersig::{Patches, Signals, StreamAction};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Feed {
items: Vec<String>,
}
// error[E0277]: `impl Future<Output = impl Stream<Item = Patches<Feed>>>` is not a stream of `Patches<Feed>` a stream's handler returns
hypersig::routes! {
fn pages(Router<()>);
stream UPDATES: StreamAction<Feed> = "/updates" => updates;
}
async fn updates((): (), (): ()) -> impl Stream<Item = Patches<Feed>> {
stream::empty()
}Opening a stream
StreamAction::call, fn call(&self) -> StreamCall<S>, exists only on a StreamAction<S, ()>, and call_with, fn call_with(&self, args: impl IntoExpr<S, A>) -> StreamCall<S>, takes an expression the browser evaluates when the stream opens. A StreamCall<S> is a statement. Put it in on_load to open the stream when the element appears, which suits changes made elsewhere, such as by other visitors.
The stream closes once its element leaves the page, and the browser applies none of its later patches. A patch that replaces the element leaves one stream open, the one the new element's on_load opens.
What goes over the network
Opening the stream sends the GET an action call sends: accept: text/event-stream, hypersig-call: 1, and the arguments as JSON in the args query parameter. The answer is 200 with content-type: text/event-stream and x-accel-buffering: no, which stops nginx from holding the patches back in its buffer. It stays open while the handler's stream runs. Each batch arrives as soon as the stream yields it, and while none comes the server sends a comment line now and then, so a proxy does not close a quiet connection. When the handler's stream finishes, the server ends the response. The network tab shows the request of the clock below as:
GET /ticks
accept: text/event-stream
hypersig-call: 1StreamAction::request, fn request(&self, args: &A) -> Request<Body>, builds the same GET for a test.
Showing the connection
StreamCall::connected, fn connected(self, flag: Sig<S, bool>) -> Self, sets flag to true when the server answers with a 2xx status and to false when the stream ends or breaks off. It stays false while the stream connects and while reconnect waits to open it again, so a page can show whether it is receiving changes. Several streams may set one flag, which is true while any of them is open. A stream has no indicator, because its answer is never awaited to the end; calling it is E0599. error and status work as on an action's call, and also go back to "" and 0 when the stream connects.
Streams that drop
StreamCall::reconnect, fn reconnect(self) -> Self, opens a stream again when its connection fails, it breaks off, or the server answers with a 5xx status, as the clock below does. It waits longer after each failure in a row, for a random part of each wait, so pages that lost the server together do not all come back at the same moment, and it stops waiting when the browser comes back online or the page becomes visible. A stream that delivers a batch starts the waits over. A response a host closes at its time limit ends before the handler's stream finished, so it counts as broken off. reconnect does not open the stream again once the handler's stream has finished, after a 4xx answer, or once the element has left the page. While the stream is failing, the error signal holds the last failure.
Each attempt evaluates the arguments again and runs the handler with them. A stream that takes a signal its patches keep current, such as the id of the last message, can send only what came after it. A stream whose arguments stay the same should start with the current values, and the page catches up with what it missed.
use futures::{Stream, stream};
use hypersig::html::{div, each_keyed, li, p};
use hypersig::{Patches, Signals, StreamAction};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize, Clone)]
struct Message {
id: i32,
body: String,
}
#[derive(Signals, Serialize, Deserialize)]
struct Chat {
messages: Vec<Message>,
last_id: i32,
live: bool,
problem: String,
}
hypersig::routes! {
fn pages(Router<()>);
stream SINCE: StreamAction<Chat, i32> = "/messages" => since;
}
// Each batch appends what came after `last_id` and moves `last_id` past it.
fn since((): (), last_id: i32) -> impl Stream<Item = Patches<Chat>> {
let missed = stored_after(last_id);
let newest = missed.last().map_or(last_id, |message| message.id);
stream::iter([Patches::new()
.list(Chat::messages().patch_append(&missed))
.signals(Chat::last_id().patch(newest))])
}
// Each attempt to open the stream reads `last_id` again.
let open = SINCE
.call_with(Chat::last_id())
.reconnect()
.connected(Chat::live())
.error(Chat::problem());
let chat = div::<Chat>()
.on_load(open)
.child(p().show(!Chat::live()).bind_text(Chat::problem()))
.child(each_keyed(
Chat::messages(),
|message| message.at(Message::id()),
|message| li().bind_text(message.at(Message::body())),
));Only a call to a StreamAction, which is always served on GET, has reconnect, because sending a POST again could repeat a change. On an action's Call it is a compile error, E0599.
use hypersig::html::button;
use hypersig::{Action, Patches, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Counter {
count: i32,
}
hypersig::routes! {
fn pages(Router<()>);
action ADD: Action<Counter> = post "/add" => |(), ()| async { Patches::<Counter>::new() };
}
// error[E0599]: no method named `reconnect` found for struct `Call<S>` in the current scope
let add = button::<Counter>().on_click(ADD.call().reconnect());What the types leave unchecked
Nothing limits how long a stream stays open or how many visitors hold one. Each open stream is one request held by the server, and a host that ends requests after a time limit closes the stream there, as Deploying in a container measures on Cloud Run. A stream without reconnect that drops stays closed, and only connected or error shows it. A stream hears of a change another visitor made through something the application provides, such as a tokio::sync::broadcast channel in the router's state, which reaches the streams of one process only. Storing data covers an application that runs more than one process.
A complete example
This clock counts the seconds the page has been connected, sent by the server once a second. The stream below uses the futures crate and tokio's timer, so add futures to the Quick start's [dependencies] and turn on tokio's time feature:
futures = "0.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "net", "time"] }use std::time::Duration;
use axum::Router;
use futures::{Stream, stream};
use hypersig::html::{p, span};
use hypersig::{Page, Patches, Route, RouterExt, Signals, StreamAction};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Clock {
seconds: i32,
}
hypersig::routes! {
fn pages(Router<()>);
const INDEX: Route = "/" => index;
stream TICKS: StreamAction<Clock> = "/ticks" => ticks;
}
async fn index((): (), (): ()) -> Page<Clock> {
Page::new("Clock", Clock { seconds: 0 }).child(
p().on_load(TICKS.call().reconnect())
.text("Connected for ")
.child(span().bind_text(Clock::seconds().to_text()))
.text(" s"),
)
}
fn ticks((): (), (): ()) -> impl Stream<Item = Patches<Clock>> {
stream::unfold(0, |seconds| async move {
tokio::time::sleep(Duration::from_secs(1)).await;
let next = seconds + 1;
Some((Clock::seconds().patch(next).into(), next))
})
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
let app = pages(Router::new()).hypersig_runtime();
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;
axum::serve(listener, app).await
}cargo test from site/examples/ in the repository.Next, List patches sends a chat's messages one at a time, and Testing handlers tests an action and a stream without a browser.