tempest_fastapi_sdk.push¶
Push unificado: uma API para navegador e celular, com o model de token de dispositivo.
DeviceService
¶
DeviceService(
repository: BaseRepository[DeviceModelT], transports: Iterable[PushDispatcher]
)
Bases: Generic[DeviceModelT]
Store devices and deliver notifications to a user's whole fleet.
Generic over the concrete device model so it returns the project's own
rows. Pair a :class:BaseRepository bound to that model with the
transports the service actually wired: web only, mobile only, or both.
Generic parameters
DeviceModelT: The concrete :class:BaseDeviceTokenModel subclass.
Attributes:
| Name | Type | Description |
|---|---|---|
repository |
BaseRepository[DeviceModelT]
|
Data access for the device table. |
transports |
tuple[PushDispatcher, ...]
|
The configured transports, in the order they were given. |
Initialize the service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repository
|
BaseRepository[DeviceModelT]
|
Repository bound to the concrete device model. |
required |
transports
|
Iterable[PushDispatcher]
|
Transports to route by platform. When two transports claim the same platform, the first one wins. |
required |
transport_for
¶
transport_for(platform: str) -> PushDispatcher | None
Return the transport that delivers to platform.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
platform
|
str
|
A :class: |
required |
Returns:
| Type | Description |
|---|---|
PushDispatcher | None
|
PushDispatcher | None: The transport, or |
PushDispatcher | None
|
service wired none for that platform. |
register
async
¶
register(
user_id: UUID,
registration: DeviceRegistrationSchema,
*,
transfer_ownership: bool = False,
) -> DeviceModelT
Persist a device, idempotently keyed by token.
The same owner re-registering updates the existing row instead of
creating a duplicate, and refreshes last_seen_at.
A token already registered to another account is left
untouched (#632): knowing a token must not be enough to take a
device from its owner. The row comes back unchanged and the
routers answer exactly as for a new registration, so the call
cannot tell whether the token belongs to someone else — the same
rule :meth:unregister follows. A handset that changes hands is
handled by the client: it unregisters on sign-out, before the next
account registers; otherwise the previous account keeps the
device.
A web registration is checked first by the dispatcher of the
:class:~tempest_fastapi_sdk.push.WebPushTransport that delivers
to it (:meth:~tempest_fastapi_sdk.webpush.WebPushDispatcher.check_endpoint):
an endpoint it would refuse raises
:class:~tempest_fastapi_sdk.exceptions.PushEndpointNotPublicException
and is not stored. A custom web transport is not consulted, and
mobile tokens, which are not URLs, are never checked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
The user that owns the device. |
required |
registration
|
DeviceRegistrationSchema
|
What the client sent. |
required |
transfer_ownership
|
bool
|
Move a token registered to another
account to |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
DeviceModelT |
DeviceModelT
|
The persisted row — created, updated, or, for a |
DeviceModelT
|
token of another account, the stored row unchanged. Never echo |
|
DeviceModelT
|
it to the requester. |
Raises:
| Type | Description |
|---|---|
PushEndpointNotPublicException
|
When the web endpoint would be
refused by the web transport's dispatcher (HTTP |
unregister
async
¶
Remove the device with token, if present.
Idempotent: unregistering an unknown token is a no-op.
With user_id the delete is scoped to that owner: a row holding
token that belongs to someone else is left untouched and the
call answers False, exactly as for an unknown token, so the
caller cannot learn whether the token is registered to another
account. Every request-driven path must pass it — the device token
is a credential, and any authenticated account that learned one
could otherwise cut another user's notifications. None keeps
the unscoped delete for internal maintenance, such as pruning a
token the transport disowned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The device token / endpoint to drop. |
required |
user_id
|
UUID | None
|
The owner the row must belong to.
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
matched (unknown token, or one owned by another user). |
list_for_user
async
¶
Return every stored device for a user.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
The user whose devices to list. |
required |
Returns:
| Type | Description |
|---|---|
list[DeviceModelT]
|
list[DeviceModelT]: The user's devices ( |
notify_user
async
¶
notify_user(
user_id: UUID,
payload: PushPayloadSchema,
*,
exclude_tokens: Iterable[str] = (),
platforms: Iterable[PushPlatformEnum | str] = (),
) -> PushFanoutResult
Deliver payload to every device the user registered.
Deliveries run concurrently and independently: one device failing never stops the others, and the returned result says which devices took the notification, which were deleted, and which merely failed. Devices the provider disowned are removed from the store before returning, so dead rows never accumulate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
user_id
|
UUID
|
The recipient. |
required |
payload
|
PushPayloadSchema
|
The notification to deliver. |
required |
exclude_tokens
|
Iterable[str]
|
Devices to skip entirely — typically the device that caused the event, which must not notify itself. Excluded devices are never contacted and never pruned. |
()
|
platforms
|
Iterable[PushPlatformEnum | str]
|
When non-empty, restrict the fan-out to these platforms (a web-only announcement, for instance). Empty means every platform. |
()
|
Returns:
| Name | Type | Description |
|---|---|---|
PushFanoutResult |
PushFanoutResult
|
One entry per targeted device, plus the |
PushFanoutResult
|
devices no configured transport could reach. |
to_device
staticmethod
¶
to_device(row: BaseDeviceTokenModel) -> PushDevice
Map a stored row onto the transport-facing device value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
row
|
BaseDeviceTokenModel
|
The persisted device. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
PushDevice |
PushDevice
|
The same device as the transports see it. |
PushDispatcher
¶
Bases: Protocol
Deliver one notification to one device.
Implementations are expected to be safe to share across requests and to do their network work off the event loop.
Attributes:
| Name | Type | Description |
|---|---|---|
platforms |
frozenset[str]
|
Which
:class: |
send
async
¶
send(device: PushDevice, payload: PushPayloadSchema) -> None
Deliver payload to device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
PushDevice
|
The delivery target. |
required |
payload
|
PushPayloadSchema
|
The notification to deliver. |
required |
Raises:
| Type | Description |
|---|---|
PushDeviceGoneError
|
When the provider reports the device as unknown or expired, so the caller should delete it. |
PushError
|
For any other delivery failure. The device keeps its row and will be retried on the next fan-out. |
PushError
¶
Bases: RuntimeError
Raised when a delivery attempt fails.
Attributes:
| Name | Type | Description |
|---|---|---|
masked_token |
str | None
|
The device the attempt targeted, identified safely for logs. Never the raw token. |
status_code |
int | None
|
Provider status, when the transport exposes one. |
Initialize the error.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
message
|
str
|
Human-readable description. Must not contain the raw device token. |
required |
masked_token
|
str | None
|
Masked device identifier. |
None
|
status_code
|
int | None
|
Provider status code, when known. |
None
|
PushDeviceGoneError
¶
PushDeviceGoneError(
message: str, *, masked_token: str | None = None, status_code: int | None = None
)
Bases: PushError
Raised when the provider says the device no longer exists.
This is the one failure that changes the store: the caller deletes the
device instead of retrying it. Both providers signal it, in their own
vocabulary — HTTP 404/410 on Web Push, UnregisteredError (and
SenderIdMismatchError) on FCM — which is exactly the translation
this package exists to own.
WebPushTransport
¶
WebPushTransport(dispatcher: WebPushDispatcher)
Deliver unified payloads to browsers over VAPID Web Push.
Attributes:
| Name | Type | Description |
|---|---|---|
dispatcher |
WebPushDispatcher
|
The configured VAPID sender. |
platforms |
frozenset[str]
|
|
Initialize the transport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dispatcher
|
WebPushDispatcher
|
A configured VAPID dispatcher. |
required |
send
async
¶
send(device: PushDevice, payload: PushPayloadSchema) -> None
Deliver payload to a browser subscription.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
PushDevice
|
The web device to deliver to. |
required |
payload
|
PushPayloadSchema
|
The notification to deliver. |
required |
Raises:
| Type | Description |
|---|---|
PushDeviceGoneError
|
When the push service answers 404/410, or
the egress check refuses the endpoint permanently (see
:attr: |
PushError
|
For any other delivery failure, including a web row stored without its encryption keys. |
FCMTransport
¶
FCMTransport(
*, auth: FirebaseAuth | None = None, app: Any | None = None, dry_run: bool = False
)
Deliver unified payloads to iOS and Android through FCM.
The transport does not own a credential of its own. Pass the
:class:~tempest_fastapi_sdk.auth.FirebaseAuth the service already
built for ID token verification and both features share one
initialized app; pass app to target a specific
firebase_admin.App; pass neither and the default app is used, so a
service that calls firebase_admin.initialize_app() itself still
works.
Built on a :class:~tempest_fastapi_sdk.auth.FirebaseAuth whose
integration is switched off (FIREBASE_ENABLED=false, so
enabled=False), the transport claims no platform and logs one
warning when it is built: a
:class:~tempest_fastapi_sdk.push.DeviceService routing through it
skips every mobile device (reported in PushFanoutResult.skipped)
instead of failing the fan-out. Calling :meth:send on it directly
raises IntegrationDisabledException.
Attributes:
| Name | Type | Description |
|---|---|---|
platforms |
frozenset[str]
|
|
dry_run |
bool
|
When |
Initialize the transport.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
auth
|
FirebaseAuth | None
|
An authenticator whose initialized
Firebase app should be reused. Takes precedence over
|
None
|
app
|
Any | None
|
An explicit |
None
|
dry_run
|
bool
|
Send messages in FCM's validate-only mode. |
False
|
Raises:
| Type | Description |
|---|---|
ImportError
|
When the optional |
FirebaseCredentialError
|
When neither |
send
async
¶
send(device: PushDevice, payload: PushPayloadSchema) -> None
Deliver payload to a mobile device.
messaging.send is a blocking HTTP call, so it runs in a worker
thread, matching the SDK's async-first convention.
Only two provider errors mean "this device is gone":
UnregisteredError (the app was uninstalled or the token was
rotated) and SenderIdMismatchError (the token belongs to
another project). InvalidArgumentError is deliberately not
treated as gone even though it can be raised for a bad token: FCM
also raises it for a malformed payload, and pruning on that would
delete an entire user's fleet the first time a notification body
is wrong. A bad token then costs one failed attempt per fan-out
until the client re-registers, which is the cheaper mistake.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
|
PushDevice
|
The mobile device to deliver to. |
required |
payload
|
PushPayloadSchema
|
The notification to deliver. |
required |
Raises:
| Type | Description |
|---|---|
IntegrationDisabledException
|
When the transport was built on a
disabled |
PushDeviceGoneError
|
When FCM disowns the token. |
PushError
|
For any other delivery failure. |
PushPlatformEnum
¶
Bases: StrEnum
The kind of device a notification is going to.
Attributes:
| Name | Type | Description |
|---|---|---|
WEB |
A browser subscription delivered over VAPID Web Push. |
|
IOS |
An iOS app instance delivered over FCM. |
|
ANDROID |
An Android app instance delivered over FCM. |
PushDevice
dataclass
¶
PushDevice(
platform: PushPlatformEnum,
token: str,
p256dh: str | None = None,
auth: str | None = None,
expiration_time: int | None = None,
)
One delivery target, whatever the platform.
Web devices carry the browser's encryption material in p256dh /
auth and put the push-service endpoint in token; mobile
devices put the FCM registration token there and leave the key fields
None. Keeping them in one type is what lets
:class:~tempest_fastapi_sdk.push.DeviceService fan out to a user's
whole fleet without the caller sorting devices by kind first.
Attributes:
| Name | Type | Description |
|---|---|---|
platform |
PushPlatformEnum
|
Which transport delivers to this device. |
token |
str
|
The per-device identity — a Web Push endpoint URL for
|
p256dh |
str | None
|
Browser ECDH public key. |
auth |
str | None
|
Browser auth secret. |
expiration_time |
int | None
|
Browser |
masked_token
property
¶
Return the token as it may appear in a log line.
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
|
PushPayloadSchema
¶
Bases: BaseSchema
A notification described in terms both transports can carry.
Web Push accepts an arbitrary JSON body that the service worker
interprets, while FCM has a fixed notification shape plus a
string-only data map. This schema is the intersection that
survives both, and each transport widens it on its own terms —
:class:~tempest_fastapi_sdk.push.WebPushTransport serializes the
whole thing as JSON, while
:class:~tempest_fastapi_sdk.push.FCMTransport maps it onto
messaging.Notification + data.
Attributes:
| Name | Type | Description |
|---|---|---|
title |
str | None
|
Heading shown by the OS notification UI. |
body |
str | None
|
Short text under the title. |
image |
str | None
|
HTTPS URL of the image — the icon on Web Push,
|
tag |
str | None
|
Coalescing key. Newer notifications with the same
tag replace older ones ( |
data |
dict[str, str]
|
Structured payload handed to the client. Values must be strings — FCM rejects anything else, so the constraint is modelled here instead of failing at send time. |
DeviceRegistrationSchema
¶
Bases: BaseSchema
What a client POSTs to register itself for notifications.
One body serves both sides. A browser sends platform="web" with
the endpoint in token plus the two key fields from
PushSubscription.toJSON(); a mobile app sends platform="ios"
or "android" with the FCM registration token and nothing else.
Attributes:
| Name | Type | Description |
|---|---|---|
token |
str
|
Push endpoint URL (web) or FCM registration token (mobile). |
platform |
PushPlatformEnum
|
Which kind of device this is. |
p256dh |
str | None
|
Browser ECDH public key. Required for |
auth |
str | None
|
Browser auth secret. Required for |
expiration_time |
int | None
|
Browser |
app_version |
str | None
|
Optional client build identifier, useful when a notification format depends on the app version. |
PushResult
dataclass
¶
PushResult(
platform: PushPlatformEnum,
masked_token: str,
delivered: bool,
pruned: bool = False,
error: str | None = None,
)
The outcome of one delivery attempt.
Attributes:
| Name | Type | Description |
|---|---|---|
platform |
PushPlatformEnum
|
The device's platform. |
masked_token |
str
|
The device, identified safely for logs. |
delivered |
bool
|
Whether the provider accepted the message. |
pruned |
bool
|
Whether the provider reported the device as gone, so it was deleted from the store. |
error |
str | None
|
Short description of the failure, when the attempt neither delivered nor pruned. |
PushFanoutResult
dataclass
¶
PushFanoutResult(
results: tuple[PushResult, ...] = (), skipped: tuple[str, ...] = tuple()
)
What happened across a user's whole fleet.
A failing device never aborts the fan-out, so this is how the caller learns which devices took the notification, which were deleted, and which merely failed and will be retried next time.
Attributes:
| Name | Type | Description |
|---|---|---|
results |
tuple[PushResult, ...]
|
One entry per targeted device, in the order the devices were read from the store. |
skipped |
tuple[str, ...]
|
Masked tokens of devices no configured transport can reach — an iOS row in a service that wired only Web Push, for instance. They are not pruned: the device is fine, the wiring is missing. |
delivered
property
¶
Return how many devices accepted the notification.
Returns:
| Name | Type | Description |
|---|---|---|
int |
int
|
The number of successful deliveries. |
pruned
property
¶
Return the devices deleted because the provider disowned them.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
tuple[str, ...]: Masked tokens of the pruned devices. |
failed
property
¶
Return the devices that failed without being disowned.
Returns:
| Type | Description |
|---|---|
str
|
tuple[str, ...]: Masked tokens of the failed devices. These |
...
|
keep their row and will be tried again on the next fan-out. |
as_dict
¶
Return a JSON-safe summary, for a router response or a log line.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
dict[str, Any]: |
dict[str, Any]
|
|
mask_push_token
¶
Return a stable, non-sensitive identifier for a device token.
A registration token (or a Web Push endpoint) is a credential: whoever holds it can send notifications to that device. It must never reach a log line or an API response, but failures still have to be traceable to a specific device — so this keeps a short SHA-256 prefix, which is stable across calls and useless to an attacker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
token
|
str
|
The raw device token or push endpoint. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
A twelve-character SHA-256 prefix. |
make_push_router
¶
make_push_router(
*,
service_factory: Callable[[AsyncSession], DeviceService[Any]],
session_factory: Callable[..., AsyncIterator[AsyncSession]],
current_user_id: Callable[..., Any],
prefix: str = "/api/push",
tags: list[str] | None = None,
vapid_public_key: str | Callable[[], str] | None = None,
transfer_ownership: bool = False,
docs_locale: str | None = None,
) -> APIRouter
Build a router with POST /register and POST /unregister.
POST {prefix}/register->service.register(idempotent by token). A browser postsplatform="web"with the endpoint and the two key fields; a mobile app postsplatform="ios"/"android"with its FCM registration token.POST {prefix}/unregister->service.unregister(delete by token, scoped to the authenticated user; no-op when absent or owned by another account).GET {prefix}/vapid-public-key-> the key the browser subscribes with, mounted only whenvapid_public_keyis given.
Both write endpoints require authentication via current_user_id.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
service_factory
|
Callable[[AsyncSession], DeviceService]
|
Builds a request-scoped service from the yielded session. |
required |
session_factory
|
Callable[..., AsyncIterator[AsyncSession]]
|
Yields
a request-scoped DB session (the project's |
required |
current_user_id
|
Callable[..., Any]
|
FastAPI dependency resolving
the authenticated user's :class: |
required |
prefix
|
str
|
URL prefix. Defaults to |
'/api/push'
|
tags
|
list[str] | None
|
OpenAPI tags. Defaults to |
None
|
vapid_public_key
|
str | Callable[[], str] | None
|
When set, mount
the public |
None
|
transfer_ownership
|
bool
|
Let |
False
|
docs_locale
|
str | None
|
Language of the OpenAPI |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
APIRouter |
APIRouter
|
Ready to mount with |