tempest_fastapi_sdk.websockets¶
WebSocket: router autenticado, hub de conexões e o envelope de mensagem.
WebSocketHub
¶
In-process registry of live WebSocket connections.
Tracks every connection accepted by
:func:tempest_fastapi_sdk.make_websocket_router and offers three
delivery patterns:
send_to(user_id, envelope)— every socket the user has open right now.send_many({user_id: envelope, ...})— a different frame per user, dispatched concurrently.broadcast(envelope, topic=...)— every subscriber oftopic(or every connection whentopicis omitted).subscribe(connection_id, topic)/unsubscribe(connection_id, topic)— per-connection topic membership.
This hub is single-process. For multi-replica deployments, fan
out across processes via a pub/sub backend (Redis pub/sub,
RabbitMQ topic exchange) — the hub itself only handles
in-process delivery. The future RedisWebSocketHub will swap
the local broadcast for a redis-driven one without changing the
public surface; today, run a single replica or use sticky
sessions when WebSocket fan-out matters.
The hub is safe to share across handlers in the same FastAPI
app — all mutators take an asyncio.Lock so concurrent
register/unregister calls do not corrupt the internal state.
Initialize the hub.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
max_per_user
|
int
|
Cap on concurrent connections per
user. When the cap is hit on |
5
|
register
async
¶
register(user_id: UUID, ws: WebSocket) -> WebSocketConnection
Register an accepted WebSocket against user_id.
When the user is already at max_per_user open
connections, the oldest one is removed and force-closed (code
4429). The indexes change under the hub lock; the close
handshake runs after the lock is released and is abandoned after
_EVICT_CLOSE_TIMEOUT_SECONDS (1 s). Awaiting it under the lock let
a peer that never answers the close stall every send_to,
broadcast and register of every other user meanwhile.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
The authenticated user owning the new connection. |
required |
ws
|
WebSocket
|
The accepted FastAPI WebSocket. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
WebSocketConnection |
WebSocketConnection
|
The registered handle. Pass its |
WebSocketConnection
|
|
|
WebSocketConnection
|
meth: |
unregister
async
¶
Remove a connection from every index. Idempotent.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection_id
|
UUID
|
Identifier of the connection. |
required |
subscribe
async
¶
Add topic to the connection's subscription set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection_id
|
UUID
|
Identifier of the connection. |
required |
topic
|
str
|
The topic to subscribe to or publish on. |
required |
unsubscribe
async
¶
Drop topic from the connection's subscription set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection_id
|
UUID
|
Identifier of the connection. |
required |
topic
|
str
|
The topic to subscribe to or publish on. |
required |
send_to
async
¶
send_to(user_id: UUID, envelope: WSEnvelope) -> int
Send envelope to every connection owned by user_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
Target user. |
required |
envelope
|
WSEnvelope
|
Frame to deliver. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of sockets that successfully received the |
int
|
frame. Dead connections are evicted transparently and do |
|
int
|
not count. |
send_many
async
¶
send_many(envelopes: dict[UUID, WSEnvelope]) -> int
Deliver a different envelope to each user, concurrently.
:meth:broadcast sends one frame to everyone and
:meth:send_to serves a single user, which leaves the common
case of per-recipient payloads — a game's fog of war, a feed
personalized per subscriber — as N sequential await
send_to calls in the caller, each waiting on the previous
socket's write.
Here every user's sockets are dispatched in parallel via
asyncio.gather, so the wall-clock cost is the slowest
socket rather than the sum of all of them. Dead connections
are evicted transparently, exactly as in :meth:send_to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
envelopes
|
dict[UUID, WSEnvelope]
|
Target user to the frame that user should receive. Users with no live connection are skipped silently. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Total number of sockets that received their frame. |
broadcast
async
¶
broadcast(envelope: WSEnvelope, *, topic: str | None = None) -> int
Deliver envelope to every subscriber of topic.
When topic is None, the envelope is delivered to
every active connection across every user — useful for
system-wide announcements, but expensive at scale; prefer
topic-scoped delivery when you can.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
envelope
|
WSEnvelope
|
Frame to deliver. |
required |
topic
|
str | None
|
Topic to fan out on, or |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Number of successful sends. See :meth: |
online_users
¶
Return the set of users with at least one active connection.
Returns:
| Type | Description |
|---|---|
set[UUID]
|
set[UUID]: The connections reached. |
connection_count
¶
Return the total number of live connections.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many connections received the message. |
topic_count
¶
Return the number of subscribers for topic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
topic
|
str
|
The topic to subscribe to or publish on. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
How many connections received the message. |
WebSocketConnection
dataclass
¶
A single live WebSocket bound to an authenticated user.
Attributes:
| Name | Type | Description |
|---|---|---|
connection_id |
UUID
|
Unique identifier; the hub keys connections by this so the same user can hold several sockets at once (e.g. multi-tab). |
user_id |
UUID
|
The user the connection belongs to. Set by
|
ws |
WebSocket
|
The underlying FastAPI/Starlette socket. |
topics |
set[str]
|
Set of topic strings the connection has
subscribed to. Populated by
:meth: |
make_websocket_router
¶
make_websocket_router(
handler: WSHandler,
*,
hub: WebSocketHub,
bearer_resolver: BearerResolver,
settings: WebSocketSettings,
path: str = "/ws",
tags: list[str] | None = None,
) -> APIRouter
Build a single-endpoint WebSocket router.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
handler
|
WSHandler
|
Coroutine the SDK invokes once per authenticated connection. The handler is responsible for the message loop; the router takes care of auth + heartbeat + hub registration. |
required |
hub
|
WebSocketHub
|
Shared hub for broadcast / send_to. One hub instance per FastAPI app is the usual setup. |
required |
bearer_resolver
|
BearerResolver
|
Awaitable returning the
user UUID for a token, or |
required |
settings
|
WebSocketSettings
|
Heartbeat / cap / size limits. |
required |
path
|
str
|
Mount path. Defaults to |
'/ws'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |
make_jwt_bearer_resolver
¶
make_jwt_bearer_resolver(
tokens: JWTUtils,
*,
accepted: Collection[str] = (ACCESS_TOKEN_TYPE,),
strict: bool = True,
) -> BearerResolver
Build the :data:BearerResolver for tokens signed by tokens.
The handshake is the WebSocket's only authentication step, and the
resolver is all of it. Checking the signature and the expiry is not
enough when one secret signs several kinds of token:
:class:~tempest_fastapi_sdk.UserAuthService signs the access token,
the refresh token and the MFA-pending token with the same
JWTUtils, and all three carry sub. A resolver that returns
sub after decode opens a full session for the token handed
out after the password step but before the second factor, and for
a refresh token. This one refuses every token whose type is not in
accepted, through the same
:func:~tempest_fastapi_sdk.utils.token_types.token_type_allowed
the HTTP guards use.
strict defaults to True, unlike
:func:~tempest_fastapi_sdk.make_bearer_token_dependency: a token
with no type marker at all is refused. Every token
:class:~tempest_fastapi_sdk.UserAuthService issues carries one;
pass strict=False only while access tokens a project signed
itself, without typ, are still in circulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
JWTUtils
|
The helper that signs the application's access tokens. |
required |
accepted
|
Collection[str]
|
Token types that may open a socket. Defaults to the access token alone. |
(ACCESS_TOKEN_TYPE,)
|
strict
|
bool
|
Refuse a token whose type cannot be determined. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
BearerResolver |
BearerResolver
|
Awaitable mapping a bearer token to the user id |
BearerResolver
|
in its |
|
BearerResolver
|
of a refused type, or carries no UUID subject. |
heartbeat
async
¶
heartbeat(
ws: WebSocket,
*,
settings: WebSocketSettings,
max_message_bytes: int | None = None,
ping_message: Mapping[str, Any] | None = None,
) -> AsyncIterator[Liveness]
Keep an accepted socket honest for as long as the block runs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ws
|
WebSocket
|
A socket that has already been accepted. This does not accept it — the handshake, including any auth or subprotocol negotiation, belongs to the caller. |
required |
settings
|
WebSocketSettings
|
Supplies |
required |
max_message_bytes
|
int | None
|
Reject inbound frames larger
than this with |
None
|
ping_message
|
Mapping[str, Any] | None
|
The JSON object each
ping sends. |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
Liveness |
AsyncIterator[Liveness]
|
The handle. Read |
AsyncIterator[Liveness]
|
cadence; call |
On exit the ping task is cancelled and ws.receive is restored,
so a socket that outlives the block behaves as it did before —
which matters when the block is nested inside another that also
wraps receive.
Liveness
dataclass
¶
The handle :func:heartbeat yields.
Attributes:
| Name | Type | Description |
|---|---|---|
interval_seconds |
int
|
How often a ping goes out. Read it to announce the cadence to the client — a browser cannot tell a normal quiet interval from a dead link, so its own watchdog has to be calibrated from this number rather than hard-coded. Retuning the server would otherwise make every client read the new interval as a drop. |
timeout_seconds |
int
|
Silence tolerated before the close. |
last_seen |
float
|
|
touch
¶
Mark the peer as alive right now.
Every inbound frame already does this on its own. Call it when liveness is proven by something the socket cannot see — a message that arrived over another transport for the same session, or work the peer demonstrably completed.
WSEnvelope
¶
Bases: BaseSchema
Canonical message envelope for the bundled WebSocket router.
Every frame the SDK sends — application data, heartbeats, errors —
fits this shape so clients can dispatch on type alone. Senders
on the consumer side are encouraged to use it too, but the router
accepts any JSON payload and only the heartbeat frames it owns are
strictly required to follow this schema.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
str
|
Event name. Reserved values:
|
data |
dict[str, Any]
|
Payload — empty dict when none. |
request_id |
str | None
|
Echoes the originating HTTP request-id for end-to-end tracing across SSE/HTTP/WS. |
HEARTBEAT_TIMEOUT_CODE
module-attribute
¶
Close code for a peer that went silent past the deadline.
Application range, so it never collides with a protocol-level close. Clients are expected to treat it as "reconnect", not as an error.