tempest_fastapi_sdk.rooms¶
Salas multiplayer online: um servidor de relay para jogos, sobre WebSocket ou TCP.
RoomRegistry
¶
RoomRegistry(
policy: RoomPolicy | None = None,
*,
identity_resolver: IdentityResolver | None = None,
clock: Callable[[], float] = monotonic,
)
Every room of one game server, in this process.
Attributes:
| Name | Type | Description |
|---|---|---|
policy |
RoomPolicy
|
The rules every room follows. |
Build an empty registry.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
policy
|
RoomPolicy | None
|
The rules; |
None
|
identity_resolver
|
IdentityResolver | None
|
Turns a bearer token
into an identity. When set, every connection needs a valid
token and its player id comes from it; |
None
|
clock
|
Callable[[], float]
|
Monotonic time source for the rate limit (tests). |
monotonic
|
requires_identity
property
¶
Whether connections must present a valid token.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
room_count
property
¶
Return how many rooms are open.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
Open rooms. |
get
¶
get(code: str) -> Room | None
Return an open room.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
The room code, any case. |
required |
Returns:
| Type | Description |
|---|---|
Room | None
|
Room | None: The room, or |
identify
async
¶
identify(token: str | None) -> RoomIdentity | None
Resolve a connection's identity.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str | None
|
The bearer token the connection presented. |
required |
Returns:
| Type | Description |
|---|---|
RoomIdentity | None
|
RoomIdentity | None: The identity, or |
RoomIdentity | None
|
resolver is configured. |
Raises:
| Type | Description |
|---|---|
UnauthorizedError
|
When a resolver is configured and the token is missing or not valid. |
create
async
¶
create(
peer: RoomPeer,
*,
name: str | None = None,
version: str | None = None,
identity: RoomIdentity | None = None,
) -> tuple[Room, RoomMember]
Open a room with the caller as host in slot 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
peer
|
RoomPeer
|
The caller's connection. |
required |
name
|
str | None
|
Display name, for a guest. |
None
|
version
|
str | None
|
Protocol version the client speaks. |
None
|
identity
|
RoomIdentity | None
|
Resolved identity, if any. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Room, RoomMember]
|
tuple[Room, RoomMember]: The room and the caller's seat. |
Raises:
| Type | Description |
|---|---|
ProtocolVersionError
|
On a version mismatch. |
ServerFullError
|
When |
join
async
¶
join(
code: str,
peer: RoomPeer,
*,
name: str | None = None,
version: str | None = None,
identity: RoomIdentity | None = None,
) -> tuple[Room, RoomMember]
Seat the caller in an open room.
An identified player already seated there (a second connection of the same account) takes the seat over, as a resume would.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
The room code, any case. |
required |
peer
|
RoomPeer
|
The caller's connection. |
required |
name
|
str | None
|
Display name, for a guest. |
None
|
version
|
str | None
|
Protocol version the client speaks. |
None
|
identity
|
RoomIdentity | None
|
Resolved identity, if any. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Room, RoomMember]
|
tuple[Room, RoomMember]: The room and the caller's seat. |
Raises:
| Type | Description |
|---|---|
ProtocolVersionError
|
On a version mismatch. |
RoomNotFoundError
|
When no room has that code. |
RoomInMatchError
|
When the room is playing and locks. |
RoomFullError
|
When no slot is free. |
resume
async
¶
resume(
code: str, player_id: str, resume_token: str, peer: RoomPeer
) -> tuple[Room, RoomMember]
Put a dropped (or replaced) player back in their seat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
str
|
The room code. |
required |
player_id
|
str
|
The player id from |
required |
resume_token
|
str
|
The resume token from |
required |
peer
|
RoomPeer
|
The new connection. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Room, RoomMember]
|
tuple[Room, RoomMember]: The room and the seat. |
Raises:
| Type | Description |
|---|---|
ResumeRejectedError
|
When the room, the seat or the token does not match (the grace window may have run out). |
leave
async
¶
leave(room: Room, member: RoomMember) -> None
Remove a player at once, freeing the slot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
room
|
Room
|
The room. |
required |
member
|
RoomMember
|
The player. |
required |
disconnect
async
¶
disconnect(room: Room, member: RoomMember, peer: RoomPeer) -> None
Note that a connection dropped, keeping the seat for the grace window.
Does nothing when peer is no longer the seat's connection (the
player already resumed elsewhere).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
room
|
Room
|
The room. |
required |
member
|
RoomMember
|
The player. |
required |
peer
|
RoomPeer
|
The connection that dropped. |
required |
set_state
async
¶
set_state(room: Room, member: RoomMember, state: RoomState) -> None
Move the room between lobby and playing (host only).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
room
|
Room
|
The room. |
required |
member
|
RoomMember
|
The caller. |
required |
state
|
RoomState
|
The new state. |
required |
Raises:
| Type | Description |
|---|---|
NotHostError
|
When the caller is not the host. |
relay_json
async
¶
relay_json(
room: Room, member: RoomMember, data: object, *, to: str | None = None
) -> None
Relay a JSON message, stamped with the sender the server knows.
Delivered as {"type": "message", "from": <player_id>, "data": ...}
to every other connected player, or only to to.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
room
|
Room
|
The room. |
required |
member
|
RoomMember
|
The sender. |
required |
data
|
object
|
The payload, relayed as is. |
required |
to
|
str | None
|
A player id, or |
None
|
Raises:
| Type | Description |
|---|---|
RateLimitedError
|
Over the rate limit. |
MessageNotAllowedError
|
When an allow list is set and |
PlayerNotFoundError
|
When |
relay_bytes
async
¶
relay_bytes(room: Room, member: RoomMember, slot: int, payload: bytes) -> None
Relay a binary frame, prefixed with the sender's slot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
room
|
Room
|
The room. |
required |
member
|
RoomMember
|
The sender. |
required |
slot
|
int
|
Destination slot, or :data: |
required |
payload
|
bytes
|
Opaque bytes, relayed as is. |
required |
Raises:
| Type | Description |
|---|---|
RateLimitedError
|
Over the rate limit. |
PlayerNotFoundError
|
When |
RoomPolicy
dataclass
¶
RoomPolicy(
max_players: int = 4,
protocol_version: str | None = None,
reconnect_grace_seconds: float = 10.0,
messages_per_second: float = 120.0,
burst: int = 240,
max_rooms: int = 1000,
code_length: int = 4,
lock_when_playing: bool = True,
allowed_message_types: frozenset[str] | None = None,
max_name_length: int = 24,
)
The rules every room of a registry follows.
Attributes:
| Name | Type | Description |
|---|---|---|
max_players |
int
|
Slots per room, |
protocol_version |
str | None
|
Version every client must announce on
|
reconnect_grace_seconds |
float
|
How long a dropped player's seat is
kept for a |
messages_per_second |
float
|
Sustained relay rate allowed per player, JSON and binary together (token bucket). |
burst |
int
|
Messages a player may send at once above the rate. |
max_rooms |
int
|
Rooms the registry holds at most. |
code_length |
int
|
Characters in a room code, |
lock_when_playing |
bool
|
Refuse |
allowed_message_types |
frozenset[str] | None
|
When set, a relayed
JSON |
max_name_length |
int
|
Characters kept of a player name. |
Raises:
| Type | Description |
|---|---|
ValueError
|
When a bound is out of range. |
RoomIdentity
dataclass
¶
Who a connection is, as an identity resolver answers.
Attributes:
| Name | Type | Description |
|---|---|---|
player_id |
str
|
Stable player id (the user id of an account). |
name |
str
|
Display name. |
IdentityResolver
module-attribute
¶
IdentityResolver = Callable[[str], Awaitable[RoomIdentity | None]]
Turn a bearer token into an identity, or None when it is not valid.
Room
dataclass
¶
Room(
code: str,
max_players: int,
members: dict[str, RoomMember] = dict(),
host_id: str | None = None,
state: RoomState = "lobby",
)
One room.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
The code players join with. |
max_players |
int
|
Slots. |
members |
dict[str, RoomMember]
|
Players by id. |
host_id |
str | None
|
The host's player id. |
state |
RoomState
|
|
snapshot
¶
Describe the room for its players.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
dict[str, Any]
|
|
free_slot
¶
Return the lowest free slot.
Returns:
| Type | Description |
|---|---|
int | None
|
int | None: The slot, or |
by_slot
¶
by_slot(slot: int) -> RoomMember | None
Return the player in a slot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slot
|
int
|
The slot. |
required |
Returns:
| Type | Description |
|---|---|
RoomMember | None
|
RoomMember | None: The player, or |
RoomMember
dataclass
¶
RoomMember(
player_id: str,
name: str,
slot: int,
resume_token: str,
peer: RoomPeer | None = None,
tokens: float = 0.0,
refilled_at: float = 0.0,
warned_at: float = float("-inf"),
grace_task: Task[None] | None = None,
)
A player seated in a room.
Attributes:
| Name | Type | Description |
|---|---|---|
player_id |
str
|
Stable player id. |
name |
str
|
Display name. |
slot |
int
|
Seat number, |
resume_token |
str
|
Secret a dropped connection presents to resume. |
peer |
RoomPeer | None
|
The live connection; |
tokens |
float
|
Token-bucket balance of the rate limit. |
refilled_at |
float
|
Clock reading of the last refill. |
warned_at |
float
|
Clock reading of the last |
grace_task |
Task[None] | None
|
Pending removal of a dropped player. |
RoomState
module-attribute
¶
lobby takes new players; playing refuses them by default.
RoomPeer
¶
Bases: Protocol
One live connection, whatever its transport.
send_json
async
¶
Send one control message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
dict[str, Any]
|
The message. |
required |
send_bytes
async
¶
Send one binary relay frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
|
required |
close
async
¶
Close the connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
int
|
Close code. |
required |
reason
|
str
|
Short reason. |
required |
BROADCAST_SLOT
module-attribute
¶
Destination slot of a binary frame meant for every other player.
REPLACED_CLOSE_CODE
module-attribute
¶
Close code sent to a connection whose player resumed on another one.
ROOM_CODE_ALPHABET
module-attribute
¶
Characters a room code is drawn from: no 0/O nor 1/I.
A code is read aloud and typed on a phone, so the look-alikes are out.
RoomSession
¶
RoomSession(
registry: RoomRegistry, peer: RoomPeer, *, identity: RoomIdentity | None = None
)
The protocol state of one connection.
Attributes:
| Name | Type | Description |
|---|---|---|
registry |
RoomRegistry
|
The server's registry. |
peer |
RoomPeer
|
The connection. |
room |
Room | None
|
The room the connection is in. |
member |
RoomMember | None
|
The connection's seat. |
Start a session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
RoomRegistry
|
The server's registry. |
required |
peer
|
RoomPeer
|
The connection. |
required |
identity
|
RoomIdentity | None
|
An identity already resolved at
the handshake (the WebSocket |
None
|
handle_text
async
¶
Handle one text frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
raw
|
str
|
The frame, expected to be a JSON object. |
required |
handle_json
async
¶
Handle one decoded control message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
object
|
The decoded frame. |
required |
handle_binary
async
¶
Handle one binary relay frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
|
required |
close
async
¶
Report that the connection dropped (the seat waits for a resume).
The bookkeeping runs in its own task behind :func:asyncio.shield,
because transports call this from a finally that is often
reached by cancellation (server shutdown, a test client tearing the
handler down right after the disconnect). Awaited inline, the
cancellation interrupted it before player_disconnected went out,
and the seat stayed marked connected to a dead peer.
hello_message
¶
hello_message(registry: RoomRegistry, heartbeat_seconds: float) -> dict[str, Any]
Build the first message a connection receives.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
RoomRegistry
|
The server's registry. |
required |
heartbeat_seconds
|
float
|
How often the server pings; the client's own watchdog should allow a few of these. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
dict[str, Any]
|
the room size, the grace window and the heartbeat cadence. |
ping_message
¶
Build the heartbeat ping of the room protocol.
The same object on every transport: the TCP server sends it from its
own pinger, and the WebSocket router hands it to
:func:~tempest_fastapi_sdk.websockets.heartbeat in place of that
primitive's default {"type", "data", "request_id"} envelope. Until
v0.370.0 the WebSocket side sent the envelope, so a client written for
one transport saw a different ping on the other.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
make_game_room_router
¶
make_game_room_router(
registry: RoomRegistry,
*,
settings: WebSocketSettings,
path: str = DEFAULT_GAME_ROOM_PATH,
tags: list[str] | None = None,
) -> APIRouter
Build the router of a game room server.
One endpoint. With an identity resolver on the registry, the token comes
in ?token= and a missing or bad one is closed with 4401 before
the handshake completes; without one, players are guests.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
RoomRegistry
|
The rooms; one per game server. |
required |
settings
|
WebSocketSettings
|
|
required |
path
|
str
|
Mount path. |
DEFAULT_GAME_ROOM_PATH
|
tags
|
list[str] | None
|
OpenAPI tags; defaults to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready for |
make_jwt_room_identity_resolver
¶
make_jwt_room_identity_resolver(
tokens: JWTUtils,
*,
name_claim: str = "name",
accepted: Collection[str] = (ACCESS_TOKEN_TYPE,),
strict: bool = True,
) -> IdentityResolver
Build the identity resolver for access tokens signed by tokens.
Built on :func:~tempest_fastapi_sdk.make_jwt_bearer_resolver, so it
refuses what that one refuses: an expired or forged token, and — the
reason not to hand-write decode + sub — a refresh token or an
MFA-pending token signed by the same secret, which carry sub too.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tokens
|
JWTUtils
|
The helper that signs the application's access tokens. |
required |
name_claim
|
str
|
Claim holding the display name; missing or not a
string falls back to the room's |
'name'
|
accepted
|
Collection[str]
|
Token types that may join a room. |
(ACCESS_TOKEN_TYPE,)
|
strict
|
bool
|
Refuse a token whose type cannot be determined. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
IdentityResolver |
IdentityResolver
|
Maps a token to a :class: |
IdentityResolver
|
|
WebSocketRoomPeer
¶
A :class:~tempest_fastapi_sdk.rooms.RoomPeer over a FastAPI socket.
Attributes:
| Name | Type | Description |
|---|---|---|
ws |
WebSocket
|
The accepted socket. |
Wrap a socket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ws
|
WebSocket
|
An accepted socket. |
required |
send_json
async
¶
Send one control message as a text frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
dict[str, Any]
|
The message. |
required |
send_bytes
async
¶
Send one binary relay frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The frame. |
required |
close
async
¶
Close the socket.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
int
|
Close code. |
required |
reason
|
str
|
Short reason. |
required |
DEFAULT_GAME_ROOM_PATH
module-attribute
¶
Where :func:make_game_room_router mounts its endpoint by default.
UNAUTHORIZED_CLOSE_CODE
module-attribute
¶
Close code for a handshake without a valid token, when one is required.
serve_game_rooms_tcp
async
¶
serve_game_rooms_tcp(
registry: RoomRegistry,
*,
host: str = "127.0.0.1",
port: int = 47200,
heartbeat_seconds: float = 15.0,
heartbeat_timeout_seconds: float = 45.0,
max_frame_bytes: int = DEFAULT_MAX_FRAME_BYTES,
) -> Server
Start a TCP game room server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
registry
|
RoomRegistry
|
The rooms; share it with
:func: |
required |
host
|
str
|
Interface to bind; |
'127.0.0.1'
|
port
|
int
|
TCP port; |
47200
|
heartbeat_seconds
|
float
|
How often the server pings. |
15.0
|
heartbeat_timeout_seconds
|
float
|
Silence tolerated before closing. |
45.0
|
max_frame_bytes
|
int
|
Largest payload accepted; a larger header closes the connection. |
DEFAULT_MAX_FRAME_BYTES
|
Returns:
| Type | Description |
|---|---|
Server
|
asyncio.Server: The listening server; |
Raises:
| Type | Description |
|---|---|
ValueError
|
When the timeout is not above the heartbeat interval. |
encode_frame
¶
Frame one message for the TCP protocol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
kind
|
int
|
:data: |
required |
payload
|
bytes
|
The message. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
|
read_frame
async
¶
read_frame(
reader: StreamReader, *, max_frame_bytes: int = DEFAULT_MAX_FRAME_BYTES
) -> tuple[int, bytes]
Read one frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
reader
|
StreamReader
|
The stream. |
required |
max_frame_bytes
|
int
|
Largest payload accepted. |
DEFAULT_MAX_FRAME_BYTES
|
Returns:
| Type | Description |
|---|---|
tuple[int, bytes]
|
tuple[int, bytes]: |
Raises:
| Type | Description |
|---|---|
IncompleteReadError
|
When the stream ends mid-frame. |
FrameTooLargeError
|
When the header announces more than
|
TCPRoomPeer
¶
A :class:~tempest_fastapi_sdk.rooms.RoomPeer over a TCP stream.
Attributes:
| Name | Type | Description |
|---|---|---|
writer |
StreamWriter
|
The stream. |
Wrap a stream.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
writer
|
StreamWriter
|
The stream. |
required |
send_json
async
¶
Send one control message.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
dict[str, Any]
|
The message. |
required |
send_bytes
async
¶
Send one binary relay frame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
The frame. |
required |
close
async
¶
Say why, then close the stream.
Sends {"type": "close", "code": code, "reason": reason} as a JSON
frame, because a raw stream has no close code of its own, and then
closes; a write failure is ignored, the stream closes anyway.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code
|
int
|
Close code, sent in a |
required |
reason
|
str
|
Short reason. |
required |
FrameTooLargeError
¶
Bases: ValueError
A frame announced a payload above the server's limit.
FRAME_HEADER
module-attribute
¶
[u32 payload length][u8 kind], big-endian.
FRAME_JSON
module-attribute
¶
Frame kind of a UTF-8 JSON control message.
DEFAULT_MAX_FRAME_BYTES
module-attribute
¶
Largest payload :func:serve_game_rooms_tcp accepts by default.
RoomError
¶
Bases: Exception
A request the room server refused.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
Stable identifier the client dispatches on. |
message |
str
|
Human-readable description. |
Build the refusal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable description. |
required |