Ir para o conteúdo

tempest_fastapi_sdk.webpush

Web Push (VAPID): envio e schemas de inscrição.

« Tempo real e mensageria


WebPushDispatcher

WebPushDispatcher(
    vapid_private_key: str,
    *,
    vapid_subject: str,
    ttl_seconds: int = 60,
    extra_vapid_claims: dict[str, str] | None = None,
    timeout: float = DEFAULT_WEBPUSH_TIMEOUT,
    allow_private_networks: bool = False,
    resolver: Resolver | None = None,
    prune_after_dns_refusals: int | None = DEFAULT_PRUNE_AFTER_DNS_REFUSALS,
    dns_refusal_window_seconds: float = DEFAULT_DNS_REFUSAL_WINDOW_SECONDS,
    clock: Callable[[], float] = monotonic,
)

Send VAPID-signed Web Push notifications to browser subscribers.

Wraps the synchronous pywebpush library in :func:asyncio.to_thread so dispatch fits the SDK's async-first convention. Subscriptions that respond with 404/410 raise :class:WebPushGoneError so the caller can prune their store; every other failure raises :class:WebPushError.

Attributes:

Name Type Description
vapid_private_key str

VAPID private key (PEM or base64url encoded). MUST match the public key advertised to clients.

vapid_claims dict[str, str]

Mandatory JWT claims attached to every push. sub is required (typically mailto:ops@example.com).

ttl_seconds int

Default time-to-live applied to each push (the push service buffers the payload for at most this long when the device is offline).

timeout float

Seconds each dispatch waits to connect and for each read before it fails with :class:WebPushError.

allow_private_networks bool

Whether endpoints resolving to loopback, private, link-local or otherwise non-public addresses are dispatched to.

Initialize the dispatcher.

Parameters:

Name Type Description Default
vapid_private_key str

VAPID private key.

required
vapid_subject str

The sub JWT claim. Browsers expect either a mailto: or https: URI.

required
ttl_seconds int

Default TTL for delivered messages.

60
extra_vapid_claims dict[str, str] | None

Additional claims merged into the JWT.

None
timeout float

Connect and read timeout, in seconds, of every dispatch.

DEFAULT_WEBPUSH_TIMEOUT
allow_private_networks bool

Skip the public-address check, for a self-hosted push service on the internal network. Redirects stay disabled and the timeout still applies. Only turn this on when subscribers are trusted.

False
resolver Resolver | None

Async hostname → addresses lookup used by the public-address check; the first address it returns is the one the dispatch connects to. None uses the event loop's getaddrinfo.

None
prune_after_dns_refusals int | None

How many consecutive :meth:send_many refusals decided by a DNS answer turn an endpoint into one :meth:prune removes. One such refusal is kept, because the answer can change; an endpoint whose host keeps resolving to a non-public address (a rebinding subscription) is otherwise never removed and costs a lookup and a log line on every fan-out. The refusals must also span dns_refusal_window_seconds, so three fan-outs in a row during a passing resolver problem prune nothing. A delivery that goes through resets the count; any other failure (a timeout, a lookup error) neither counts nor resets. An endpoint listed twice in one call counts once. A host of a browser push service (:data:KNOWN_PUSH_SERVICE_HOSTS) is never pruned this way, since its refusal means the deployment's resolver is wrong; a self-hosted push service on the internal network is not in that list, so serve it with allow_private_networks=True (nothing is refused then) or pass None here. The counts live in this instance, bounded to :data:MAX_TRACKED_DNS_REFUSALS endpoints. None disables pruning on DNS refusals.

DEFAULT_PRUNE_AFTER_DNS_REFUSALS
dns_refusal_window_seconds float

Least time, in seconds, between the first counted refusal and the one that prunes.

DEFAULT_DNS_REFUSAL_WINDOW_SECONDS
clock Callable[[], float]

Monotonic time source for the window (tests).

monotonic

Raises:

Type Description
ValueError

When prune_after_dns_refusals is below 1, dns_refusal_window_seconds is negative, or the sub claim (vapid_subject, or a "sub" in extra_vapid_claims) is not mailto:<email> nor https://<host> — the format py_vapid signs with, so the fault surfaces here instead of on the first push (#791).

check_endpoint async

check_endpoint(endpoint: str) -> None

Apply the egress check a dispatch applies, without sending.

The same scheme, public-address and allow_private_networks rules as :meth:send, through the same resolver, so a subscription refused here is exactly one :meth:send would refuse. :func:~tempest_fastapi_sdk.webpush.make_web_push_router calls it before storing an endpoint; the switch that lets a self-hosted push service through stays one switch, on the dispatcher.

Parameters:

Name Type Description Default
endpoint str

The subscription endpoint to judge.

required

Raises:

Type Description
WebPushEndpointRefusedError

When the endpoint is refused.

WebPushError

When the endpoint host cannot be resolved.

send async

send(
    subscription: WebPushSubscriptionSchema,
    payload: WebPushPayloadSchema | dict[str, Any] | str | bytes,
    *,
    ttl_seconds: int | None = None,
    headers: dict[str, str] | None = None,
) -> None

Send a single push notification.

Parameters:

Name Type Description Default
subscription WebPushSubscriptionSchema

The recipient.

required
payload WebPushPayloadSchema | dict | str | bytes

The notification body. Pydantic models and dicts are JSON-encoded; strings/bytes are sent as-is.

required
ttl_seconds int | None

Override :attr:ttl_seconds for this dispatch.

None
headers dict[str, str] | None

Extra HTTP headers to attach to the push request (forwarded to pywebpush).

None

Raises:

Type Description
WebPushGoneError

When the push service reports the subscription as dead — 404/410 anywhere, plus 400 from WNS, which is how Edge's push service spells it. See :func:_is_gone.

WebPushEndpointRefusedError

When the egress check refuses the endpoint (non-public address, not https); no request is sent.

WebPushConfigurationError

When py_vapid refuses to sign the dispatcher's claims (VapidException, a sub it does not accept); no request is sent.

WebPushError

For any other delivery failure, including an unresolvable host, a redirect answer, a timeout and a connection error.

send_many async

send_many(
    subscriptions: list[WebPushSubscriptionSchema],
    payload: WebPushPayloadSchema | dict[str, Any] | str | bytes,
    *,
    ttl_seconds: int | None = None,
    headers: dict[str, str] | None = None,
    max_concurrency: int | None = None,
) -> list[str]

Fan out a single payload to many subscriptions.

Dispatches run concurrently via :func:asyncio.gather. Only subscriptions that can never be delivered are returned — the ones the push service reports as dead, and the ones the egress check refuses permanently (see :attr:WebPushEndpointRefusedError.permanent: not https, or an IP-literal host that is not public). The list is what :meth:prune consumes, so an endpoint that failed for a transient reason must not be in it: a refusal decided by a DNS answer is logged and kept, because the answer can change -- until it repeats prune_after_dns_refusals times in a row across calls, when the endpoint is returned too.

Parameters:

Name Type Description Default
subscriptions list[WebPushSubscriptionSchema]

Recipients.

required
payload WebPushPayloadSchema | dict[str, Any] | str | bytes

The notification body (same shapes as :meth:send).

required
ttl_seconds int | None

Override TTL.

None
headers dict[str, str] | None

Extra HTTP headers.

None
max_concurrency int | None

Cap on dispatches in flight at once. None (the default) keeps the historical behaviour of starting every dispatch immediately, which is right for one user's handful of devices. A global fan-out should pass a bound — every dispatch is a TLS request to a push service, and thousands at once earn a rate limit rather than a faster send. Values below 1 are treated as unbounded.

None

Returns:

Type Description
list[str]

list[str]: Endpoints whose subscription is gone and should

list[str]

be removed from the application's store.

Raises:

Type Description
WebPushConfigurationError

When py_vapid refuses to sign the dispatcher's claims. It fails the same way for every subscription, so it is raised rather than logged per subscriber like a delivery failure. Before #791 the raw VapidException escaped instead, untyped.

WebPushEndpointRefusedError

WebPushEndpointRefusedError(
    message: str, *, endpoint: str | None = None, permanent: bool
)

Bases: WebPushError

Raised when the egress policy refuses a subscription endpoint.

The endpoint is not an https URL, or (unless the dispatcher allows private networks) it names or resolves to a loopback, private, link-local or otherwise non-public address. No request was sent.

Attributes:

Name Type Description
permanent bool

True when the refusal follows from the URL itself — the scheme, or a host that is an IP literal — so no later attempt can succeed. False when it follows from a DNS answer, which can change: a resolver that maps a real push service to an internal proxy refuses every endpoint at once, and the store must not lose them all over a configuration slip.

Initialize the refusal.

Parameters:

Name Type Description Default
message str

Human-readable description.

required
endpoint str | None

Subscription endpoint, when known.

None
permanent bool

Whether the URL alone decided the refusal.

required

WebPushConfigurationError

WebPushConfigurationError(
    message: str, *, status_code: int | None = None, endpoint: str | None = None
)

Bases: WebPushError

Raised when the dispatcher's own VAPID configuration cannot sign.

A configuration fault, not a delivery one: it fails the same way for every subscription, so :meth:WebPushDispatcher.send_many raises it rather than logging it per subscriber. The dispatcher checks the sub claim on construction; this covers what that check cannot see, a claim changed afterwards, by turning py_vapid's VapidException into a typed error. A malformed private key is not covered: pywebpush raises binascii.Error (a ValueError) for it, before py_vapid signs anything.

WebPushSubscriptionService

WebPushSubscriptionService(
    repository: BaseRepository[SubscriptionModelT], dispatcher: WebPushDispatcher
)

Bases: Generic[SubscriptionModelT]

Store, prune and deliver Web Push subscriptions.

Generic over the concrete subscription model so it returns the project's own rows. Pair a :class:BaseRepository bound to that model with a configured :class:WebPushDispatcher.

Generic parameters

SubscriptionModelT: The concrete :class:BaseWebPushSubscriptionModel subclass.

Attributes:

Name Type Description
repository BaseRepository[SubscriptionModelT]

Data access for the subscription table.

dispatcher WebPushDispatcher

VAPID-signed sender.

Initialize the service.

Parameters:

Name Type Description Default
repository BaseRepository[SubscriptionModelT]

Repository bound to the concrete subscription model.

required
dispatcher WebPushDispatcher

Configured dispatcher.

required

subscribe async

subscribe(
    user_id: UUID,
    subscription: WebPushSubscriptionSchema,
    *,
    user_agent: str | None = None,
    transfer_ownership: bool = False,
) -> SubscriptionModelT

Persist a subscription, idempotently keyed by endpoint.

The unique endpoint is the device identity. The same owner re-subscribing updates the keys, expiration_time and user_agent of the existing row instead of creating a duplicate.

The endpoint is checked first with :meth:WebPushDispatcher.check_endpoint on :attr:dispatcher: one that dispatcher would refuse to deliver to (not https, or naming or resolving to a loopback, private, link-local or otherwise non-public address) raises :class:PushEndpointNotPublicException and is not stored, so allow_private_networks and resolver on the dispatcher govern registration and delivery alike. A host that does not resolve at that moment is accepted; every send re-checks.

An endpoint already registered to another account is left untouched (#632): knowing an endpoint and supplying keys must not be enough to take a device from its owner, who would stop receiving their own notifications while they are encrypted for the caller. The row comes back unchanged and the routers answer exactly as for a new subscription, so the call cannot tell whether the endpoint belongs to someone else — the same rule :meth:unsubscribe follows. Two accounts on one browser share one PushSubscription: the client unsubscribes on sign-out, before the next account subscribes.

Parameters:

Name Type Description Default
user_id UUID

The user that owns the device.

required
subscription WebPushSubscriptionSchema

The browser PushSubscription.toJSON() payload.

required
user_agent str | None

Optional device label to store.

None
transfer_ownership bool

Move an endpoint registered to another account to user_id. Off by default and never turned on by :func:make_web_push_router unless asked.

False

Returns:

Name Type Description
SubscriptionModelT SubscriptionModelT

The persisted row — created, updated, or,

SubscriptionModelT

for an endpoint of another account, the stored row unchanged.

SubscriptionModelT

Never echo it to the requester.

Raises:

Type Description
PushEndpointNotPublicException

When the dispatcher would refuse the endpoint (HTTP 422).

unsubscribe async

unsubscribe(endpoint: str, *, user_id: UUID | None = None) -> bool

Remove the subscription with endpoint, if present.

Idempotent: removing an endpoint that is not stored is a no-op.

With user_id the delete is scoped to that owner: a row holding endpoint that belongs to someone else is left untouched and the call answers False, exactly as for an unknown endpoint, so the caller cannot learn whether the endpoint is registered to another account. Every request-driven path must pass it. None keeps the unscoped delete for internal maintenance, such as pruning an endpoint the push service answered 404/410 for.

Parameters:

Name Type Description Default
endpoint str

The push endpoint to drop.

required
user_id UUID | None

The owner the row must belong to. None deletes regardless of owner.

None

Returns:

Name Type Description
bool bool

True when a row was deleted, False when none

bool

matched (unknown endpoint, or one owned by another user).

list_for_user async

list_for_user(user_id: UUID) -> list[SubscriptionModelT]

Return every stored subscription for a user.

Parameters:

Name Type Description Default
user_id UUID

The user whose devices to list.

required

Returns:

Type Description
list[SubscriptionModelT]

list[SubscriptionModelT]: The user's subscriptions ([]

list[SubscriptionModelT]

when the user has none).

list_all async

list_all() -> list[SubscriptionModelT]

Return every stored subscription, across all users.

The whole table in one list. For delivery prefer :meth:notify_all, which walks the table in batches instead of holding it in memory; this method exists for the caller that needs the rows themselves — an export, a count by host, a migration.

Returns:

Type Description
list[SubscriptionModelT]

list[SubscriptionModelT]: Every subscription ([] when the

list[SubscriptionModelT]

table is empty).

prune async

prune(endpoints: list[str]) -> int

Delete the subscriptions matching endpoints.

Parameters:

Name Type Description Default
endpoints list[str]

Push endpoints to remove (typically the gone list returned by :meth:notify_user).

required

Returns:

Name Type Description
int int

The number of rows actually deleted.

notify_user async

notify_user(
    user_id: UUID,
    payload: WebPushPayloadSchema | dict[str, Any] | str | bytes,
    *,
    ttl_seconds: int | None = None,
    exclude_endpoints: list[str] | None = None,
) -> int

Send payload to every device a user subscribed, pruning dead ones.

Subscriptions the push service reports as gone (HTTP 404/410) are deleted from the store before returning, so stale devices never accumulate.

Pass exclude_endpoints to skip specific devices — the common case being a multi-device sync notification where the device that made the change must not notify itself. Excluded devices are never contacted and never pruned.

Parameters:

Name Type Description Default
user_id UUID

The recipient user.

required
payload WebPushPayloadSchema | dict | str | bytes

The notification body (same shapes as :meth:WebPushDispatcher.send).

required
ttl_seconds int | None

Optional TTL override.

None
exclude_endpoints list[str] | None

Push endpoints to skip (e.g. the originating device). None sends to all.

None

Returns:

Name Type Description
int int

How many devices the payload was delivered to (targeted

int

devices minus the pruned, gone ones).

notify_all async

notify_all(
    payload: WebPushPayloadSchema | dict[str, Any] | str | bytes,
    *,
    ttl_seconds: int | None = None,
    exclude_endpoints: list[str] | None = None,
    page_size: int = _DEFAULT_BROADCAST_PAGE_SIZE,
    max_concurrency: int | None = _DEFAULT_BROADCAST_CONCURRENCY,
) -> int

Send payload to every stored device, pruning the dead ones.

The global counterpart of :meth:notify_user: same delivery, same automatic pruning, no user_id filter. Use it for the announcement that is not about one account — maintenance window, release notice, campaign.

Two things differ from :meth:notify_user, and both are about size. The table is walked in batches of page_size rather than loaded whole, so memory does not scale with the subscriber base. And the dispatch fan-out is bounded by max_concurrency, because every dispatch is a request to a push service and thousands at once earn a rate limit.

The walk is cursor-based, not offset-based, precisely because this method deletes as it goes: an offset would skip a row for every row pruned on an earlier page. Rows created while the broadcast runs are not visited — the cursor moves from newest to oldest, and a new subscription is newer than the page already passed. That is what makes the walk terminate.

Parameters:

Name Type Description Default
payload WebPushPayloadSchema | dict | str | bytes

The notification body (same shapes as :meth:WebPushDispatcher.send).

required
ttl_seconds int | None

Optional TTL override.

None
exclude_endpoints list[str] | None

Push endpoints to skip. Excluded devices are never contacted and never pruned.

None
page_size int

Rows loaded per batch. Defaults to 500.

_DEFAULT_BROADCAST_PAGE_SIZE
max_concurrency int | None

Dispatches in flight at once, forwarded to :meth:WebPushDispatcher.send_many. None sends the whole batch at once. Defaults to 32.

_DEFAULT_BROADCAST_CONCURRENCY

Returns:

Name Type Description
int int

How many devices the payload was delivered to (targeted

int

devices minus the pruned, gone ones).

Raises:

Type Description
ValueError

When page_size is below 1, which would either loop forever or read nothing.

make_web_push_router

make_web_push_router(
    *,
    service_factory: Callable[[AsyncSession], WebPushSubscriptionService[Any]],
    session_factory: Callable[..., AsyncIterator[AsyncSession]],
    current_user_id: Callable[..., Any],
    prefix: str = "/api/push",
    tags: list[str] | None = None,
    store_user_agent: bool = True,
    vapid_public_key: str | Callable[[], str] | None = None,
    transfer_ownership: bool = False,
    docs_locale: str | None = None,
) -> APIRouter

Build a router with POST /subscribe and POST /unsubscribe.

Both endpoints accept the raw PushSubscription.toJSON() body the browser produces (a :class:WebPushSubscriptionSchema), so the tempest-react-sdk WebPushClient callbacks hit them with no payload mangling:

  • POST {prefix}/subscribe -> service.subscribe (idempotent by endpoint). Stores the User-Agent as the device label when store_user_agent is set.
  • POST {prefix}/unsubscribe -> service.unsubscribe (delete by endpoint, scoped to the authenticated user; no-op when absent or owned by another account).

Both require authentication via current_user_id.

Parameters:

Name Type Description Default
service_factory Callable[[AsyncSession], WebPushSubscriptionService]

Builds a request-scoped service from the yielded session (typically lambda s: WebPushSubscriptionService( BaseRepository(s, model=Model), dispatcher)).

required
session_factory Callable[..., AsyncIterator[AsyncSession]]

Yields a request-scoped DB session (the project's get_session).

required
current_user_id Callable[..., Any]

A FastAPI dependency that resolves the authenticated user's :class:~uuid.UUID.

required
prefix str

URL prefix. Defaults to "/api/push".

'/api/push'
tags list[str] | None

OpenAPI tags. Defaults to ["push"].

None
store_user_agent bool

When True (default), persist the request User-Agent header as the device label.

True
vapid_public_key str | Callable[[], str] | None

When set, mount a public GET {prefix}/vapid-public-key returning {"public_key": ...} so the browser can subscribe without the key being baked into the frontend build. Accepts a string or a zero-arg callable (resolved per request). None (default) omits the route.

None
transfer_ownership bool

Let POST {prefix}/subscribe move an endpoint registered to another account to the caller. Off by default (#632): the stored row is left untouched and the caller gets the same answer as a new subscription. Turn on only where moving devices between accounts is a real case; the service override must then accept transfer_ownership=.

False
docs_locale str | None

Language of the OpenAPI summary and description text — "en-US" or "pt-BR". None (default) reads API_DOCS_LOCALE through :class:~tempest_fastapi_sdk.settings.ServerSettings, whose default is "en-US".

None

Returns:

Name Type Description
APIRouter APIRouter

Ready to mount with app.include_router.

WebPushSubscriptionSchema

Bases: BaseSchema

Server-side representation of PushSubscription.toJSON().

Two browser-flavored field names (expirationTime) are exposed via aliases so the schema round-trips JSON produced by JSON.stringify(subscription) without manual key mangling.

Attributes:

Name Type Description
endpoint str

Push service endpoint URL.

keys WebPushKeysSchema

Encryption keys.

expiration_time int | None

Optional expiration timestamp in milliseconds since epoch. Aliased to expirationTime on the wire.

WebPushPayloadSchema

Bases: BaseSchema

JSON payload delivered with each push, in the shape the service worker reads.

Mirrors tempest-react-sdk's PushPayload (v0.86.0), pinned by tests/webpush/test_payload_contract.py: the field names on the wire are the ones installPushHandler reads, so :meth:to_json serializes by alias (requireInteraction) and drops None fields, leaving the browser defaults in place.

The click destination is the top-level url. The React push handler writes data.url from it after spreading data, so a free-form data bag cannot redirect the click, and a url placed only inside data is ignored: every click opens /. Earlier releases of this schema documented data={"url": ...}, so construction and assignment lift a string data["url"] into url when url is absent or None. An empty string counts as a value and is not replaced. When both are given and differ, the top-level url wins and a warning is logged.

The React click handler's default resolver opens only pages of the worker's own origin over http(s): a url on another origin, or with another scheme, opens / unless the app installs its own resolveUrl.

Attributes:

Name Type Description
title str | None

Notification title shown to the user.

body str | None

Notification body.

icon str | None

URL of the icon to display.

badge str | None

URL of the badge icon (Android).

image str | None

URL of a large image shown in the notification.

tag str | None

Tag used to coalesce notifications.

url str | None

Page opened when the notification body is clicked.

actions list[WebPushActionSchema] | None

Notification buttons.

require_interaction bool | None

Keep the notification on screen until the user acts. requireInteraction on the wire.

vibrate int | list[int] | None

Vibration pattern in milliseconds.

silent bool | None

Show without sound or vibration.

renotify bool | None

Alert again when the same tag replaces an older notification.

timestamp int | None

Event time in epoch milliseconds.

dir Literal['auto', 'ltr', 'rtl'] | None

Text direction.

lang str | None

BCP 47 language tag of the title and body.

data dict[str, Any] | None

Arbitrary application payload.

to_json

to_json() -> str

Serialize the payload as the service worker expects it.

Uses the wire names (requireInteraction) and drops None fields, so an option the payload does not set stays absent and the browser applies its own default instead of receiving null.

Returns:

Name Type Description
str str

The JSON encoded payload.

WebPushActionSchema

Bases: BaseSchema

One notification button, as the service worker reads it.

action, title and icon are the browser's NotificationAction. url is not part of that type: the tempest-react-sdk push handler moves it into data.actionUrls and opens it when this button is clicked, falling back to the payload's top-level url.

Attributes:

Name Type Description
action str

Identifier delivered as event.action on click.

title str

Button label.

icon str | None

Button icon URL.

url str | None

Page opened when this button is clicked.

WebPushError

WebPushError(
    message: str, *, status_code: int | None = None, endpoint: str | None = None
)

Bases: RuntimeError

Raised when a push delivery attempt fails irrecoverably.

Attributes:

Name Type Description
status_code int | None

HTTP status returned by the push service, or None when the failure happened before the request was made.

endpoint str | None

The subscription endpoint, when known.

Initialize the error.

Parameters:

Name Type Description Default
message str

Human-readable description.

required
status_code int | None

HTTP status, when known.

None
endpoint str | None

Subscription endpoint, when known.

None

WebPushGoneError

WebPushGoneError(
    message: str, *, status_code: int | None = None, endpoint: str | None = None
)

Bases: WebPushError

Raised when the push service reports the subscription is gone.

Maps to HTTP 404/410. Receivers should delete the subscription from their store and stop attempting delivery.

WebPushKeysSchema

Bases: BaseSchema

The keys object returned by PushSubscription.toJSON().

Browsers expose the encryption material as two URL-safe base64 strings; the SDK keeps the wire names so subscriptions can be stored verbatim and replayed on dispatch.

Attributes:

Name Type Description
p256dh str

Client public ECDH key (URL-safe base64).

auth str

Client auth secret (URL-safe base64).