API Reference: SocketApp¶
socketspec.app.SocketApp
¶
FastAPI-style WebSocket application entry point.
Source code in src\socketspec\app.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | |
handle_connect(raw_socket, headers, query_params)
async
¶
Accept and register a new WebSocket connection.
Source code in src\socketspec\app.py
handle_disconnect(conn, reason='client_close')
async
¶
Tear down a connection and run lifecycle cleanup.
Source code in src\socketspec\app.py
handle_event(conn, raw_message)
async
¶
Handle one inbound client message.
Source code in src\socketspec\app.py
middleware(func)
¶
on(event, *, description='', tags=None, emits=None, broadcasts=None, ordered=False, executor=False, deprecated=False)
¶
Register an event handler.
Source code in src\socketspec\app.py
on_connect(func)
¶
on_disconnect(func)
¶
on_error(func)
¶
on_room_join(func)
¶
on_room_leave(func)
¶
Register a hook that runs after a connection leaves a room.
room_guard(pattern)
¶
Protect a room name pattern with a permission function.
Source code in src\socketspec\app.py
Constructor Parameters¶
| Parameter | Type | Default | Description |
|---|---|---|---|
docs |
bool |
False |
Enable the /socket-docs interactive UI |
docs_url |
str |
"/socket-docs" |
URL path for the docs UI |
docs_access_token |
str \| None |
None |
Bearer token required to access the docs UI |
auth |
AuthBackend \| None |
None |
Authentication backend (JWTAuth, APIKeyAuth, or custom) |
backend |
"memory" \| BackendAdapter |
"memory" |
Storage backend for connections and rooms |
allowed_origins |
list[str] \| None |
["*"] |
Allowed WebSocket origin headers |
max_payload_size |
int |
65536 |
Maximum inbound payload size in bytes |
rate_limit |
RateLimit \| None |
None |
Token bucket rate limit per connection |
session |
SessionConfig \| None |
SessionConfig() |
Heartbeat and TTL configuration |
rooms |
list[Room] \| None |
None |
Static rooms to create at startup |
namespace |
str |
"/" |
Namespace prefix for all events |
Event Registration¶
@socket.on(event, *, ...)¶
Register an event handler.
@socket.on(
"send_message",
description="Send a chat message.",
tags=["chat"],
emits=[Emits("message_ack", model=AckModel)],
broadcasts=[Broadcasts("new_message", room="chat:{room}", model=MsgModel)],
ordered=False,
deprecated=False,
)
async def handler(conn: Connection, payload: MyModel) -> None: ...
| Parameter | Type | Default | Description |
|---|---|---|---|
event |
str |
— | Event name. Cannot be a reserved system event. |
description |
str |
"" |
Shown in the docs UI |
tags |
list[str] |
[] |
Group events in the docs UI |
emits |
list[Emits] |
[] |
Metadata: events the handler emits back to sender |
broadcasts |
list[Broadcasts] |
[] |
Metadata: events the handler broadcasts to rooms |
ordered |
bool |
False |
If True, events from this connection are processed sequentially |
deprecated |
bool |
False |
Shows ⚠ DEPRECATED badge in the docs UI |
Lifecycle Decorators¶
@socket.on_connect¶
Runs after a connection is established. Receives conn: Connection.
@socket.on_disconnect¶
Runs after a connection closes. Receives conn: Connection, reason: str.
@socket.on_error¶
Runs when a handler raises an unhandled exception. Receives conn: Connection, error: Exception.
@socket.on_room_join¶
Runs after a connection joins a room. Receives conn: Connection, room: str.
@socket.on_room_leave¶
Runs after a connection leaves a room. Receives conn: Connection, room: str.
@socket.room_guard(pattern)¶
Register a room permission guard for a name pattern.
@socket.room_guard("admin:{section}")
async def guard(conn: Connection, section: str) -> bool:
return conn.identity.role == "admin"
@socket.middleware¶
Register middleware that wraps every event handler.
@socket.middleware
async def log_events(conn, event, payload, next_handler):
print(f"[{conn.id}] {event}")
await next_handler(conn, event, payload)
System Events (Reserved)¶
These events are used internally. You cannot register handlers for them.
| Event | Direction | Description |
|---|---|---|
__connect__ |
Server → Client | Connection established |
__disconnect__ |
Server → Client | Connection closing |
__ping__ |
Server → Client | Heartbeat ping |
__pong__ |
Client → Server | Heartbeat response |
__error__ |
Server → Client | Error envelope |
__auth_expiring__ |
Server → Client | JWT near expiry |
__session_expiring__ |
Server → Client | Session max-duration reached |
__idle_warning__ |
Server → Client | Idle timeout reached |
__server_shutdown__ |
Server → Client | Server is shutting down |
__refresh_auth__ |
Client → Server | Client requests token refresh |
Error Codes¶
All errors are delivered in the __error__ envelope:
{
"event": "__error__",
"payload": {
"code": "VALIDATION_ERROR",
"message": "...",
"request_id": "uuid",
"details": {}
}
}
| Code | Trigger |
|---|---|
AUTH_ERROR |
Authentication failed at connect time |
AUTH_EXPIRED |
JWT expired mid-session |
HANDLER_ERROR |
Unhandled exception in event handler |
IDLE_TIMEOUT |
Connection was idle too long |
PAYLOAD_TOO_LARGE |
Payload exceeded max_payload_size |
PERMISSION_ERROR |
Room guard returned False |
RATE_LIMIT_ERROR |
Token bucket exhausted |
ROOM_NOT_FOUND |
Broadcast to a non-existent room |
SESSION_EXPIRED |
max_duration reached |
UNKNOWN_EVENT |
No handler registered for this event |
VALIDATION_ERROR |
JSON parse failure or Pydantic validation failure |