Firebase Cloud Messaging 1. Versuch
This commit is contained in:
1 parent
f1fb926c2f
commit
4c8b11c4d5
25 files changed
+2111
-31
No files matched your search
@@ -32,8 +32,10 @@ from datetime import datetime, timedelta, timezone
|
||||
from threading import Event, Lock
|
||||
from flask import current_app
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.services.fcm_service import fcm_service
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.ws import store
|
||||
from cmbnet.ws.client_types import normalize_client_type
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
@@ -79,12 +81,17 @@ class WebSocketBroker:
|
||||
# ------------------------------------------------------------------
|
||||
# Verbindungen und Authentifizierung
|
||||
# ------------------------------------------------------------------
|
||||
def register_connection(self, tenant_id, account_id, client_id, ws, role=None, group_id=None):
|
||||
def register_connection(self, tenant_id, account_id, client_id, ws,
|
||||
role=None, group_id=None, client_type=None):
|
||||
"""Registriert eine neue, noch nicht authentifizierte Client-Verbindung.
|
||||
|
||||
Die Verbindung wird anhand der Client-ID verwaltet. Die Account-ID wird
|
||||
mitgeführt, damit Empfänger weiterhin über Rollen und Gruppen ermittelt
|
||||
werden können und ein Account mehrere Clients parallel betreiben kann.
|
||||
|
||||
``client_type`` ist ausschließlich ein FCM-Routing-Merkmal. Der Wert
|
||||
wird gegen die Rolle des Accounts geprüft; ein Dispatcher kann sich
|
||||
beispielsweise nicht als Gruppen-View ausgeben.
|
||||
"""
|
||||
if not client_id:
|
||||
return False
|
||||
@@ -104,13 +111,16 @@ class WebSocketBroker:
|
||||
existing_account = store.get_client_account(tenant_id, client_id)
|
||||
if existing_account is not None and existing_account != account_id:
|
||||
return False
|
||||
if not store.ensure_client(
|
||||
tenant_id, client_id, account_id, worker_id=self.worker_id
|
||||
):
|
||||
return False
|
||||
|
||||
if role is None:
|
||||
role = account['role']
|
||||
client_type = normalize_client_type(client_type, role)
|
||||
|
||||
if not store.ensure_client(
|
||||
tenant_id, client_id, account_id, worker_id=self.worker_id,
|
||||
client_type=client_type
|
||||
):
|
||||
return False
|
||||
|
||||
# Für Gruppen-Accounts die zugehörige Gruppe ermitteln. Ein Account der
|
||||
# Rolle "Gruppe" ist höchstens einer Gruppe zugeordnet.
|
||||
@@ -147,6 +157,7 @@ class WebSocketBroker:
|
||||
'client_id': client_id,
|
||||
'role': role,
|
||||
'group_id': group_id,
|
||||
'client_type': client_type,
|
||||
'last_ping': datetime.now(),
|
||||
'connected_at': time.monotonic(),
|
||||
'last_pong_at': None,
|
||||
@@ -513,8 +524,72 @@ class WebSocketBroker:
|
||||
)
|
||||
if queued:
|
||||
self.delivery_wakeup.set()
|
||||
# Mobile Clients, die als getrennt gelten, werden zusätzlich über
|
||||
# FCM geweckt. Der eigentliche Inhalt bleibt in der Queue.
|
||||
if message.code >= 99:
|
||||
self.wake_client(tenant_id, client_id, 'queue')
|
||||
return queued
|
||||
|
||||
def wake_client(self, tenant_id, client_id, reason='queue',
|
||||
cooldown_seconds=None):
|
||||
"""Sendet bei Bedarf ein FCM-Aufwachsignal an einen mobilen Client.
|
||||
|
||||
Die Methode ist bewusst idempotent und durch ``last_wake_at``
|
||||
gedrosselt. Sie wird sowohl beim Einreihen einer Nachricht als auch
|
||||
vom periodischen Offline-Worker aufgerufen.
|
||||
"""
|
||||
try:
|
||||
if not fcm_service.server_ready():
|
||||
return False
|
||||
|
||||
if cooldown_seconds is None:
|
||||
try:
|
||||
cooldown_seconds = int(current_app.config.get(
|
||||
'FCM_QUEUE_WAKE_COOLDOWN_SECONDS', 60
|
||||
))
|
||||
except (TypeError, ValueError):
|
||||
cooldown_seconds = 60
|
||||
|
||||
current = store.now()
|
||||
rows = store.claim_offline_mobile_wakes(
|
||||
tenant_id,
|
||||
disconnected_before=current,
|
||||
re_wake_before=current - max(0, cooldown_seconds),
|
||||
client_id=client_id,
|
||||
reason=reason,
|
||||
limit=1,
|
||||
)
|
||||
if not rows:
|
||||
return False
|
||||
|
||||
tokens = [row['token'] for row in rows]
|
||||
result = fcm_service.send_wake(tokens, reason=reason)
|
||||
for token in result.get('invalid_tokens') or []:
|
||||
store.mark_push_token_invalid(token)
|
||||
|
||||
if result.get('sent'):
|
||||
return True
|
||||
|
||||
# Ein fehlgeschlagenes Signal wird nicht als erfolgreich verbucht.
|
||||
# Der nächste Versuch darf aber erst nach dem Cooldown erfolgen, um
|
||||
# bei einem FCM-Ausfall keine Schleife zu erzeugen.
|
||||
for row in rows:
|
||||
store.set_client_wake_sent(
|
||||
tenant_id, row['client_id'], f'{reason}:failed', current
|
||||
)
|
||||
return False
|
||||
except Exception as exc:
|
||||
# Ein FCM-Problem darf das Einreihen und Ausliefern fachlicher
|
||||
# Nachrichten niemals verhindern.
|
||||
try:
|
||||
current_app.logger.warning(
|
||||
'FCM-Aufwachsignal fehlgeschlagen (tenant=%s, client=%s): %s',
|
||||
tenant_id, client_id, exc
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
def cleanup_client_queues(self):
|
||||
"""Räumt abgelaufene Queues und verwaiste Clients in der DB auf."""
|
||||
store.purge_expired_queue_rows()
|
||||
@@ -523,6 +598,13 @@ class WebSocketBroker:
|
||||
self._client_queue_timeout_message()
|
||||
)
|
||||
store.cleanup_clients(self._client_retention_seconds())
|
||||
try:
|
||||
token_retention = float(current_app.config.get(
|
||||
'FCM_PUSH_TOKEN_RETENTION_MINUTES', 1440
|
||||
)) * 60
|
||||
except (TypeError, ValueError):
|
||||
token_retention = 1440 * 60
|
||||
store.cleanup_orphan_push_tokens(max(3600.0, token_retention))
|
||||
|
||||
# Lokale Caches für inzwischen entfernte Clients bereinigen.
|
||||
for key in list(self.client_sequences):
|
||||
|
||||
Reference in new issue
Block a user