ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

TechniquesResponsesStreaming and SSELimits and TimeoutsCORSLogging and TracingBind TargetsGraceful ShutdownHealth checks

Operating

Reference

Techniques

Streaming and SSE

Server-Sent Events and streamed response bodies, resumption, keep-alive, and ending with the drain.

A handler can answer with a stream: Server-Sent Events for a long-lived feed, or a streamed body for a large or paced download. Both are written to the client while the handler's stream is polled. The example is examples/18-http-streaming.

Server-Sent Events

Sse::new(stream) answers 200 with content-type: text/event-stream; charset=utf-8 and cache-control: no-cache. The stream's items are Event values, or Result<Event, E>.

use futures_util::stream::BoxStream;
use futures_util::StreamExt;
use ulo::ExecutionRef;
use ulo_http::{Event, LastEventId, Sse};

#[ulo_http::get("/events")]
fn events(&self, last: LastEventId, exec: ExecutionRef) -> Sse<BoxStream<'static, Event>> {
    let after = last.0.and_then(|id| id.parse().ok()).unwrap_or(0);
    Sse::new(Feed::since(self.feed.clone(), after).take_until(exec.draining()).boxed()).keep_alive(KEEP_ALIVE)
}

ExecutionRef is the handle to the running call (its cancellation and drain signals); Feed is the example's own log of numbered messages that readers wait on, and KEEP_ALIVE a Duration. An Event carries data, id, event and retry, built with a chain:

let id = EventId::new((next + 1).to_string()).expect("digits are a valid id");
Event::default().id(id).data(text)

Event::json(&value) serialises a value into data and returns an error for a value that does not serialise. Event::comment(text) writes a comment-only frame, and a reader raises no event for it. data is split into data: lines at CR, LF and CRLF alike. EventId::new and EventName::new refuse line terminators, and the id refuses U+0000, so a bad value fails where it is built and never in the middle of a stream.

Resuming after a disconnect

A reconnecting client sends the last id it saw in Last-Event-ID. The LastEventId extractor hands the value to the handler as Option<String>. The handler decides where to resume. The example numbers messages from 1 and starts after the id the client names:

GET /events                       -> id: 1 / data: a, id: 2 / data: b, ...
GET /events, Last-Event-ID: 2     -> id: 3 / data: c, ...

tests/streaming.rs asserts that ids 1 and 2 are not sent again, and that a request with no header starts at the beginning.

Keep-alive

.keep_alive(period) writes a : keepalive comment after at least period of idleness, so a proxy does not close the stream as idle. The period is timed by the app's Timer. The guarantee is a comment after at least the period, sometimes a little later, never sooner. Choose a period comfortably below the shortest proxy idle timeout in the deployment. Duration::ZERO turns it off.

Ending with the drain

An open stream would hold the shutdown until the drain window ends. take_until(exec.draining()) ends it cleanly when the drain starts: the stream finishes with its chunked terminator and no error event, and the shutdown report counts nothing abandoned. See Graceful Shutdown.

Sse::end_event(name) writes a final event named name with empty data when the stream returns None. SSE has no end marker, so a client cannot tell a clean end from a cut-off without one. It is off by default.

Errors in the middle of a stream

The status is sent before the first item is polled, so an Err item cannot change it. It goes to the error handlers, which may reshape it or end the stream. An error that is written reaches the client as an event named error with {"kind", "message", "details"} as its data, and the stream ends.

A streamed body

Body::stream(stream) takes a stream of Result<Bytes, E>. The body is written in chunked encoding on HTTP/1.1 and as data frames on HTTP/2, with no content-length.

use std::convert::Infallible;

use futures_util::stream;
use ulo_http::{Body, Bytes};

#[ulo_http::get("/export")]
fn export(&self) -> Body {
    let pace = self.pace.clone();
    Body::stream(stream::unfold(0, move |row| {
        let pace = pace.clone();
        async move {
            if row == 3 {
                return None;
            }
            if row > 0 {
                pace.0.acquire().await.ok()?.forget();
            }
            Some((Ok::<_, Infallible>(Bytes::from(format!("row {}\n\n", row + 1))), row + 1))
        }
    }))
}

The example paces rows with a semaphore so a test can read each frame as it is written: row 2 is written only after row 1 has been read and the pace allows it.

Disconnects

When the client closes the connection or resets the stream before the response's head is written or before the body ends, the execution (the call's unit of work, see Scopes) is cancelled with reason Disconnected. A handler watching exec.cancelled() stops its work, and a stream is dropped at the next poll. On actix, poem and rocket a disconnect before the head is written is observed only once the host drops the response body.

Streams that borrow the controller

A reply outlives the handler call. The handler attribute appends use<> to each opaque return type so the stream does not capture &self. A stream that needs the controller takes self: Arc<Self> as the receiver:

async fn watch(self: Arc<Self>, ..) -> Sse<impl Stream<Item = Event>>

Responses

What an HTTP handler may return, and what each value becomes on the wire.

Limits and Timeouts

Body limits, route timeouts, in-flight limits and the other HTTP server settings.

On this page

Server-Sent EventsResuming after a disconnectKeep-aliveEnding with the drainErrors in the middle of a streamA streamed bodyDisconnectsStreams that borrow the controller