tempest_fastapi_sdk.sse¶
Server-Sent Events sobre o streaming do Starlette.
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. |
heartbeat_event |
ServerSentEvent | Callable[[], ServerSentEvent] | None
|
What the heartbeat puts on the wire. |
max_queue |
int
|
Maximum number of buffered events. |
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
|
max_queue
|
int
|
Maximum buffered events before |
1000
|
overflow
|
OverflowPolicy
|
Overflow reaction. Defaults to
|
'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
¶
Return how many events were discarded by the overflow policy.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Count of events lost to |
int
|
since the stream was created. Always |
|
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 |
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 — |
None
|
status_code
|
int
|
HTTP status. Defaults to |
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
¶
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
( |
heartbeat_seconds |
float | None
|
Idle interval passed to every
:class: |
Initialize the broker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
redis
|
Redis | None
|
Async Redis client (from the |
None
|
channel_prefix
|
str
|
Prefix for Redis channels. In Redis mode
give every service its own value (for example
|
_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: |
None
|
max_queue
|
int
|
Bounded-queue size for every stream opened by
:meth: |
1000
|
overflow
|
OverflowPolicy
|
Overflow policy for those streams.
Defaults to |
'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: |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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
|
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
¶
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
¶
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 ( |
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 |
None
|
retry
|
int | None
|
Optional reconnect hint (ms). |
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
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 |
None
|
retry
|
int | None
|
Optional reconnect hint (ms). |
None
|
run
async
¶
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. |
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
|
id |
str | None
|
Optional |
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 |
encode
¶
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: |
required |
status_code
|
int
|
HTTP status code. Defaults to |
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
|
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 bycurrent_user; answers a :class:SSETicketResponseSchemawhose ticket opens the channelchannel_for(user).GET <prefix>/stream— reads?<ticket_param>=, checks the signature, the expiry andtyp="stream", and returnsbroker.response(channel). Without a ticket it asksfallback_user; with neither it answers401.
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 ( |
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 |
required |
fallback_user
|
Callable[..., Coroutine[Any, Any, Any]] | None
|
A
soft user dependency the stream route asks when no ticket
came — it returns |
None
|
channel_for
|
Callable[[Any], str] | None
|
Maps the authenticated
user to the broker channel. |
None
|
prefix
|
str
|
URL prefix. Defaults to |
'/sse'
|
tag
|
str
|
OpenAPI tag. Defaults to |
'SSE'
|
ticket_ttl
|
timedelta | None
|
Lifetime of a ticket. |
None
|
ticket_param
|
str
|
Query parameter the stream route reads the
ticket from. Defaults to |
'ticket'
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
The router, ready for |
Raises:
| Type | Description |
|---|---|
ValueError
|
When |
DEFAULT_SSE_TICKET_TTL
module-attribute
¶
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
¶
Claim of the ticket that names the broker channel it opens.
SSE_TICKET_ERROR
module-attribute
¶
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
¶
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.publishwaits 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.