Skip to content

Server-sent events

rn_forge.fastapi.sse

Server-sent events over FastAPI.

Requires the sse extra. Not imported by :mod:rn_forge.fastapi.

Importing this module imports sse_starlette, which replaces uvicorn.Server.handle_exit for the whole process so that open streams are drained on shutdown (sse_starlette.sse.AppStatus).

:func:sse_response returns an EventSourceResponse; the media type, the cache-control and x-accel-buffering headers, the heartbeat, disconnect handling and graceful shutdown are its. This module adds validation of frame fields, a terminal error frame, and a retry frame. It does not read Last-Event-ID: the route does, and passes it to the event source.

DEFAULT_PING_SECONDS = 15.0 module-attribute

Seconds between heartbeat comments on an idle stream.

DEFAULT_RETRY_MS = 5000 module-attribute

Milliseconds a client waits before reconnecting a dropped stream.

sse_response(events, *, ping=DEFAULT_PING_SECONDS, retry=DEFAULT_RETRY_MS, registry=None, instance='', headers=None, log=None)

Stream events as text/event-stream.

Parameters:

Name Type Description Default
events AsyncIterable[ServerSentEvent]

The frames to send, in order.

required
ping float | None

Seconds between heartbeat comments while the stream is idle. None or 0 disables the heartbeat.

DEFAULT_PING_SECONDS
retry int | None

Milliseconds a browser EventSource waits before reconnecting. Sent as the first frame; None sends no such frame.

DEFAULT_RETRY_MS
registry ProblemRegistry | None

Maps an exception escaping events to its problem. Defaults to :func:~rn_forge.web.default_registry.

None
instance str

The problem's instance member.

''
headers Mapping[str, str] | None

Response headers. They are applied last, so each replaces a default of the same name.

None
log Log | None

Called as log("problem.server_error", context) for a 5xx problem, with the exception under "exc", as :func:~rn_forge.fastapi.problem.register_problem_handlers does.

None

Returns:

Name Type Description
EventSourceResponse

The response. Each frame of events is sent as given, except that an

EventSourceResponse

id or event containing \r, \n or \x00 is rejected

with EventSourceResponse

class:~rn_forge.web.WebError. An exception escaping events,

EventSourceResponse

that one included, ends the stream with a single frame whose event

EventSourceResponse

is error and whose data is the problem as JSON, as

EventSourceResponse

registry renders it. Cancellation and client disconnect are not

EventSourceResponse

errors and send nothing.

Raises:

Type Description
ValueError

retry is not a non-negative integer, or ping is negative.