tempestweb.server¶
O host do Modo B: create_app monta o app FastAPI com as rotas WebSocket e SSE, SecurityConfig liga autenticação, origem e limites de carga, e o RedisSessionRouter dispensa sticky session no SSE. É o que você importa no server.py de um deploy.
Guia com exemplos: Deploy em produção · Segurança (Modo B).
tempestweb.server ¶
tempestweb.server — Mode B FastAPI host (WebSocket + SSE) and WebPush.
Re-exports the server factory/class and the WebPush service (P3). See
docs/plan.md (Trilhos B e P) and docs/contract.md for the wire format
carried over both transports.
TempestWebServer ¶
Bases: Generic[S]
Holds the app definition and the live SSE session registry.
S is the application state type.
Attributes:
| Name | Type | Description |
|---|---|---|
api |
FastAPI
|
The FastAPI application instance with the routes mounted. |
Source code in tempestweb/server/app.py
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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 | |
Credentials
dataclass
¶
The authentication material extracted from a connection.
Attributes:
| Name | Type | Description |
|---|---|---|
token |
str | None
|
The bearer token — from |
origin |
str | None
|
The request |
headers |
Mapping[str, str]
|
The request headers (lower-cased keys). |
query |
Mapping[str, str]
|
The request query parameters. |
Source code in tempestweb/server/security.py
SecurityConfig
dataclass
¶
Opt-in security controls for the Mode B host.
Attributes:
| Name | Type | Description |
|---|---|---|
authenticate |
Authenticate | None
|
Run on every WS upgrade / SSE request before a session is
created; a falsy return or a raised error rejects the connection.
|
trusted_proxies |
list[str] | None
|
Peer addresses whose |
allowed_origins |
list[str] | None
|
If set, the exact |
max_connections |
int | None
|
Cap on concurrent live sessions (WS + SSE combined). A
connection over the cap is refused (WS close |
max_message_bytes |
int | None
|
Reject an SSE |
max_connections_per_minute |
int | None
|
Per-client-IP cap on new connections in a
rolling 60s window; a flood is refused (WS |
max_events_per_minute |
int | None
|
Per-client-IP cap on inbound envelopes in a
rolling 60s window — clicks, input, |
security_headers |
bool
|
When |
hsts |
bool
|
When |
content_security_policy |
str | None
|
An explicit |
Source code in tempestweb/server/security.py
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 | |
header_values ¶
The hardening response headers implied by this config (S6).
Source code in tempestweb/server/security.py
origin_allowed ¶
Whether origin may connect under this config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
origin
|
str | None
|
The request |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
|
Source code in tempestweb/server/security.py
InProcessRouter ¶
Single-instance router: an inbound event feeds the local transport only.
Source code in tempestweb/server/sessions.py
bind
async
¶
No cross-instance delivery is needed in-process.
Source code in tempestweb/server/sessions.py
deliver
async
¶
Feed the local transport; report False when the session is remote.
Source code in tempestweb/server/sessions.py
RedisSessionRouter ¶
Cross-instance SSE router over Redis pub/sub (drops the sticky need).
Each session maps to a channel <prefix><session_id>. The instance holding
the stream subscribes and feeds its transport; a POST on any instance
publishes to the channel (or feeds directly when the session is local).
Source code in tempestweb/server/sessions.py
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 | |
from_url
classmethod
¶
Build a router from a Redis URL (requires the [cache] extra).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
A |
required |
prefix
|
str
|
The channel key prefix. |
'tw:sse:'
|
Returns:
| Type | Description |
|---|---|
RedisSessionRouter
|
A configured :class: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in tempestweb/server/sessions.py
bind
async
¶
Subscribe to the session's channel and feed the transport.
Source code in tempestweb/server/sessions.py
deliver
async
¶
Feed a local transport directly, else publish for the holding instance.
PUBLISH answers with the number of subscribers that received the
message, and that is the only evidence available that some instance still
holds the session. Reporting success unconditionally (as this used to)
turned every post for a session that had already ended into a silent
204: the client believed its click had been delivered and the event
was gone.
Source code in tempestweb/server/sessions.py
SessionRouter ¶
Bases: Protocol
Routes SSE inbound events to the transport holding the stream.
Source code in tempestweb/server/sessions.py
bind
async
¶
Start delivering inbound events for session_id to transport.
Called when an SSE stream opens on this instance. Returns a teardown coroutine to call when the stream closes.
Source code in tempestweb/server/sessions.py
deliver
async
¶
Deliver one inbound envelope for session_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
The target session. |
required |
envelope
|
dict[str, Any]
|
The wire envelope (event / native_result). |
required |
local
|
SSETransport | None
|
The transport on this instance, or |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
could not be routed (the caller returns |
Source code in tempestweb/server/sessions.py
InMemorySubscriptionStore
dataclass
¶
A simple in-memory subscription store (dev/tests).
Subscriptions are keyed by their push endpoint so re-subscribing the same
browser replaces, never duplicates. Each stored record carries its owner.
Attributes:
| Name | Type | Description |
|---|---|---|
_by_endpoint |
dict[str, dict[str, Any]]
|
Internal endpoint -> {owner, subscription} mapping. |
Source code in tempestweb/server/webpush.py
add ¶
Persist (or replace) a subscription for an owner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
owner
|
str
|
The owning user/topic identifier. |
required |
subscription
|
SubscriptionInfo
|
The browser push subscription JSON (needs |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the subscription has no |
Source code in tempestweb/server/webpush.py
remove ¶
Remove a subscription by endpoint.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
The push endpoint URL. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True when a subscription was removed, False when absent. |
Source code in tempestweb/server/webpush.py
list_for ¶
Return all subscriptions for an owner.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
owner
|
str
|
The owning identifier. |
required |
Returns:
| Type | Description |
|---|---|
list[SubscriptionInfo]
|
The subscriptions ([] when the owner has none). |
Source code in tempestweb/server/webpush.py
all ¶
Return every stored subscription.
Returns:
| Type | Description |
|---|---|
list[SubscriptionInfo]
|
All subscriptions ([] when empty). |
SendOutcome
dataclass
¶
The result of attempting to send to one subscription.
Attributes:
| Name | Type | Description |
|---|---|---|
endpoint |
str
|
The target push endpoint. |
ok |
bool
|
Whether the push was accepted. |
status_code |
int | None
|
The push service HTTP status (when known), and |
gone |
bool
|
Whether the endpoint is dead (HTTP 410/404) and was pruned. |
error |
str | None
|
A human-readable error when |
Source code in tempestweb/server/webpush.py
SubscriptionStore ¶
Bases: Protocol
Storage protocol for push subscriptions keyed by endpoint.
A host app supplies a real implementation (SQLAlchemy, Redis, …); the default
InMemorySubscriptionStore covers tests and single-process dev.
Source code in tempestweb/server/webpush.py
VapidConfig
dataclass
¶
VAPID credentials and contact for signing WebPush requests.
Attributes:
| Name | Type | Description |
|---|---|---|
public_key |
str
|
Base64url VAPID public key (shared with the browser client). |
private_key |
str
|
Base64url VAPID private key (secret; empty disables sending). |
subject |
str
|
VAPID |
Source code in tempestweb/server/webpush.py
enabled
property
¶
Whether sending is enabled (a private key is configured).
Returns:
| Type | Description |
|---|---|
bool
|
True when a non-empty private key is present. |
from_env
classmethod
¶
Build a config from environment variables.
Reads <prefix>PUBLIC_KEY, <prefix>PRIVATE_KEY and
<prefix>SUBJECT. Missing values fall back to the dataclass defaults.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prefix
|
str
|
Environment variable prefix. |
'VAPID_'
|
Returns:
| Type | Description |
|---|---|
VapidConfig
|
The populated config. |
Source code in tempestweb/server/webpush.py
VapidKeys
dataclass
¶
A freshly generated VAPID keypair (base64url, unpadded).
Attributes:
| Name | Type | Description |
|---|---|---|
public_key |
str
|
The application server key the browser subscribes with (65-byte uncompressed P-256 point). |
private_key |
str
|
The signing key the server keeps secret (32-byte scalar). |
Source code in tempestweb/server/webpush.py
WebPushError ¶
Bases: Exception
Raised by a sender to signal a push delivery failure.
Attributes:
| Name | Type | Description |
|---|---|---|
status_code |
The push service HTTP status, when available. |
Source code in tempestweb/server/webpush.py
WebPushService ¶
Owns the subscription store and sends VAPID-signed push messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vapid
|
VapidConfig
|
The VAPID configuration. |
required |
store
|
SubscriptionStore | None
|
The subscription store (defaults to in-memory). |
None
|
sender
|
WebPushSender | None
|
The push sender callable (defaults to |
None
|
timeout
|
float
|
Per-send HTTP timeout in seconds, forwarded to the sender.
|
10.0
|
Source code in tempestweb/server/webpush.py
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 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 | |
add_subscription ¶
Persist a browser push subscription for an owner (POST /webpush/subscribe).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
owner
|
str
|
The owning user/topic identifier. |
required |
subscription
|
SubscriptionInfo
|
The browser push subscription JSON. |
required |
Source code in tempestweb/server/webpush.py
remove_subscription ¶
Remove a subscription by endpoint (DELETE /webpush/my).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
The push endpoint URL. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Whether a subscription was removed. |
Source code in tempestweb/server/webpush.py
send ¶
Send one VAPID-signed push to a single subscription.
A dead endpoint (HTTP 410/404) is pruned from the store and reported with
gone=True; a store that fails while pruning is ignored, so one dead
endpoint cannot cancel delivery to the live ones. Sending is a no-op
success-free outcome when VAPID is disabled (no private key), so dev
environments degrade cleanly.
The call blocks (pywebpush posts with requests) and is
bounded by self.timeout. An async caller must run it off the
loop; webpush_router's /send route goes through
run_in_threadpool for exactly that reason.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subscription
|
SubscriptionInfo
|
The target subscription JSON (needs |
required |
payload
|
dict[str, Any]
|
The JSON-able notification payload (title/body/data/...). |
required |
Returns:
| Type | Description |
|---|---|
SendOutcome
|
The send outcome, carrying the status the push service answered (or |
SendOutcome
|
None when the sender exposes no response). |
Source code in tempestweb/server/webpush.py
send_to_owner ¶
Send a push to every subscription an owner has.
Returns [] when the owner has no subscriptions (never an error).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
owner
|
str
|
The owning identifier. |
required |
payload
|
dict[str, Any]
|
The notification payload. |
required |
Returns:
| Type | Description |
|---|---|
list[SendOutcome]
|
One outcome per subscription ([] when the owner has none). |
Source code in tempestweb/server/webpush.py
broadcast ¶
Send a push to every stored subscription.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
payload
|
dict[str, Any]
|
The notification payload. |
required |
Returns:
| Type | Description |
|---|---|
list[SendOutcome]
|
One outcome per subscription ([] when the store is empty). |
Source code in tempestweb/server/webpush.py
create_app ¶
create_app(state_factory: Callable[[], S], view: Callable[[App[S]], Widget], *, title: str = 'tempestweb', security: SecurityConfig | None = None, metrics: bool = False, observability: ServerObservability | None = None, sse_backend: SessionRouter | None = None, concurrent_dispatch: bool = False, theme: Theme | None = None) -> FastAPI
Build a Mode B FastAPI app for a view and state factory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_factory
|
Callable[[], S]
|
Builds a fresh state per connection (isolation). |
required |
view
|
Callable[[App[S]], Widget]
|
The shared |
required |
title
|
str
|
OpenAPI title for the FastAPI app. |
'tempestweb'
|
security
|
SecurityConfig | None
|
Opt-in auth + origin controls (Track S — S0/S1/S3). |
None
|
metrics
|
bool
|
When |
False
|
observability
|
ServerObservability | None
|
Patch latency, structured session logs and tracing (S8).
|
None
|
sse_backend
|
SessionRouter | None
|
SSE inbound router (Track S — S4). |
None
|
concurrent_dispatch
|
bool
|
Dispatch each event as its own task (ordered per
widget key) instead of one at a time, so a slow handler cannot freeze
the connection. Off by default; |
False
|
theme
|
Theme | None
|
The palette every component resolves its colors against.
|
None
|
Returns:
| Type | Description |
|---|---|
FastAPI
|
The configured FastAPI application with WS and SSE routes mounted. |
Source code in tempestweb/server/app.py
jwt_authenticator ¶
jwt_authenticator(key: str, *, algorithms: tuple[str, ...] = ('HS256',), audience: str | None = None, issuer: str | None = None, require_expiry: bool = True) -> Authenticate
Build an authenticate callable that verifies a bearer JWT (S3).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The signing key / secret. |
required |
algorithms
|
tuple[str, ...]
|
Accepted signing algorithms. |
('HS256',)
|
audience
|
str | None
|
Expected |
None
|
issuer
|
str | None
|
Expected |
None
|
require_expiry
|
bool
|
Refuse a token with no |
True
|
Returns:
| Type | Description |
|---|---|
Authenticate
|
A predicate that accepts a connection with a valid, unexpired JWT. |
Source code in tempestweb/server/security.py
token_authenticator ¶
Build an authenticate callable for a shared-secret token.
Compares the connection's bearer token to secret with a constant-time
check (the X-Token convention). An empty secret disables the gate
(always allows) — dev-only, matching the framework's "empty secret disables
auth" rule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
secret
|
str
|
The shared secret; empty disables the gate. |
required |
Returns:
| Type | Description |
|---|---|
Authenticate
|
A predicate that accepts a connection whose token equals |
Source code in tempestweb/server/security.py
verify_jwt ¶
verify_jwt(token: str, key: str, *, algorithms: tuple[str, ...] = ('HS256',), audience: str | None = None, issuer: str | None = None, require_expiry: bool = True) -> dict[str, Any]
Verify a JWT's signature and expiry, returning its claims.
Unlike observability.auth.decode_jwt (which only base64url-decodes the
payload), this validates the signature and standard time claims.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The compact-serialization JWT. |
required |
key
|
str
|
The signing key / secret. |
required |
algorithms
|
tuple[str, ...]
|
Accepted signing algorithms. |
('HS256',)
|
audience
|
str | None
|
Expected |
None
|
issuer
|
str | None
|
Expected |
None
|
require_expiry
|
bool
|
Refuse a token that carries no |
True
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
The verified claims. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If PyJWT is not installed. |
ValueError
|
If the token is invalid, expired, missing a required claim, or fails a claim check. |
Source code in tempestweb/server/security.py
generate_vapid_keys ¶
Generate a P-256 VAPID keypair for WebPush.
The public key is the browser applicationServerKey and the private key
signs push requests server-side. Store the private key as a secret (env var)
— never commit it.
Returns:
| Type | Description |
|---|---|
VapidKeys
|
The base64url-encoded :class: |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in tempestweb/server/webpush.py
webpush_router ¶
Build a FastAPI router exposing the WebPush subscribe/send endpoints.
Mount it on a host app with app.include_router(webpush_router(service)).
Endpoints (all JSON):
GET {prefix}/vapid-public-key→{"public_key": ...}for the client to subscribe with.POST {prefix}/subscribe(body: the browser subscription JSON) → stores it underowner.POST {prefix}/unsubscribe(body:{"endpoint": ...}) → removes it, only when thisownerholds it; a body with noendpointanswers 400, like/subscribealready did.POST {prefix}/send(body: the notification payload) → pushes to every subscription ofowner; returns{"sent", "total"}. The blocking send runs in a worker thread, so it never stalls the event loop.
A single fixed owner keeps the default multi-tenant-free; an app with
real users wires its own routes around the same :class:WebPushService,
resolving the owner from auth.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service
|
WebPushService
|
The WebPush service (store + sender). |
required |
owner
|
str
|
The owner every subscription is filed under (default |
'default'
|
prefix
|
str
|
The route prefix. |
'/webpush'
|
Returns:
| Type | Description |
|---|---|
Any
|
A configured |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If FastAPI is not installed. |
Source code in tempestweb/server/webpush.py
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 | |