Files
urus/src/sse.rs
T
Claude (sandbox) 4f06265338 feat(serve): split request read budget into head_timeout + body_timeout
The single request_timeout covered head + body under one wall clock, so a
slow-but-legit body upload (e.g. a trickling cellular IoT client) was
judged by the short head deadline and killed mid-body. Split into:

- head_timeout (default 30s): first byte -> full head parse; the classic
  slowloris surface, kept short.
- body_timeout (default 300s): head parse -> full body; an absolute cap
  sized for slow links, anchored independently once the head has parsed.

read_head no longer returns a shared deadline; run_connection anchors the
body deadline itself. ReadHeadErr::RequestTimeout -> HeadTimeout. Config
and ConnLimits gain body_timeout; request_timeout renamed to head_timeout
(breaking, but this axis is unreleased).

Tests: slow_body_outlives_head_timeout (positive: body survives past the
head clock), fixed_/chunked_body_stall_killed_at_body_timeout (body cap
still bites), slowloris_partial_head_killed_at_head_timeout (head clock
unchanged). 79 lib + 43 integration green; clippy --lib clean.
2026-08-12 13:00:22 +00:00

180 lines
6.1 KiB
Rust

//! Server-Sent Events sugar over `RespBody::Stream`.
//!
//! An SSE response is just a streaming body with the right headers and a
//! heartbeat: `Conn::sse()` wires all of it and hands back an
//! [`EventSender`] for a producer actor to feed.
//!
//! ```no_run
//! use urus::{Conn, Next, Pipeline, Router};
//! use std::time::Duration;
//!
//! let pipeline = Pipeline::new().plug(Router::new().get(
//! "/events",
//! |c: Conn, _n: Next| {
//! let (c, events) = c.sse();
//! smarm::spawn(move || {
//! let mut i = 0;
//! loop {
//! if events.send("tick", &i.to_string()).is_err() {
//! return; // client gone; conn actor dropped the stream
//! }
//! i += 1;
//! smarm::sleep(Duration::from_secs(1));
//! }
//! });
//! c
//! },
//! ));
//! ```
//!
//! Liveness: the connection actor emits a `: keep-alive` comment chunk
//! whenever [`HEARTBEAT_INTERVAL`] passes with no event (see
//! `StreamBody::heartbeat`). A client that went away is detected when a
//! write — event or heartbeat — stalls past `write_timeout`; the conn
//! actor then drops the stream and the producer's next [`EventSender`]
//! call returns `Err(SseClosed)`. There is no request clock on an SSE
//! response: the head/body read budgets cover only the read phase, by
//! design.
use crate::conn::{Conn, RespBody, StreamBody};
use std::time::Duration;
/// Default heartbeat: one comment line per this interval of silence.
pub const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(15);
/// What the heartbeat puts on the wire — an SSE comment, invisible to
/// `EventSource` consumers.
pub(crate) const HEARTBEAT_PAYLOAD: &[u8] = b": keep-alive\n\n";
/// The stream has ended: the connection actor dropped the receiving end
/// (client disconnect, write timeout, or server shutdown). Producers
/// should exit when they see this.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SseClosed;
impl std::fmt::Display for SseClosed {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("SSE stream closed")
}
}
impl std::error::Error for SseClosed {}
/// Producer handle for an SSE response. Clonable — multiple producers may
/// feed one stream; the stream ends when the LAST clone drops.
#[derive(Clone)]
pub struct EventSender {
tx: smarm::Sender<Vec<u8>>,
}
impl EventSender {
/// Send a named event: `event: {event}` + `data:` line(s).
pub fn send(&self, event: &str, data: &str) -> Result<(), SseClosed> {
self.tx
.send(format_event(Some(event), data))
.map_err(|_| SseClosed)
}
/// Send an unnamed event (`data:` line(s) only) — what `EventSource`
/// surfaces as a plain `message`.
pub fn data(&self, data: &str) -> Result<(), SseClosed> {
self.tx
.send(format_event(None, data))
.map_err(|_| SseClosed)
}
/// Send a comment line. Invisible to `EventSource`; useful for
/// application-level pings beyond the built-in heartbeat.
pub fn comment(&self, text: &str) -> Result<(), SseClosed> {
let mut out = Vec::with_capacity(text.len() + 4);
out.extend_from_slice(b": ");
out.extend_from_slice(text.as_bytes());
out.extend_from_slice(b"\n\n");
self.tx.send(out).map_err(|_| SseClosed)
}
}
/// Wire format for one event. Multi-line `data` becomes one `data:` line
/// per line (the SSE framing for embedded newlines); the blank line
/// dispatches the event.
pub(crate) fn format_event(event: Option<&str>, data: &str) -> Vec<u8> {
let mut out = Vec::with_capacity(data.len() + 32);
if let Some(e) = event {
out.extend_from_slice(b"event: ");
out.extend_from_slice(e.as_bytes());
out.push(b'\n');
}
for line in data.split('\n') {
out.extend_from_slice(b"data: ");
out.extend_from_slice(line.as_bytes());
out.push(b'\n');
}
out.push(b'\n');
out
}
impl Conn {
/// Turn this response into a Server-Sent Events stream with the
/// default [`HEARTBEAT_INTERVAL`]. Returns the `Conn` (return it from
/// the handler) and the [`EventSender`] to hand to a producer actor.
pub fn sse(self) -> (Self, EventSender) {
self.sse_with_heartbeat(HEARTBEAT_INTERVAL)
}
/// [`Conn::sse`] with a custom heartbeat interval.
pub fn sse_with_heartbeat(mut self, interval: Duration) -> (Self, EventSender) {
let (tx, rx) = smarm::channel::<Vec<u8>>();
if self.status.is_none() {
self.status = Some(200);
}
self.resp_headers.set("content-type", "text/event-stream");
self.resp_headers.set("cache-control", "no-cache");
self.resp_body = RespBody::Stream(
StreamBody::new(rx).with_heartbeat(interval, HEARTBEAT_PAYLOAD.to_vec()),
);
(self, EventSender { tx })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn format_named_event() {
assert_eq!(
format_event(Some("tick"), "42"),
b"event: tick\ndata: 42\n\n".to_vec()
);
}
#[test]
fn format_unnamed_event() {
assert_eq!(format_event(None, "hi"), b"data: hi\n\n".to_vec());
}
#[test]
fn format_multiline_data() {
assert_eq!(
format_event(None, "a\nb"),
b"data: a\ndata: b\n\n".to_vec()
);
}
#[test]
fn sse_sets_headers_and_stream_body() {
let (conn, _events) = Conn::new().sse();
assert_eq!(conn.status, Some(200));
assert_eq!(conn.resp_headers.get("content-type"), Some("text/event-stream"));
assert_eq!(conn.resp_headers.get("cache-control"), Some("no-cache"));
match &conn.resp_body {
RespBody::Stream(s) => {
let (interval, payload) = s.heartbeat.as_ref().expect("heartbeat set");
assert_eq!(*interval, HEARTBEAT_INTERVAL);
assert_eq!(payload.as_slice(), HEARTBEAT_PAYLOAD);
}
other => panic!("expected Stream body, got {other:?}"),
}
}
}