Firebase Cloud Messaging 1. Versuch

This commit is contained in:
concierge committed 2026-11-08 12:25:35 +01:00
1 parent f1fb926c2f
commit 4c8b11c4d5
25 files changed
+2111 -31

No files matched your search

+87 -5
View File
@@ -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):
+34
View File
@@ -0,0 +1,34 @@
"""Zulässige Webview-Typen und ihre Rollenbindung.
Der Client-Typ steuert ausschließlich, ob der Broker für eine Webview
FCM-Aufwachsignale einsetzen darf. Er ersetzt keine Rollenprüfung: Der Typ
wird beim Code-0-Handshake zusätzlich zur Session-Rolle validiert.
"""
GROUP_VIEW = 'group_view'
DISPATCHER_MOBILE = 'dispatcher_mobile'
MOBILE_CLIENT_TYPES = frozenset({GROUP_VIEW, DISPATCHER_MOBILE})
CLIENT_TYPE_ROLES = {
GROUP_VIEW: frozenset({'Gruppe'}),
DISPATCHER_MOBILE: frozenset({'Dispatcher', 'Administrator'}),
}
def normalize_client_type(value, role=None):
"""Gibt einen gültigen Client-Typ oder ``None`` zurück.
``None`` bedeutet: kein FCM für diese Webview. Ältere Clients ohne
Typangabe bleiben damit kompatibel.
"""
text = str(value or '').strip().lower()
if text not in MOBILE_CLIENT_TYPES:
return None
if role is not None and role not in CLIENT_TYPE_ROLES[text]:
return None
return text
def is_mobile_client_type(value):
return value in MOBILE_CLIENT_TYPES
+5 -2
View File
@@ -6,7 +6,8 @@ from datetime import datetime
class WSMessage:
def __init__(self, sender_id=None, receiver_id=None, code=0, msg="", ts=None, client_id=None):
def __init__(self, sender_id=None, receiver_id=None, code=0, msg="", ts=None,
client_id=None, client_type=None):
self.sender_id = sender_id
self.receiver_id = receiver_id
self.code = code
@@ -15,6 +16,7 @@ class WSMessage:
# Nur für den Code-0-Handshake. Wird nicht an andere Clients
# weitergegeben und deshalb auch nicht in to_dict() serialisiert.
self.client_id = client_id
self.client_type = client_type
def to_dict(self):
return {
@@ -38,7 +40,8 @@ class WSMessage:
ts=data.get('ts'),
# Ältere Clients senden noch session_id. Sie werden übergangsweise
# als Client-ID akzeptiert.
client_id=data.get('client_id') or data.get('session_id')
client_id=data.get('client_id') or data.get('session_id'),
client_type=data.get('client_type')
)
@classmethod
+103
View File
@@ -0,0 +1,103 @@
"""Periodischer Worker für FCM-Aufwachsignale.
Der Worker läuft in jedem WSGI-Prozess. Die eigentliche Kandidatenauswahl
wird über ``claim_offline_mobile_wakes`` in SQLite transaktional reserviert,
damit mehrere Worker nicht dasselbe Signal senden.
"""
from __future__ import annotations
import threading
from cmbnet.db import get_db
from cmbnet.services.fcm_service import fcm_service
from cmbnet.ws import store
class PushWakeWorker:
def __init__(self, interval=30):
self.interval = max(5.0, float(interval or 30))
self.app = None
self.running = False
self._thread = None
self._stop = threading.Event()
def start(self, app=None, interval=None):
if app is not None:
self.app = app
if interval is not None:
self.interval = max(5.0, float(interval))
if self.running or self.app is None:
return
self.running = True
self._stop.clear()
self._thread = threading.Thread(
target=self._run,
name='cmbnet-fcm-wake',
daemon=True,
)
self._thread.start()
def stop(self):
self.running = False
self._stop.set()
if self._thread is not None:
self._thread.join(timeout=2.0)
self._thread = None
def _run(self):
with self.app.app_context():
while not self._stop.is_set() and self.running:
try:
self._run_once()
except Exception as exc:
try:
self.app.logger.warning(
'FCM-Offline-Worker fehlgeschlagen: %s', exc
)
except Exception:
pass
self._stop.wait(self.interval)
def _run_once(self):
config = self.app.config
if not fcm_service.server_ready():
return
try:
offline_seconds = max(
0.0,
float(config.get('FCM_OFFLINE_WAKE_MINUTES', 5)) * 60
)
except (TypeError, ValueError):
offline_seconds = 5 * 60
current = store.now()
cutoff = current - offline_seconds
db = get_db()
tenant_rows = db.execute('SELECT id FROM tenants').fetchall()
for tenant_row in tenant_rows:
tenant_id = tenant_row['id']
candidates = store.claim_offline_mobile_wakes(
tenant_id,
disconnected_before=cutoff,
re_wake_before=cutoff,
auto_position_only=True,
reason='offline',
limit=500,
)
if not candidates:
continue
tokens = [row['token'] for row in candidates]
result = fcm_service.send_wake(tokens, reason='offline')
for token in result.get('invalid_tokens') or []:
store.mark_push_token_invalid(token)
if result.get('failed'):
self.app.logger.warning(
'FCM-Offline-Wake: %s von %s Signalen fehlgeschlagen '
'(tenant=%s)', result.get('failed'), len(tokens), tenant_id
)
push_wake_worker = PushWakeWorker()
+17 -9
View File
@@ -17,15 +17,17 @@ from cmbnet.ws.protocol import WSMessage
def _parse_auth_payload(value):
"""Liefert (Token, Client-ID) aus dem Code-0-Payload.
"""Liefert (Token, Client-ID, Client-Typ) aus dem Code-0-Payload.
Ältere Clients senden statt ``client_id`` noch ``session_id``. Der
alte Schlüssel wird übergangsweise weiter akzeptiert.
alte Schlüssel wird übergangsweise weiter akzeptiert. ``client_type``
ist optional; ohne Angabe bleibt FCM für die Webview deaktiviert.
"""
if isinstance(value, dict):
return (
value.get('token'),
value.get('client_id') or value.get('session_id')
value.get('client_id') or value.get('session_id'),
value.get('client_type')
)
if isinstance(value, str):
@@ -34,15 +36,16 @@ def _parse_auth_payload(value):
try:
data = json.loads(text)
except (TypeError, ValueError):
return None, None
return None, None, None
if isinstance(data, dict):
return (
data.get('token'),
data.get('client_id') or data.get('session_id')
data.get('client_id') or data.get('session_id'),
data.get('client_type')
)
return text, None
return text, None, None
return None, None
return None, None, None
@sock.route('/<tenant>/ws')
@@ -97,14 +100,19 @@ def ws(ws, tenant):
ws.close()
break
token, requested_client_id = _parse_auth_payload(msg.msg)
token, requested_client_id, client_type = _parse_auth_payload(
msg.msg
)
if not requested_client_id:
requested_client_id = getattr(msg, 'client_id', None)
if client_type is None:
client_type = getattr(msg, 'client_type', None)
client_id = broker.normalize_client_id(requested_client_id, account_id)
msg.client_id = client_id
if not token or not broker.register_connection(
tenant_id, account_id, client_id, ws
tenant_id, account_id, client_id, ws,
client_type=client_type
):
broker.log_incoming(
tenant_id, msg, recipients=[],
+247 -7
View File
@@ -47,12 +47,17 @@ def client_is_connected(tenant_id, client_id):
return bool(row and row['disconnected_at'] is None)
def ensure_client(tenant_id, client_id, account_id, worker_id=None):
def ensure_client(tenant_id, client_id, account_id, worker_id=None,
client_type=None):
"""Registriert eine Client-ID bzw. aktualisiert ihren Verbindungsstatus.
Gibt ``False`` zurück, wenn die Client-ID bereits einem anderen Account
gehört. Ein solcher Wechsel wäre ein Hinweis auf eine manipulierte
Zuordnung und wird vom Broker abgelehnt.
``client_type`` wird bei jedem Reconnect aktualisiert. ``None`` lässt
einen bereits bekannten Typ unverändert, damit ältere Clients ohne
Typangabe ihre FCM-Berechtigung nicht verlieren.
"""
db = get_db()
row = get_client(tenant_id, client_id)
@@ -63,19 +68,20 @@ def ensure_client(tenant_id, client_id, account_id, worker_id=None):
return False
db.execute(
'UPDATE ws_clients SET worker_id = ?, connected_at = ?, '
'disconnected_at = NULL, authenticated = 0 '
'disconnected_at = NULL, authenticated = 0, '
'client_type = COALESCE(?, client_type) '
'WHERE tenant_id = ? AND client_id = ?',
(worker_id, current, tenant_id, client_id)
(worker_id, current, client_type, tenant_id, client_id)
)
db.commit()
return True
db.execute(
'INSERT INTO ws_clients '
'(tenant_id, client_id, account_id, worker_id, connected_at, '
' authenticated, last_seq) '
'VALUES (?, ?, ?, ?, ?, 0, 0)',
(tenant_id, client_id, account_id, worker_id, current)
'(tenant_id, client_id, account_id, client_type, worker_id, '
' connected_at, authenticated, last_seq) '
'VALUES (?, ?, ?, ?, ?, ?, 0, 0)',
(tenant_id, client_id, account_id, client_type, worker_id, current)
)
db.commit()
return True
@@ -207,6 +213,236 @@ def client_ids_for_accounts(tenant_id, account_ids):
return result
def set_client_wake_sent(tenant_id, client_id, reason=None, timestamp=None):
"""Vermerkt ein erfolgreich abgesetztes FCM-Aufwachsignal."""
db = get_db()
db.execute(
'UPDATE ws_clients SET last_wake_at = ?, last_wake_reason = ? '
'WHERE tenant_id = ? AND client_id = ?',
(timestamp if timestamp is not None else now(), reason, tenant_id, client_id)
)
db.commit()
def upsert_push_token(tenant_id, client_id, account_id, token, client_type,
platform=None, auto_position=False):
"""Speichert bzw. aktualisiert ein FCM-Token.
Das Token ist projektweit eindeutig. Meldet sich derselbe Browser nach
einem Neuladen mit einer neuen Client-ID an, wird der bestehende Eintrag
verschoben, statt ein zweites Token anzulegen. Ältere Tokens derselben
Client-ID werden entfernt, damit nach einer Token-Rotation keine doppelten
Wake-Signale entstehen.
"""
db = get_db()
current = now()
db.execute(
'DELETE FROM ws_push_tokens '
'WHERE tenant_id = ? AND client_id = ? AND token <> ?',
(tenant_id, client_id, token)
)
db.execute(
'''INSERT INTO ws_push_tokens
(tenant_id, client_id, account_id, token, client_type,
platform, auto_position, invalid, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, 0, ?, ?)
ON CONFLICT(token) DO UPDATE SET
tenant_id = excluded.tenant_id,
client_id = excluded.client_id,
account_id = excluded.account_id,
client_type = excluded.client_type,
platform = excluded.platform,
auto_position = excluded.auto_position,
invalid = 0,
updated_at = excluded.updated_at''',
(tenant_id, client_id, account_id, token, client_type,
platform, 1 if auto_position else 0, current, current)
)
db.commit()
def delete_push_token(tenant_id, token=None, client_id=None, account_id=None):
"""Entfernt ein FCM-Token gezielt über Token oder Client-ID."""
clauses = ['tenant_id = ?']
params = [tenant_id]
if token:
clauses.append('token = ?')
params.append(token)
if client_id:
clauses.append('client_id = ?')
params.append(client_id)
if account_id is not None:
clauses.append('account_id = ?')
params.append(account_id)
if len(clauses) == 1:
return
db = get_db()
db.execute(
f'DELETE FROM ws_push_tokens WHERE {" AND ".join(clauses)}',
tuple(params)
)
db.commit()
def get_push_token(tenant_id, client_id):
"""Liefert das zuletzt aktualisierte, gültige Token eines Clients."""
return get_db().execute(
'''SELECT * FROM ws_push_tokens
WHERE tenant_id = ? AND client_id = ? AND invalid = 0
ORDER BY updated_at DESC, id DESC LIMIT 1''',
(tenant_id, client_id)
).fetchone()
def mark_push_token_invalid(token):
"""Markiert ein von FCM abgelehntes Token als ungültig."""
db = get_db()
db.execute(
'UPDATE ws_push_tokens SET invalid = 1, updated_at = ? WHERE token = ?',
(now(), token)
)
db.commit()
def _offline_mobile_wake_query(tenant_id, disconnected_before,
re_wake_before=None, group_id=None,
auto_position_only=False, client_id=None,
limit=500):
sql = [
'''SELECT c.tenant_id, c.client_id, c.account_id, c.client_type,
c.disconnected_at, c.last_wake_at, c.last_wake_reason,
p.token, p.platform, p.auto_position
FROM ws_clients c
JOIN ws_push_tokens p
ON p.id = (
SELECT p2.id FROM ws_push_tokens p2
WHERE p2.tenant_id = c.tenant_id
AND p2.client_id = c.client_id
AND p2.invalid = 0
ORDER BY p2.updated_at DESC, p2.id DESC
LIMIT 1
)
WHERE c.tenant_id = ?
AND c.client_type IN ('group_view', 'dispatcher_mobile')
AND c.disconnected_at IS NOT NULL
AND c.disconnected_at <= ?'''
]
params = [tenant_id, disconnected_before]
if client_id is not None:
sql.append('AND c.client_id = ?')
params.append(client_id)
if re_wake_before is not None:
sql.append(
'AND (c.last_wake_at IS NULL OR c.last_wake_at <= ?)'
)
params.append(re_wake_before)
if auto_position_only:
sql.append("AND (c.client_type = 'dispatcher_mobile' OR p.auto_position = 1)")
if group_id is not None:
sql.append(
'''AND EXISTS (
SELECT 1 FROM group_accounts ga
WHERE ga.tenant_id = c.tenant_id
AND ga.account_id = c.account_id
AND ga.group_id = ?
)'''
)
params.append(group_id)
sql.append('ORDER BY c.disconnected_at ASC LIMIT ?')
params.append(max(1, int(limit)))
return ' '.join(sql), tuple(params)
def offline_mobile_wake_candidates(tenant_id, disconnected_before,
re_wake_before=None, group_id=None,
auto_position_only=False, client_id=None,
limit=500):
"""Liefert offline mobile Clients mit gültigem FCM-Token.
``disconnected_before`` ist der Spätzeitpunkt, zu dem die Trennung
eingetreten sein muss (für den regulären Offline-Timeout).
``re_wake_before`` verhindert zu häufige Wiederholungen; ``None`` hebt
die Sperre auf (manueller Aufruf).
``auto_position_only`` berücksichtigt nur Gruppen-Views, bei denen die
automatische Positionsübertragung aktiviert ist.
"""
sql, params = _offline_mobile_wake_query(
tenant_id,
disconnected_before,
re_wake_before=re_wake_before,
group_id=group_id,
auto_position_only=auto_position_only,
client_id=client_id,
limit=limit,
)
return get_db().execute(sql, params).fetchall()
def claim_offline_mobile_wakes(tenant_id, disconnected_before,
re_wake_before=None, group_id=None,
auto_position_only=False, client_id=None,
reason='offline', limit=500):
"""Reserviert fällige Wake-Kandidaten prozessübergreifend.
Mehrere WSGI-Worker dürfen nicht dasselbe FCM-Signal senden. Deshalb
werden die Kandidaten in einer ``BEGIN IMMEDIATE``-Transaktion gelesen
und ihr ``last_wake_at`` sofort gesetzt. Der tatsächliche FCM-Versand
erfolgt erst nach dem Commit.
"""
db = get_db()
if db.in_transaction:
db.commit()
db.execute('BEGIN IMMEDIATE')
try:
sql, params = _offline_mobile_wake_query(
tenant_id,
disconnected_before,
re_wake_before=re_wake_before,
group_id=group_id,
auto_position_only=auto_position_only,
client_id=client_id,
limit=limit,
)
rows = db.execute(sql, params).fetchall()
current = now()
for row in rows:
db.execute(
'UPDATE ws_clients SET last_wake_at = ?, last_wake_reason = ? '
'WHERE tenant_id = ? AND client_id = ?',
(current, reason, tenant_id, row['client_id'])
)
db.commit()
return rows
except Exception:
db.rollback()
raise
def cleanup_orphan_push_tokens(max_age_seconds):
"""Entfernt ungültige sowie verwaiste, lange nicht aktualisierte Tokens."""
db = get_db()
cutoff = now() - max_age_seconds
db.execute(
'DELETE FROM ws_push_tokens WHERE invalid = 1'
)
db.execute(
'''DELETE FROM ws_push_tokens
WHERE updated_at < ?
AND NOT EXISTS (
SELECT 1 FROM ws_clients c
WHERE c.tenant_id = ws_push_tokens.tenant_id
AND c.client_id = ws_push_tokens.client_id
)''',
(cutoff,)
)
db.commit()
def describe_connections(tenant_id):
"""Liefert alle aktuell verbundenen Clients inklusive Account und Gruppe."""
rows = get_db().execute(
@@ -477,6 +713,10 @@ def cleanup_clients(retention_seconds):
'DELETE FROM ws_client_queue WHERE tenant_id = ? AND client_id = ?',
(tenant_id, client_id)
)
db.execute(
'DELETE FROM ws_push_tokens WHERE tenant_id = ? AND client_id = ?',
(tenant_id, client_id)
)
db.execute(
'DELETE FROM ws_clients WHERE tenant_id = ? AND client_id = ?',
(tenant_id, client_id)