Ir para o conteúdo

tempest_fastapi_sdk.sse

Server-Sent Events sobre o streaming do Starlette.

« Tempo real e mensageria


EventStream

EventStream(
    *,
    heartbeat_seconds: float | None = 15.0,
    heartbeat_event: ServerSentEvent | Callable[[], ServerSentEvent] | None = None,
    max_queue: int = 1000,
    overflow: OverflowPolicy = "drop_oldest",
)

Async in-memory queue feeding one SSE HTTP connection.

A handler builds one stream per client request, publish-es events from anywhere in the application (background tasks, websockets, dependency callbacks), and passes :meth:stream to :func:sse_response. A None enqueued by :meth:close terminates the iteration so the response completes cleanly.

Heartbeats are emitted when the queue stays empty for longer than heartbeat_seconds; this keeps load-balancers from closing idle TCP connections. By default the beat is an SSE comment (: keepalive), which the browser never surfaces to JavaScript. Pass heartbeat_event to send a real event instead, for a client that watches the beat to know the connection is alive.

Backpressure. The internal queue is bounded (max_queue) so a slow or stalled client cannot make a busy producer grow the queue without limit and exhaust memory. When the queue fills, the overflow policy decides what gives — evict the oldest event (default), drop the incoming one, or block the producer. The :meth:close sentinel always gets through, evicting a queued event if that is the only way to fit. :attr:dropped_events counts every event lost to overflow so you can surface it in metrics / logs.

Attributes:

Name Type Description
heartbeat_seconds float | None

Idle interval that triggers a heartbeat. None disables heartbeats.

heartbeat_event ServerSentEvent | Callable[[], ServerSentEvent] | None

What the heartbeat puts on the wire. None keeps the comment frame.

max_queue int

Maximum number of buffered events. 0 disables the bound (unbounded — pre-0.91 behavior).

overflow OverflowPolicy

What happens when the queue is full.

Initialize the stream.

Parameters:

Name Type Description Default
heartbeat_seconds float | None

Idle interval before a heartbeat is emitted.

15.0
heartbeat_event ServerSentEvent | Callable[[], ServerSentEvent] | None

The frame the heartbeat emits. None (the default) emits ServerSentEvent(comment="keepalive"), which keeps the connection warm without waking the browser. Pass a :class:ServerSentEvent to make the beat visible to the client instead — a comment does not fire onmessage, so a client that treats the beat as proof of a live connection has nothing to listen for. Pass a callable to build a fresh frame per beat, which is what stamping a timestamp into the payload needs.

None
max_queue int

Maximum buffered events before overflow kicks in. 0 disables the bound. Defaults to 1000.

1000
overflow OverflowPolicy

Overflow reaction. Defaults to "drop_oldest".

'drop_oldest'
Notes

Only "block" gets a hard-bounded queue, because only it wants real backpressure. The drop policies keep an unbounded queue and enforce the bound by hand on data events, which is what keeps the close sentinel from ever being blocked or evicted — the stream can always be terminated.

dropped_events property

dropped_events: int

Return how many events were discarded by the overflow policy.

Returns:

Name Type Description
int int

Count of events lost to drop_oldest / drop_newest

int

since the stream was created. Always 0 under "block"

int

or an unbounded queue.

publish async

publish(
    data: SSEData = "",
    *,
    event: str | None = None,
    id: str | None = None,
    retry: int | None = None,
) -> None

Enqueue a new event for delivery.

Parameters:

Name Type Description Default
data SSEData

The payload (string, bytes or JSON-serializable).

''
event str | None

Optional event name.

None
id str | None

Optional Last-Event-ID.

None
retry int | None

Optional reconnect hint in milliseconds.

None

publish_event async

publish_event(event: ServerSentEvent) -> None

Enqueue a pre-built :class:ServerSentEvent.

Parameters:

Name Type Description Default
event ServerSentEvent

The event to enqueue.

required

close async

close() -> None

Signal the stream to end after draining queued events.

response

response(
    *,
    on_disconnect: Callable[[], object] | None = None,
    status_code: int = 200,
    headers: dict[str, str] | None = None,
) -> StreamingResponse

Return an SSE :class:StreamingResponse wired to this stream.

Convenience over sse_response(self.stream(), ...) that also threads on_disconnect — run when the client goes away — so a producer bound to this connection is torn down without hand-rolled try/finally boilerplate at every call site.

Parameters:

Name Type Description Default
on_disconnect Callable[[], object] | None

Called (awaited if it returns an awaitable) when the response generator closes — i.e. the client disconnected or the stream ended. Cancel the producer task here. Whatever it returns is discarded, so a callback with a return value of its own — task.cancel, which returns bool — is as valid as one returning None.

None
status_code int

HTTP status. Defaults to 200.

200
headers dict[str, str] | None

Extra headers to attach.

None

Returns:

Name Type Description
StreamingResponse StreamingResponse

A ready-to-return SSE response.

stream async

stream() -> AsyncIterator[bytes]

Yield encoded SSE bytes until :meth:close is invoked.

Yields:

Name Type Description
bytes AsyncIterator[bytes]

An encoded SSE frame ready to write to the wire.

SSEBroker

SSEBroker(
    *,
    redis: Redis | None = None,
    channel_prefix: str = _DEFAULT_CHANNEL_PREFIX,
    heartbeat_seconds: float | None = 15.0,
    heartbeat_event: ServerSentEvent | Callable[[], ServerSentEvent] | None = None,
    max_queue: int = 1000,
    overflow: OverflowPolicy = "drop_oldest",
)

Channel-based SSE fan-out, optionally bridged over Redis pub/sub.

Attributes:

Name Type Description
channel_prefix str

Redis key prefix for published channels ("<prefix>:<channel>"). Also the PSUBSCRIBE pattern root. Ignored in single-process mode.

heartbeat_seconds float | None

Idle interval passed to every :class:EventStream created by :meth:register.

Initialize the broker.

Parameters:

Name Type Description Default
redis Redis | None

Async Redis client (from the [cache] extra). None runs single-process (local fan-out only).

None
channel_prefix str

Prefix for Redis channels. In Redis mode give every service its own value (for example "orders-api:sse"): Redis pub/sub is shared by every client of the instance regardless of the DB index, so the prefix is the only thing that keeps one service's events out of another's streams. A nested prefix (app next to app:chat) is safe since 0.340.0: the "<prefix>:*" pattern still receives the longer prefix's messages, but each envelope carries the prefix that published it and the receiver drops the ones that are not its own. Defaults to "sse", which is kept for compatibility; with a Redis client it logs a warning naming the risk rather than failing, so existing single-service deployments keep working unchanged.

_DEFAULT_CHANNEL_PREFIX
heartbeat_seconds float | None

Idle heartbeat for streams.

15.0
heartbeat_event ServerSentEvent | Callable[[], ServerSentEvent] | None

Frame every stream emits on an idle beat, forwarded to :class:EventStream. None keeps the : keepalive comment. Set it here rather than subclassing: this is the only place a stream is constructed, so a service that needs a visible beat has no other seam.

None
max_queue int

Bounded-queue size for every stream opened by :meth:register. 0 disables the bound. Defaults to 1000.

1000
overflow OverflowPolicy

Overflow policy for those streams. Defaults to "drop_oldest".

'drop_oldest'

register

register(channel: str) -> EventStream

Open a local stream subscribed to channel and track it.

Parameters:

Name Type Description Default
channel str

The logical channel (e.g. a user id or topic).

required

Returns:

Name Type Description
EventStream EventStream

A fresh stream to hand to

EventStream

func:tempest_fastapi_sdk.sse_response.

Raises:

Type Description
ValueError

When channel is :data:BROADCAST_CHANNEL, which :meth:broadcast reserves.

response

response(
    channel: str, *, status_code: int = 200, headers: dict[str, str] | None = None
) -> StreamingResponse

Subscribe to channel and return the SSE response in one call.

Bundles the whole per-connection lifecycle: :meth:register opens a local stream, :func:tempest_fastapi_sdk.sse_response wraps it, and an on_disconnect hook calls :meth:unregister when the client goes away. This removes the hand-rolled try/finally wrapper — forgetting which used to leak a stream per disconnect.

Parameters:

Name Type Description Default
channel str

The logical channel to subscribe the client to.

required
status_code int

HTTP status. Defaults to 200.

200
headers dict[str, str] | None

Extra headers to attach.

None

Returns:

Name Type Description
StreamingResponse StreamingResponse

A ready-to-return SSE response that

StreamingResponse

unregisters its stream on disconnect.

unregister

unregister(channel: str, stream: EventStream) -> None

Drop a closed stream from channel.

Call this from the response generator's finally so a disconnected client is forgotten.

Parameters:

Name Type Description Default
channel str

The channel the stream was registered under.

required
stream EventStream

The stream to remove.

required

local_subscribers

local_subscribers(channel: str) -> int

Return how many local streams are open on channel.

Parameters:

Name Type Description Default
channel str

The channel to inspect.

required

Returns:

Name Type Description
int int

The local subscriber count (this worker only).

local_channels

local_channels() -> list[str]

Return the channels with at least one open stream on this worker.

The counterpart of :meth:local_subscribers, which answers for one channel: this enumerates them, so "how many clients are connected right now" is a metric a service can read without touching the broker's internals. Local by construction — a worker knows its own streams and nothing about its siblings'.

Returns:

Type Description
list[str]

list[str]: The channel names, sorted, that hold a live stream

list[str]

in this process ([] when nobody is connected here).

publish async

publish(
    channel: str,
    data: SSEData = "",
    *,
    event: str | None = None,
    id: str | None = None,
    retry: int | None = None,
) -> None

Publish an event to every subscriber of channel.

In Redis mode the event is PUBLISH-ed and delivered to all workers (including this one) by their :meth:run loop. In single-process mode it fans out to local streams immediately.

Parameters:

Name Type Description Default
channel str

Target channel.

required
data SSEData

Payload (string, bytes or JSON-serializable).

''
event str | None

Optional SSE event name.

None
id str | None

Optional Last-Event-ID.

None
retry int | None

Optional reconnect hint (ms).

None

Raises:

Type Description
ValueError

When channel is :data:BROADCAST_CHANNEL, which :meth:broadcast reserves.

broadcast async

broadcast(
    data: SSEData = "",
    *,
    event: str | None = None,
    id: str | None = None,
    retry: int | None = None,
) -> None

Publish an event to every subscriber of every channel.

The axis :meth:publish does not cover: one event to N channels instead of one channel to N connections. This is the global notice — "maintenance in 5 minutes", "a new version is available" — that a service otherwise has to fake by keeping its own registry of open channels alongside the broker's.

In Redis mode the event is PUBLISH-ed under :data:BROADCAST_CHANNEL, which the <prefix>:* pattern every worker already subscribes to reaches without any new subscription; each worker's :meth:run loop then fans it to all of its local streams. In single-process mode it fans out locally right away.

A stream registered under more than one channel — which :meth:register does not produce, but a caller holding a stream can arrange — receives the event once: the fan-out is over the set of streams, not the list of channels.

Parameters:

Name Type Description Default
data SSEData

Payload (string, bytes or JSON-serializable).

''
event str | None

Optional SSE event name.

None
id str | None

Optional Last-Event-ID.

None
retry int | None

Optional reconnect hint (ms).

None

run async

run() -> None

Consume Redis pub/sub and fan messages to local streams.

Long-running: start it as a background task in the app lifespan and cancel it (or call :meth:aclose) on shutdown. A no-op in single-process mode.

Each message is dispatched in isolation. The <prefix>:* pattern receives whatever any client of the Redis instance publishes on a matching channel, not only this broker's envelopes, so a frame that fails to decode or to fan out is logged (channel and error type, never the payload) and skipped. Letting it escape would end the loop, and with it every later delivery to this worker's streams, while the worker kept accepting connections.

Raises:

Type Description
RuntimeError

If called without a Redis client.

aclose async

aclose() -> None

Stop the pub/sub subscription opened by :meth:run.

ServerSentEvent dataclass

ServerSentEvent(
    data: SSEData = "",
    event: str | None = None,
    id: str | None = None,
    retry: int | None = None,
    comment: str | None = None,
)

A single SSE frame.

Encodes to the line-based wire format defined by the spec (https://html.spec.whatwg.org/multipage/server-sent-events.html). data may be a string, bytes, or any JSON-serializable Python object — non-string payloads are JSON-encoded before transmission.

Attributes:

Name Type Description
data SSEData

The event payload.

event str | None

Optional event name; the browser routes EventSource.addEventListener(name, ...) by this.

id str | None

Optional Last-Event-ID value used by the browser to resume after a reconnect.

retry int | None

Reconnection delay (milliseconds) the browser should use after a connection drop.

comment str | None

Optional comment line prepended to the frame (renders as : comment); useful for heartbeats.

encode

encode() -> str

Render the event as the wire-format string.

A frame that carries no payload and no event name, but does carry comment, id or retry, is a control frame: it gets no data: line at all. That line is what makes the browser dispatch, even when it looks empty — data: parses to a data buffer holding a single line feed, and the dispatch step strips that feed and delivers the empty string as a message event. Writing it therefore turned the idle : keepalive heartbeat into an event that every consumer listening on onmessage received as business data. Measured in Chromium over EventSource: : keepalive\ndata: \n\n fires onmessage, : keepalive\n\n fires nothing.

A frame that names an event keeps its data: line when the payload is empty, because a named event with an empty body is meant to dispatch; so does a bare ServerSentEvent().

Returns:

Name Type Description
str str

The encoded event, including the trailing blank line

str

that marks frame boundaries.

sse_response

sse_response(
    stream: AsyncIterable[bytes],
    *,
    status_code: int = 200,
    headers: dict[str, str] | None = None,
    on_disconnect: Callable[[], object] | None = None,
) -> StreamingResponse

Wrap stream in a Starlette text/event-stream response.

Adds the SSE-specific headers (Cache-Control: no-cache, Connection: keep-alive, X-Accel-Buffering: no) so intermediate proxies don't buffer or cache the long-lived response. Caller-supplied headers are layered below the SSE defaults so the three critical headers above cannot be accidentally overridden — pass extra metadata, not replacements.

Pass on_disconnect to run cleanup when the client goes away — the response generator's finally is the one place guaranteed to fire on disconnect, so this is where you cancel a bound producer task or call :meth:SSEBroker.unregister. It removes the hand-rolled try/finally wrapper the recipe used to require.

Parameters:

Name Type Description Default
stream AsyncIterable[bytes]

The byte stream produced by :meth:EventStream.stream (or any compatible generator).

required
status_code int

HTTP status code. Defaults to 200.

200
headers dict[str, str] | None

Extra headers to attach.

None
on_disconnect Callable[[], object] | None

Cleanup callback run (and awaited if it returns an awaitable) when the stream ends or the client disconnects. None skips it.

None

Returns:

Name Type Description
StreamingResponse StreamingResponse

A ready-to-return SSE response.

make_sse_router

make_sse_router(
    broker: SSEBroker | Callable[[Request], SSEBroker],
    *,
    tokens: JWTUtils | Callable[[Request], JWTUtils],
    current_user: Callable[..., Coroutine[Any, Any, Any]],
    fallback_user: Callable[..., Coroutine[Any, Any, Any]] | None = None,
    channel_for: Callable[[Any], str] | None = None,
    prefix: str = "/sse",
    tag: str = "SSE",
    ticket_ttl: timedelta | None = None,
    ticket_param: str = "ticket",
    docs_locale: str | None = None,
) -> APIRouter

Build the router that issues SSE tickets and serves the stream.

Mounts two routes:

  • POST <prefix>/ticket — guarded by current_user; answers a :class:SSETicketResponseSchema whose ticket opens the channel channel_for(user).
  • GET <prefix>/stream — reads ?<ticket_param>=, checks the signature, the expiry and typ="stream", and returns broker.response(channel). Without a ticket it asks fallback_user; with neither it answers 401.

The channel travels inside the signed ticket, so the stream route opens no database session and the client cannot pick a channel of its own. A deactivated account stops getting tickets at once (that is current_user's check) and loses the stream on its next reconnect.

With :class:~tempest_fastapi_sdk.UserAuthService, prefer :meth:~tempest_fastapi_sdk.UserAuthService.sse_router, which builds tokens, current_user and fallback_user from the service.

Parameters:

Name Type Description Default
broker SSEBroker | Callable[[Request], SSEBroker]

The broker the stream subscribes to, or a factory called with each request that returns it (lambda request: request.app.state.broker).

required
tokens JWTUtils | Callable[[Request], JWTUtils]

The helper that signs and verifies tickets — the same one that signs the access token, or a factory returning it.

required
current_user Callable[..., Coroutine[Any, Any, Any]]

The dependency that authenticates POST <prefix>/ticket and yields the user, raising on a missing or invalid session.

required
fallback_user Callable[..., Coroutine[Any, Any, Any]] | None

A soft user dependency the stream route asks when no ticket came — it returns None instead of raising. Lets a client that can send Authorization: Bearer skip the ticket, and, built with query_param, keeps an existing ?access_token= client working while it migrates. None (default) makes the ticket the only way in.

None
channel_for Callable[[Any], str] | None

Maps the authenticated user to the broker channel. None (default) uses str(user.id).

None
prefix str

URL prefix. Defaults to "/sse".

'/sse'
tag str

OpenAPI tag. Defaults to "SSE".

'SSE'
ticket_ttl timedelta | None

Lifetime of a ticket. None (default) uses :data:DEFAULT_SSE_TICKET_TTL (60 seconds).

None
ticket_param str

Query parameter the stream route reads the ticket from. Defaults to "ticket".

'ticket'
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

The router, ready for app.include_router.

Raises:

Type Description
ValueError

When ticket_ttl is shorter than one second.

DEFAULT_SSE_TICKET_TTL module-attribute

DEFAULT_SSE_TICKET_TTL: Final[timedelta] = timedelta(seconds=60)

How long a ticket can open a stream. Long enough for the round trip between POST /ticket and new EventSource(...), short enough that a URL lifted from a log is useless soon after.

SSE_CHANNEL_CLAIM module-attribute

SSE_CHANNEL_CLAIM: Final[str] = 'ch'

Claim of the ticket that names the broker channel it opens.

SSE_TICKET_ERROR module-attribute

SSE_TICKET_ERROR: Final[str] = 'SSE ticket is missing or invalid'

Message of the 401 the stream route answers without a usable credential.

SSETicketResponseSchema

Bases: BaseSchema

A ticket that opens one SSE stream.

The ticket goes in the stream URL (?ticket=...) because the browser EventSource cannot send a header. It is a JWT with typ="stream": every guard built on :func:~tempest_fastapi_sdk.token_type_allowed refuses it, so a ticket copied out of an access log opens that one stream until it expires and calls nothing else. It is not single-use: until it expires it opens the stream every time it is presented.

Attributes:

Name Type Description
ticket str

The signed ticket to pass as the stream's query parameter.

expires_in int

Seconds until the ticket can no longer open a stream. A stream already open is not cut when it expires; a reconnect after it needs a new ticket.

OverflowPolicy module-attribute

OverflowPolicy = Literal['drop_oldest', 'drop_newest', 'block']

How :class:EventStream reacts when its bounded queue is full.

  • "drop_oldest" (default) — evict the oldest queued event to make room for the new one. Keeps the freshest data; best for live tickers / progress where stale frames are worthless.
  • "drop_newest" — discard the incoming event, keep the backlog. Best when every early event matters and later ones are redundant.
  • "block" — apply backpressure: :meth:EventStream.publish waits until the consumer drains a slot. Use only when the producer is dedicated to a single connection and losing events is unacceptable.

SSEData module-attribute

SSEData: TypeAlias = (
    str | bytes | Mapping[str, Any] | Sequence[Any] | int | float | bool | None
)

Payload accepted by the SSE publishers (:meth:EventStream.publish, :meth:SSEBroker.publish, and the :class:ServerSentEvent data field).

str and bytes are written to the wire as-is; every other value is JSON-encoded (json.dumps(..., default=str)) before transmission. The union spells out the JSON value shapes — objects (Mapping), arrays (Sequence) and the scalars str / int / float / bool / None. To send an arbitrary object that only serializes via default=str (e.g. a bare UUID), wrap it in str(...) or a dict first.