Ir para o conteúdo

tempest_fastapi_sdk.rooms

Salas multiplayer online: um servidor de relay para jogos, sobre WebSocket ou TCP.

« Tempo real e mensageria


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 uses the defaults.

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 admits guests, each given a random player id.

None
clock Callable[[], float]

Monotonic time source for the rate limit (tests).

monotonic

requires_identity property

requires_identity: bool

Whether connections must present a valid token.

Returns:

Name Type Description
bool bool

True when an identity resolver was given.

room_count property

room_count: int

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 None.

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 None for a guest when no

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 max_rooms rooms are open.

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 welcome.

required
resume_token str

The resume token from welcome.

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 for everyone else.

None

Raises:

Type Description
RateLimitedError

Over the rate limit.

MessageNotAllowedError

When an allow list is set and data is not an object with an allowed type.

PlayerNotFoundError

When to is not in the room.

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:BROADCAST_SLOT.

required
payload bytes

Opaque bytes, relayed as is.

required

Raises:

Type Description
RateLimitedError

Over the rate limit.

PlayerNotFoundError

When slot is empty.

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, 2 to 255.

protocol_version str | None

Version every client must announce on create / join; a mismatch is refused with version_mismatch. None accepts any.

reconnect_grace_seconds float

How long a dropped player's seat is kept for a resume; 0 removes it at once.

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, 4 to 12.

lock_when_playing bool

Refuse join while the room is playing; a resume is always allowed.

allowed_message_types frozenset[str] | None

When set, a relayed JSON data must be an object whose type is listed here.

max_name_length int

Characters kept of a player name.

Raises:

Type Description
ValueError

When a bound is out of range.

RoomIdentity dataclass

RoomIdentity(player_id: str, name: str)

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

lobby or playing.

snapshot

snapshot() -> dict[str, Any]

Describe the room for its players.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: code, host_id, state,

dict[str, Any]

max_players and players by slot.

free_slot

free_slot() -> int | None

Return the lowest free slot.

Returns:

Type Description
int | None

int | None: The slot, or None when the room is full.

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 None for an empty slot.

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, 0 to max_players - 1; addresses binary frames.

resume_token str

Secret a dropped connection presents to resume.

peer RoomPeer | None

The live connection; None while dropped.

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 rate_limited sent.

grace_task Task[None] | None

Pending removal of a dropped player.

connected property

connected: bool

Whether the player has a live connection.

Returns:

Name Type Description
bool bool

True while peer is set.

public

public() -> dict[str, Any]

Describe the player for the other players.

Returns:

Type Description
dict[str, Any]

dict[str, Any]: player_id, name, slot, connected.

RoomState module-attribute

RoomState = Literal['lobby', 'playing']

lobby takes new players; playing refuses them by default.

RoomPeer

Bases: Protocol

One live connection, whatever its transport.

send_json async

send_json(message: dict[str, Any]) -> None

Send one control message.

Parameters:

Name Type Description Default
message dict[str, Any]

The message.

required

send_bytes async

send_bytes(data: bytes) -> None

Send one binary relay frame.

Parameters:

Name Type Description Default
data bytes

[u8 sender slot][payload].

required

close async

close(code: int, reason: str) -> None

Close the connection.

Parameters:

Name Type Description Default
code int

Close code.

required
reason str

Short reason.

required

BROADCAST_SLOT module-attribute

BROADCAST_SLOT: Final[int] = 255

Destination slot of a binary frame meant for every other player.

REPLACED_CLOSE_CODE module-attribute

REPLACED_CLOSE_CODE: Final[int] = 4409

Close code sent to a connection whose player resumed on another one.

ROOM_CODE_ALPHABET module-attribute

ROOM_CODE_ALPHABET: Final[str] = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'

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 ?token=); None resolves the token field of create / join when the registry requires one.

None

handle_text async

handle_text(raw: str) -> None

Handle one text frame.

Parameters:

Name Type Description Default
raw str

The frame, expected to be a JSON object.

required

handle_json async

handle_json(message: object) -> None

Handle one decoded control message.

Parameters:

Name Type Description Default
message object

The decoded frame.

required

handle_binary async

handle_binary(data: bytes) -> None

Handle one binary relay frame.

Parameters:

Name Type Description Default
data bytes

[u8 destination slot][payload].

required

close async

close() -> None

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.

refuse async

refuse(error: RoomError, request: str | None) -> None

Answer a refusal without closing the connection.

Parameters:

Name Type Description Default
error RoomError

The refusal.

required
request str | None

The type that was refused.

required

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]: {"type": "hello", ...} with the protocol version,

dict[str, Any]

the room size, the grace window and the heartbeat cadence.

ping_message

ping_message() -> dict[str, Any]

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]: {"type": "ping"}, a fresh dict per call.

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

WS_HEARTBEAT_SECONDS, WS_HEARTBEAT_TIMEOUT_SECONDS and WS_MAX_MESSAGE_BYTES (a larger frame is closed with 1009).

required
path str

Mount path.

DEFAULT_GAME_ROOM_PATH
tags list[str] | None

OpenAPI tags; defaults to ["rooms"].

None

Returns:

Name Type Description
APIRouter APIRouter

Ready for app.include_router.

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 "Player <n>".

'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:RoomIdentity whose

IdentityResolver

player_id is the token's UUID subject, or None.

WebSocketRoomPeer

WebSocketRoomPeer(ws: WebSocket)

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_json(message: dict[str, Any]) -> None

Send one control message as a text frame.

Parameters:

Name Type Description Default
message dict[str, Any]

The message.

required

send_bytes async

send_bytes(data: bytes) -> None

Send one binary relay frame.

Parameters:

Name Type Description Default
data bytes

The frame.

required

close async

close(code: int, reason: str) -> None

Close the socket.

Parameters:

Name Type Description Default
code int

Close code.

required
reason str

Short reason.

required

DEFAULT_GAME_ROOM_PATH module-attribute

DEFAULT_GAME_ROOM_PATH: str = '/rooms/ws'

Where :func:make_game_room_router mounts its endpoint by default.

UNAUTHORIZED_CLOSE_CODE module-attribute

UNAUTHORIZED_CLOSE_CODE: int = 4401

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:~tempest_fastapi_sdk.rooms.make_game_room_router to put TCP and WebSocket players in the same rooms.

required
host str

Interface to bind; "0.0.0.0" to accept phones on the network.

'127.0.0.1'
port int

TCP port; 0 picks a free one (read it from server.sockets[0].getsockname()).

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; close() it on shutdown.

Raises:

Type Description
ValueError

When the timeout is not above the heartbeat interval.

encode_frame

encode_frame(kind: int, payload: bytes) -> bytes

Frame one message for the TCP protocol.

Parameters:

Name Type Description Default
kind int

:data:FRAME_JSON or :data:FRAME_BINARY.

required
payload bytes

The message.

required

Returns:

Name Type Description
bytes bytes

header + payload.

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]: (kind, payload).

Raises:

Type Description
IncompleteReadError

When the stream ends mid-frame.

FrameTooLargeError

When the header announces more than max_frame_bytes; nothing more is read.

TCPRoomPeer

TCPRoomPeer(writer: StreamWriter)

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_json(message: dict[str, Any]) -> None

Send one control message.

Parameters:

Name Type Description Default
message dict[str, Any]

The message.

required

send_bytes async

send_bytes(data: bytes) -> None

Send one binary relay frame.

Parameters:

Name Type Description Default
data bytes

The frame.

required

close async

close(code: int, reason: str) -> None

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 {"type": "close"} message.

required
reason str

Short reason.

required

FrameTooLargeError

Bases: ValueError

A frame announced a payload above the server's limit.

FRAME_HEADER module-attribute

FRAME_HEADER: Final[Struct] = struct.Struct('!IB')

[u32 payload length][u8 kind], big-endian.

FRAME_JSON module-attribute

FRAME_JSON: Final[int] = 0

Frame kind of a UTF-8 JSON control message.

FRAME_BINARY module-attribute

FRAME_BINARY: Final[int] = 1

Frame kind of a binary relay frame.

DEFAULT_MAX_FRAME_BYTES module-attribute

DEFAULT_MAX_FRAME_BYTES: Final[int] = 65536

Largest payload :func:serve_game_rooms_tcp accepts by default.

RoomError

RoomError(message: str)

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

RoomNotFoundError

RoomNotFoundError(message: str)

Bases: RoomError

No room has that code (or it closed).

RoomFullError

RoomFullError(message: str)

Bases: RoomError

Every slot of the room is taken.

RoomInMatchError

RoomInMatchError(message: str)

Bases: RoomError

The room is playing and does not take new players.

ServerFullError

ServerFullError(message: str)

Bases: RoomError

The server already holds its maximum number of rooms.

ProtocolVersionError

ProtocolVersionError(message: str)

Bases: RoomError

The client speaks another protocol version than the server.

NotHostError

NotHostError(message: str)

Bases: RoomError

Only the room's host may do that.

NotInRoomError

NotInRoomError(message: str)

Bases: RoomError

The connection has not created, joined or resumed a room yet.

AlreadyInRoomError

AlreadyInRoomError(message: str)

Bases: RoomError

The connection is already in a room; leave it first.

PlayerNotFoundError

PlayerNotFoundError(message: str)

Bases: RoomError

The addressed player is not in the room.

ResumeRejectedError

ResumeRejectedError(message: str)

Bases: RoomError

The resume token does not match, or the grace window ran out.

RateLimitedError

RateLimitedError(message: str)

Bases: RoomError

The player sent more messages than the policy allows.

MessageNotAllowedError

MessageNotAllowedError(message: str)

Bases: RoomError

The relayed message's type is not on the policy's allow list.

UnauthorizedError

UnauthorizedError(message: str)

Bases: RoomError

The server requires an identity token and none (or a bad one) came.

BadRequestError

BadRequestError(message: str)

Bases: RoomError

The frame is not a message the protocol defines.