Broker unterstützt jetzt mehrere WSGI Worker
This commit is contained in:
1 parent
1e2a58e563
commit
f5b0c9509c
13 files changed
+1252
-327
No files matched your search
+226
-209
@@ -23,14 +23,17 @@ Wichtige Regeln aus der Spezifikation:
|
||||
Zeitfenster wieder zurück auf "unterwegs".
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from threading import Lock
|
||||
from threading import Event, Lock
|
||||
from flask import current_app
|
||||
from cmbnet.db import get_db
|
||||
from cmbnet.services.groups_service import GroupsService
|
||||
from cmbnet.ws import store
|
||||
from cmbnet.ws.protocol import WSMessage
|
||||
|
||||
|
||||
@@ -43,41 +46,35 @@ class WebSocketBroker:
|
||||
# 'group_id': <verknüpfte Gruppe oder None>,
|
||||
# }
|
||||
# Eine Client-ID gehört genau zu einer Webview. Mehrere Clients
|
||||
# desselben Accounts besitzen daher getrennte Einträge.
|
||||
# desselben Accounts besitzen daher getrennte Einträge. Dieses Dict
|
||||
# enthält bewusst nur die Verbindungen des aktuellen Worker-Prozesses.
|
||||
self.connections = {}
|
||||
# authenticated[tenant_id][client_id] = True
|
||||
# Erst nach erfolgreichem Code-0-Handshake darf ein Client Nachrichten
|
||||
# über die Verbindung senden.
|
||||
# über die Verbindung senden. Auch dieser Status ist prozesslokal.
|
||||
self.authenticated = {}
|
||||
|
||||
# Nicht zustellbare Nachrichten werden pro Client gepuffert.
|
||||
# Schlüssel: (tenant_id, client_id).
|
||||
self.client_queues = {}
|
||||
# client_accounts[(tenant_id, client_id)] = account_id
|
||||
# Bleibt auch nach einem Verbindungsabbruch erhalten, damit weitere
|
||||
# Nachrichten für denselben Client gepuffert werden können.
|
||||
self.client_accounts = {}
|
||||
# account_clients[(tenant_id, account_id)] = {client_id, ...}
|
||||
# Wird für die Empfängerermittlung benötigt: Ein Account kann mehrere
|
||||
# Clients gleichzeitig betreiben.
|
||||
self.account_clients = {}
|
||||
# disconnected_clients[(tenant_id, client_id)] = monotonic Zeitpunkt.
|
||||
# Dient dem Aufräumen dauerhaft verlassener Webviews.
|
||||
self.disconnected_clients = {}
|
||||
self.queue_lock = Lock()
|
||||
# Gemeinsamer Zustand liegt in SQLite (siehe cmbnet/ws/store.py):
|
||||
# ws_clients, ws_client_queue und ws_group_presence. Dadurch finden
|
||||
# Reconnects auf einem anderen Worker ihre Queue und Sequenznummer.
|
||||
self.worker_id = os.environ.get('CMBNET_WS_WORKER_ID') or ''
|
||||
if not self.worker_id:
|
||||
self.worker_id = f'{socket.gethostname()}:{os.getpid()}'
|
||||
|
||||
# Sequenznummern werden pro Client-ID vergeben und bleiben über einen
|
||||
# WebSocket-Reconnect derselben Webview hinweg erhalten. Dadurch kann
|
||||
# der Client nach einem Reconnect erkennen, ob ihm Frames fehlen.
|
||||
# client_sequences[(tenant_id, client_id)] = zuletzt zugestellte Sequenz
|
||||
# Sequenznummern werden pro Client-ID vergeben. Der lokale Cache wird
|
||||
# beim Registrieren aus der Datenbank geladen; nach jedem erfolgreichen
|
||||
# Versand wird die gemeinsame Zählung fortgeschrieben.
|
||||
self.client_sequences = {}
|
||||
# Ein Lock pro Client-ID serialisiert Sequenzvergabe und Sendevorgang
|
||||
# auch dann, wenn die Verbindung während eines Reconnects ersetzt wird.
|
||||
self.client_sequence_locks = {}
|
||||
|
||||
# Zeitpunkt des letzten Code-2-Pongs je Gruppe (monotonic).
|
||||
self.group_last_pong = {}
|
||||
self.group_online_since = {}
|
||||
# Serialisiert das Ausliefern der gemeinsamen Queue pro Client, damit
|
||||
# Authentifizierung und Polling-Schleife nicht parallel dieselben
|
||||
# Aufträge versenden.
|
||||
self.client_delivery_locks = {}
|
||||
# Weckt die lokale Polling-Schleife nach einer neu eingestellten
|
||||
# Nachricht. Workerübergreifend übernimmt das reguläre Polling.
|
||||
self.delivery_wakeup = Event()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Verbindungen und Authentifizierung
|
||||
@@ -102,10 +99,15 @@ class WebSocketBroker:
|
||||
|
||||
# Eine Client-ID ist an den Account gebunden, der sie im Handshake
|
||||
# verwendet hat. Ein Wechsel des Accounts unter derselben ID wäre ein
|
||||
# Hinweis auf eine falsche bzw. manipulierte Zuordnung.
|
||||
existing_account = self.client_accounts.get((tenant_id, client_id))
|
||||
# Hinweis auf eine falsche bzw. manipulierte Zuordnung. Die Zuordnung
|
||||
# liegt prozessübergreifend in ws_clients.
|
||||
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']
|
||||
@@ -123,6 +125,7 @@ class WebSocketBroker:
|
||||
group_id = group['id'] if group else None
|
||||
|
||||
connections = self.connections.setdefault(tenant_id, {})
|
||||
key = (tenant_id, client_id)
|
||||
|
||||
# Eine neue Verbindung mit derselben Client-ID ersetzt eine eventuell
|
||||
# noch registrierte alte Verbindung (z. B. nach einem schnellen
|
||||
@@ -148,9 +151,9 @@ class WebSocketBroker:
|
||||
'connected_at': time.monotonic(),
|
||||
'last_pong_at': None,
|
||||
# Zuletzt an diese Client-ID zugestellte Sequenznummer. Die
|
||||
# maßgebliche Zählung liegt in self.client_sequences, damit sie
|
||||
# einen Reconnect überlebt.
|
||||
'seq': self.client_sequences.get((tenant_id, client_id), 0),
|
||||
# maßgebliche Zählung liegt in ws_clients und überlebt damit einen
|
||||
# Worker-Wechsel.
|
||||
'seq': store.get_last_seq(tenant_id, client_id),
|
||||
# Ob diese Client-ID bereits vor diesem Handshake bekannt war.
|
||||
# Nur dann bleibt ihre Queue auch bei einem fehlgeschlagenen
|
||||
# erneuten Handshake erhalten.
|
||||
@@ -163,9 +166,8 @@ class WebSocketBroker:
|
||||
'send_lock': Lock()
|
||||
}
|
||||
|
||||
self.client_accounts[(tenant_id, client_id)] = account_id
|
||||
self.account_clients.setdefault((tenant_id, account_id), set()).add(client_id)
|
||||
self.disconnected_clients.pop((tenant_id, client_id), None)
|
||||
self.client_sequences[key] = store.get_last_seq(tenant_id, client_id)
|
||||
self.client_delivery_locks.setdefault(key, Lock())
|
||||
return True
|
||||
|
||||
def send_to_connection(self, tenant_id, client_id, data):
|
||||
@@ -191,7 +193,7 @@ class WebSocketBroker:
|
||||
|
||||
last_seq = self.client_sequences.get(key)
|
||||
if last_seq is None:
|
||||
last_seq = int(conn.get('seq') or 0)
|
||||
last_seq = store.get_last_seq(tenant_id, client_id)
|
||||
next_seq = last_seq + 1
|
||||
payload['seq'] = next_seq
|
||||
framed = json.dumps(payload, ensure_ascii=False)
|
||||
@@ -205,6 +207,12 @@ class WebSocketBroker:
|
||||
|
||||
self.client_sequences[key] = next_seq
|
||||
conn['seq'] = next_seq
|
||||
# Die Sequenz wird erst nach erfolgreichem Senden persistiert,
|
||||
# damit ein fehlgeschlagener Versand keine Lücke erzeugt.
|
||||
store.set_last_seq(
|
||||
tenant_id, client_id, next_seq,
|
||||
account_id=conn.get('account_id')
|
||||
)
|
||||
return True
|
||||
except Exception:
|
||||
# Eine fehlerhafte Verbindung darf den Versand an andere Clients
|
||||
@@ -216,6 +224,10 @@ class WebSocketBroker:
|
||||
"""Prüft, ob ein Client den Code-0-Handshake erfolgreich absolviert hat."""
|
||||
return self.authenticated.get(tenant_id, {}).get(client_id, False)
|
||||
|
||||
def describe_connections(self, tenant_id):
|
||||
"""Liefert alle verbundenen Clients des Mandanten aus der gemeinsamen DB."""
|
||||
return store.describe_connections(tenant_id)
|
||||
|
||||
def authenticate(self, tenant_id, account_id, client_id, token):
|
||||
"""Authentifiziert eine Client-Verbindung anhand des Einmal-Tokens (Code 0).
|
||||
|
||||
@@ -257,13 +269,15 @@ class WebSocketBroker:
|
||||
if conn.get('role') == 'Gruppe' and conn.get('group_id'):
|
||||
# Ein frisch verbundener Gruppen-Client erhält eine
|
||||
# Zwei-Minuten-Kulanz, bis der erste Code-2-Pong eintrifft.
|
||||
key = (tenant_id, conn['group_id'])
|
||||
self.group_online_since[key] = time.monotonic()
|
||||
store.set_group_online_since(tenant_id, conn['group_id'])
|
||||
|
||||
self.authenticated.setdefault(tenant_id, {})[client_id] = True
|
||||
self.client_accounts[(tenant_id, client_id)] = account_id
|
||||
self.account_clients.setdefault((tenant_id, account_id), set()).add(client_id)
|
||||
self.disconnected_clients.pop((tenant_id, client_id), None)
|
||||
store.mark_authenticated(
|
||||
tenant_id, client_id, True, worker_id=self.worker_id
|
||||
)
|
||||
self.client_sequences[(tenant_id, client_id)] = store.get_last_seq(
|
||||
tenant_id, client_id
|
||||
)
|
||||
|
||||
# Zuerst die für diesen Client gepufferten Nachrichten ausliefern.
|
||||
# Wurde die Queue wegen Überschreitung der Maximalzeit verworfen, wird
|
||||
@@ -313,23 +327,26 @@ class WebSocketBroker:
|
||||
if not authenticated:
|
||||
self.authenticated.pop(tenant_id, None)
|
||||
|
||||
key = (tenant_id, client_id)
|
||||
self.client_sequences.pop(key, None)
|
||||
self.client_sequence_locks.pop(key, None)
|
||||
|
||||
if not was_authenticated and not was_known_client:
|
||||
# Ein nie erfolgreich authentifizierter neuer Client hinterlässt
|
||||
# keine Zuordnung, Queue oder Empfängerregistrierung.
|
||||
account_id = self.client_accounts.pop((tenant_id, client_id), None)
|
||||
self.client_queues.pop((tenant_id, client_id), None)
|
||||
self.disconnected_clients.pop((tenant_id, client_id), None)
|
||||
self.client_sequences.pop((tenant_id, client_id), None)
|
||||
self.client_sequence_locks.pop((tenant_id, client_id), None)
|
||||
if account_id is not None:
|
||||
clients = self.account_clients.get((tenant_id, account_id))
|
||||
if clients is not None:
|
||||
clients.discard(client_id)
|
||||
if not clients:
|
||||
self.account_clients.pop((tenant_id, account_id), None)
|
||||
store.delete_client(
|
||||
tenant_id, client_id, worker_id=self.worker_id
|
||||
)
|
||||
self.client_delivery_locks.pop(key, None)
|
||||
return
|
||||
|
||||
self.disconnected_clients[(tenant_id, client_id)] = time.monotonic()
|
||||
# Die Client-ID bleibt samt Queue bekannt. Ein Reconnect kann auf
|
||||
# einem beliebigen Worker landen und findet den Zustand dort wieder.
|
||||
# Das Delivery-Lock bleibt bestehen, damit eine laufende Zustellung
|
||||
# nicht mit einer neuen Verbindung derselben Client-ID kollidiert.
|
||||
store.mark_disconnected(
|
||||
tenant_id, client_id, worker_id=self.worker_id
|
||||
)
|
||||
|
||||
def _get_connection(self, tenant_id, client_id):
|
||||
return self.connections.get(tenant_id, {}).get(client_id)
|
||||
@@ -369,7 +386,8 @@ class WebSocketBroker:
|
||||
|
||||
recipient_rows = []
|
||||
for recipient_id in sorted(set(recipients or [])):
|
||||
account_id = self.client_accounts.get((tenant_id, recipient_id))
|
||||
client_row = store.get_client(tenant_id, recipient_id)
|
||||
account_id = client_row['account_id'] if client_row else None
|
||||
account = None
|
||||
if account_id is not None:
|
||||
account = db.execute(
|
||||
@@ -388,8 +406,12 @@ class WebSocketBroker:
|
||||
|
||||
info = self._get_sender_info(tenant_id, account)
|
||||
info['client_id'] = recipient_id
|
||||
info['connected'] = bool(self._get_connection(tenant_id, recipient_id))
|
||||
info['authenticated'] = self.is_authenticated(tenant_id, recipient_id)
|
||||
info['connected'] = bool(
|
||||
client_row and client_row['disconnected_at'] is None
|
||||
)
|
||||
info['authenticated'] = bool(
|
||||
client_row and client_row['authenticated']
|
||||
)
|
||||
recipient_rows.append(info)
|
||||
|
||||
payload = message.msg
|
||||
@@ -454,95 +476,62 @@ class WebSocketBroker:
|
||||
minutes = 60
|
||||
return max(self._client_queue_max_age_seconds(), minutes * 60)
|
||||
|
||||
def _ensure_client_queue(self, tenant_id, client_id, now=None):
|
||||
"""Liefert die Queue eines Clients und legt sie bei Bedarf an."""
|
||||
key = (tenant_id, client_id)
|
||||
queue = self.client_queues.get(key)
|
||||
if queue is None:
|
||||
queue = {
|
||||
'messages': [],
|
||||
'created_at': now if now is not None else time.monotonic(),
|
||||
'expired': False,
|
||||
'code99_only': False,
|
||||
'code99_message': None,
|
||||
'account_id': self.client_accounts.get(key),
|
||||
}
|
||||
self.client_queues[key] = queue
|
||||
return queue
|
||||
|
||||
def _expire_client_queue(self, queue, now=None):
|
||||
"""Verwirft zu alte Nachrichten und hinterlässt einen Code-99-Hinweis."""
|
||||
if not queue or queue.get('code99_only') or queue.get('expired'):
|
||||
return
|
||||
|
||||
now = now if now is not None else time.monotonic()
|
||||
if now - queue.get('created_at', now) < self._client_queue_max_age_seconds():
|
||||
return
|
||||
|
||||
queue['messages'].clear()
|
||||
queue['expired'] = True
|
||||
def _ephemeral_ttl_seconds(self):
|
||||
try:
|
||||
return max(1.0, float(current_app.config.get(
|
||||
'WS_EPHEMERAL_TTL_SECONDS', 30
|
||||
)))
|
||||
except (TypeError, ValueError):
|
||||
return 30.0
|
||||
|
||||
def _queue_undeliverable(self, tenant_id, client_id, message):
|
||||
"""Puffert eine nicht zustellbare Nachricht für einen Client."""
|
||||
if message.code < 100 and message.code != 99:
|
||||
return
|
||||
"""Puffert eine nicht zustellbare Nachricht für einen Client.
|
||||
|
||||
if (tenant_id, client_id) not in self.client_accounts:
|
||||
return
|
||||
Bei Code 2 handelt es sich um ein kurzlebiges Lebenszeichen. Es wird
|
||||
nur für aktuell verbundene Clients gepuffert, damit ein späterer
|
||||
Reconnect kein veraltetes Pong erhält.
|
||||
"""
|
||||
if message.code == 2:
|
||||
if not store.client_is_connected(tenant_id, client_id):
|
||||
return False
|
||||
elif message.code < 100 and message.code != 99:
|
||||
return False
|
||||
|
||||
with self.queue_lock:
|
||||
queue = self._ensure_client_queue(tenant_id, client_id)
|
||||
now = time.monotonic()
|
||||
if not store.client_exists(tenant_id, client_id):
|
||||
return False
|
||||
|
||||
if message.code == 99:
|
||||
# Eine nicht zustellbare Reload-Aufforderung verdrängt alle
|
||||
# älteren Nachrichten. Danach wird nichts weiter gepuffert.
|
||||
queue['messages'].clear()
|
||||
queue['code99_only'] = True
|
||||
queue['code99_message'] = message.to_json()
|
||||
queue['expired'] = False
|
||||
return
|
||||
|
||||
self._expire_client_queue(queue, now)
|
||||
if queue.get('expired') or queue.get('code99_only'):
|
||||
return
|
||||
|
||||
queue['messages'].append(message.to_json())
|
||||
queued = store.enqueue_message(
|
||||
tenant_id,
|
||||
client_id,
|
||||
message.code,
|
||||
message.to_json(),
|
||||
self._client_queue_max_age_seconds(),
|
||||
timeout_payload=self._client_queue_timeout_message(),
|
||||
ephemeral_seconds=(
|
||||
self._ephemeral_ttl_seconds() if message.code == 2 else None
|
||||
)
|
||||
)
|
||||
if queued:
|
||||
self.delivery_wakeup.set()
|
||||
return queued
|
||||
|
||||
def cleanup_client_queues(self):
|
||||
"""Räumt abgelaufene Client-Queues und verwaiste Webviews auf."""
|
||||
now = time.monotonic()
|
||||
retention = self._client_retention_seconds()
|
||||
with self.queue_lock:
|
||||
for queue in self.client_queues.values():
|
||||
self._expire_client_queue(queue, now)
|
||||
"""Räumt abgelaufene Queues und verwaiste Clients in der DB auf."""
|
||||
store.purge_expired_queue_rows()
|
||||
store.expire_queues(
|
||||
self._client_queue_max_age_seconds(),
|
||||
self._client_queue_timeout_message()
|
||||
)
|
||||
store.cleanup_clients(self._client_retention_seconds())
|
||||
|
||||
for key, disconnected_at in list(self.disconnected_clients.items()):
|
||||
tenant_id, client_id = key
|
||||
if self._get_connection(tenant_id, client_id):
|
||||
self.disconnected_clients.pop(key, None)
|
||||
continue
|
||||
if now - disconnected_at < retention:
|
||||
continue
|
||||
|
||||
queue = self.client_queues.get(key)
|
||||
# Solange noch zustellbare Nachrichten warten, bleibt der
|
||||
# Client registriert. Danach darf die verwaiste Webview
|
||||
# inklusive Code-99-Tombstone verworfen werden.
|
||||
if queue and not queue.get('expired') and not queue.get('code99_only'):
|
||||
continue
|
||||
|
||||
account_id = self.client_accounts.pop(key, None)
|
||||
self.client_queues.pop(key, None)
|
||||
self.disconnected_clients.pop(key, None)
|
||||
# Lokale Caches für inzwischen entfernte Clients bereinigen.
|
||||
for key in list(self.client_sequences):
|
||||
if not store.client_exists(*key):
|
||||
self.client_sequences.pop(key, None)
|
||||
self.client_sequence_locks.pop(key, None)
|
||||
if account_id is not None:
|
||||
clients = self.account_clients.get((tenant_id, account_id))
|
||||
if clients is not None:
|
||||
clients.discard(client_id)
|
||||
if not clients:
|
||||
self.account_clients.pop((tenant_id, account_id), None)
|
||||
for key in list(self.client_delivery_locks):
|
||||
if not store.client_exists(*key):
|
||||
self.client_delivery_locks.pop(key, None)
|
||||
|
||||
def _client_queue_timeout_message(self):
|
||||
minutes = current_app.config.get('WS_QUEUE_MAX_AGE_MINUTES', 15)
|
||||
@@ -556,8 +545,13 @@ class WebSocketBroker:
|
||||
)
|
||||
).to_json()
|
||||
|
||||
def _client_delivery_lock(self, tenant_id, client_id):
|
||||
return self.client_delivery_locks.setdefault(
|
||||
(tenant_id, client_id), Lock()
|
||||
)
|
||||
|
||||
def restore_client_queue(self, tenant_id, client_id):
|
||||
"""Liefert gepufferte Nachrichten eines wiedererkannten Clients aus.
|
||||
"""Liefert persistierte Nachrichten eines wiedererkannten Clients aus.
|
||||
|
||||
Rückgabe: (Menge der Roh-Nachrichten aus der Queue, Late-Entry-Sperre).
|
||||
Die Menge dient dazu, dieselben Nachrichten nicht zusätzlich als
|
||||
@@ -565,57 +559,66 @@ class WebSocketBroker:
|
||||
war oder nur noch eine Code-99-Nachricht enthielt. In diesem Fall darf
|
||||
keine zusätzliche Late-Entry-Historie mehr gesendet werden.
|
||||
"""
|
||||
key = (tenant_id, client_id)
|
||||
now = time.monotonic()
|
||||
|
||||
with self.queue_lock:
|
||||
queue = self.client_queues.get(key)
|
||||
if not queue:
|
||||
with self._client_delivery_lock(tenant_id, client_id):
|
||||
rows = store.fetch_queue(tenant_id, client_id)
|
||||
if not rows:
|
||||
return set(), False
|
||||
self._expire_client_queue(queue, now)
|
||||
|
||||
if queue.get('code99_only'):
|
||||
raw_message = queue.get('code99_message') or self._client_queue_timeout_message()
|
||||
self.client_queues.pop(key, None)
|
||||
send_only = True
|
||||
messages = []
|
||||
elif queue.get('expired'):
|
||||
raw_message = self._client_queue_timeout_message()
|
||||
self.client_queues.pop(key, None)
|
||||
send_only = True
|
||||
messages = []
|
||||
started_at = store.get_queue_started_at(tenant_id, client_id)
|
||||
max_age = self._client_queue_max_age_seconds()
|
||||
if started_at is not None and store.now() - started_at >= max_age:
|
||||
store.replace_queue_with_timeout(
|
||||
tenant_id, client_id, self._client_queue_timeout_message()
|
||||
)
|
||||
rows = store.fetch_queue(tenant_id, client_id)
|
||||
suppress_late_entries = True
|
||||
else:
|
||||
raw_message = None
|
||||
send_only = False
|
||||
messages = list(queue.get('messages', []))
|
||||
queue['messages'] = []
|
||||
suppress_late_entries = any(
|
||||
row['code99_only'] for row in rows
|
||||
)
|
||||
|
||||
if send_only:
|
||||
if raw_message and not self.send_to_connection(tenant_id, client_id, raw_message):
|
||||
# Verbindung ist bereits wieder weg: Queue für den nächsten
|
||||
# Versuch erhalten.
|
||||
with self.queue_lock:
|
||||
self.client_queues.setdefault(key, queue)
|
||||
return set(), True
|
||||
raw_messages = set()
|
||||
for row in rows:
|
||||
raw_message = row['payload']
|
||||
if not self.send_to_connection(tenant_id, client_id, raw_message):
|
||||
# Verbindung ist bereits wieder weg. Noch nicht
|
||||
# zugestellte Aufträge bleiben in der Queue.
|
||||
break
|
||||
if not row['code99_only']:
|
||||
raw_messages.add(raw_message)
|
||||
store.delete_queue_row(row['id'])
|
||||
|
||||
unsent = []
|
||||
for index, raw_message in enumerate(messages):
|
||||
if not self.send_to_connection(tenant_id, client_id, raw_message):
|
||||
unsent = messages[index:]
|
||||
break
|
||||
return raw_messages, suppress_late_entries
|
||||
|
||||
with self.queue_lock:
|
||||
current = self.client_queues.get(key)
|
||||
if current is not None:
|
||||
if unsent:
|
||||
current['messages'] = unsent + current.get('messages', [])
|
||||
if not current.get('messages'):
|
||||
self.client_queues.pop(key, None)
|
||||
def drain_client_queue(self, tenant_id, client_id):
|
||||
"""Stellt die gemeinsame Queue eines lokal verbundenen Clients zu."""
|
||||
self.restore_client_queue(tenant_id, client_id)
|
||||
|
||||
# Auch nicht zugestellte Queue-Nachrichten von den Late Entries
|
||||
# ausnehmen. Sie bleiben in der Queue und werden beim nächsten
|
||||
# Reconnect erneut versucht, statt doppelt gepuffert zu werden.
|
||||
return set(messages), False
|
||||
def drain_local_clients(self):
|
||||
"""Zustellrunde für alle lokal verbundenen, authentifizierten Clients."""
|
||||
local_clients = set()
|
||||
for tenant_id, connections in list(self.connections.items()):
|
||||
for client_id in list(connections):
|
||||
if self.is_authenticated(tenant_id, client_id):
|
||||
local_clients.add((tenant_id, client_id))
|
||||
|
||||
if not local_clients:
|
||||
return
|
||||
|
||||
# Nur Clients mit tatsächlich wartenden Aufträgen öffnen eine
|
||||
# Transaktion. Das hält die Polling-Schleife bei vielen verbundenen
|
||||
# Clients günstig.
|
||||
for tenant_id, client_id in store.clients_with_queue(local_clients):
|
||||
try:
|
||||
self.drain_client_queue(tenant_id, client_id)
|
||||
except Exception as exc:
|
||||
try:
|
||||
current_app.logger.warning(
|
||||
'WS-Queue-Zustellung fehlgeschlagen: tenant=%s client=%s error=%s',
|
||||
tenant_id, client_id, exc
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Late Entry
|
||||
@@ -881,7 +884,7 @@ class WebSocketBroker:
|
||||
"""Wertet ein Code-2-Lebenszeichen eines Clients aus."""
|
||||
conn = self._get_connection(tenant_id, client_id) if client_id else None
|
||||
if conn and conn.get('account_id') == account_id:
|
||||
conn['last_pong_at'] = time.monotonic()
|
||||
conn['last_pong_at'] = time.time()
|
||||
|
||||
if not sender or sender['role'] != 'Gruppe':
|
||||
return
|
||||
@@ -897,9 +900,8 @@ class WebSocketBroker:
|
||||
if not group:
|
||||
return
|
||||
|
||||
now = time.monotonic()
|
||||
group_id = group['id']
|
||||
self.group_last_pong[(tenant_id, group_id)] = now
|
||||
store.record_group_pong(tenant_id, group_id)
|
||||
|
||||
if group['state'] == 'unterwegs':
|
||||
self._set_group_state_internal(
|
||||
@@ -917,11 +919,16 @@ class WebSocketBroker:
|
||||
return False
|
||||
|
||||
old_state = group['state']
|
||||
db.execute(
|
||||
# Der Vergleich im UPDATE verhindert, dass zwei Worker denselben
|
||||
# automatischen Statuswechsel gleichzeitig in die Historie schreiben.
|
||||
cursor = db.execute(
|
||||
'UPDATE groups SET state = ?, updated_at = CURRENT_TIMESTAMP '
|
||||
'WHERE id = ? AND tenant_id = ?',
|
||||
(new_state, group_id, tenant_id)
|
||||
'WHERE id = ? AND tenant_id = ? AND state = ?',
|
||||
(new_state, group_id, tenant_id, old_state)
|
||||
)
|
||||
if cursor.rowcount == 0:
|
||||
db.rollback()
|
||||
return False
|
||||
db.execute(
|
||||
'''INSERT INTO group_state_history
|
||||
(tenant_id, group_id, from_state, to_state, last_lat, last_lon,
|
||||
@@ -937,7 +944,7 @@ class WebSocketBroker:
|
||||
)
|
||||
|
||||
if new_state == 'online':
|
||||
self.group_online_since[(tenant_id, group_id)] = time.monotonic()
|
||||
store.set_group_online_since(tenant_id, group_id)
|
||||
|
||||
message = WSMessage(
|
||||
sender_id=actor_account_id or 0,
|
||||
@@ -972,20 +979,24 @@ class WebSocketBroker:
|
||||
except (TypeError, ValueError):
|
||||
timeout = 120.0
|
||||
|
||||
now = time.monotonic()
|
||||
current = store.now()
|
||||
for row in rows:
|
||||
key = (row['tenant_id'], row['id'])
|
||||
reference = self.group_last_pong.get(key)
|
||||
online_since = self.group_online_since.get(key)
|
||||
presence = store.get_group_presence(row['tenant_id'], row['id'])
|
||||
last_pong = presence['last_pong_at'] if presence else None
|
||||
online_since = presence['online_since'] if presence else None
|
||||
reference = last_pong
|
||||
if online_since is not None:
|
||||
reference = max(reference, online_since) if reference else online_since
|
||||
reference = (
|
||||
max(reference, online_since)
|
||||
if reference is not None else online_since
|
||||
)
|
||||
if reference is None:
|
||||
# Zustand war bereits vor dem Start des Trackings "online".
|
||||
# Ab jetzt läuft die Kulanzfrist.
|
||||
self.group_online_since[key] = now
|
||||
store.set_group_online_since(row['tenant_id'], row['id'], current)
|
||||
continue
|
||||
|
||||
if now - reference > timeout:
|
||||
if current - reference > timeout:
|
||||
self._set_group_state_internal(
|
||||
row['tenant_id'], row['id'], 'unterwegs'
|
||||
)
|
||||
@@ -1158,7 +1169,7 @@ class WebSocketBroker:
|
||||
db.commit()
|
||||
GroupsService.update_cache_entry(tenant_id, group_id, {'state': new_state})
|
||||
if new_state == 'online':
|
||||
self.group_online_since[(tenant_id, group_id)] = time.monotonic()
|
||||
store.set_group_online_since(tenant_id, group_id)
|
||||
self._log_business(tenant_id, sender['id'], 'group.state_change', 'group',
|
||||
group_id, {'from': group['state'], 'to': new_state})
|
||||
|
||||
@@ -1402,34 +1413,40 @@ class WebSocketBroker:
|
||||
return message
|
||||
|
||||
def _deliver(self, tenant_id, message, sender):
|
||||
"""Stellt eine Nachricht an alle berechtigten Clients zu."""
|
||||
"""Stellt eine Nachricht an alle berechtigten Clients zu.
|
||||
|
||||
Lokal verbundene Clients erhalten den Frame direkt. Für alle anderen
|
||||
Clients wird ein persistenter Auftrag in der gemeinsamen Queue
|
||||
angelegt. Jeder Worker pollt diese Queue für seine eigenen Clients.
|
||||
"""
|
||||
recipients = sorted(self._get_recipients(tenant_id, message, sender))
|
||||
self.log_incoming(tenant_id, message, sender, recipients=recipients)
|
||||
for client_id in recipients:
|
||||
self._send(tenant_id, client_id, message)
|
||||
self.delivery_wakeup.set()
|
||||
|
||||
def _send(self, tenant_id, client_id, message):
|
||||
"""Sendet eine Nachricht an einen Client oder puffert sie für ihn."""
|
||||
# Erst nach erfolgreicher Token-Authentifizierung dürfen Nachrichten
|
||||
# an einen Client zugestellt werden.
|
||||
if not self.is_authenticated(tenant_id, client_id):
|
||||
self._queue_undeliverable(tenant_id, client_id, message)
|
||||
return False
|
||||
conn = self._get_connection(tenant_id, client_id)
|
||||
authenticated = self.is_authenticated(tenant_id, client_id)
|
||||
|
||||
if self.send_to_connection(tenant_id, client_id, message.to_json()):
|
||||
return True
|
||||
# Ein lokal verbundener Client ohne wartende Queue wird direkt
|
||||
# bedient. Existiert bereits eine Queue, wird auch diese Nachricht
|
||||
# eingereiht, damit die Reihenfolge erhalten bleibt.
|
||||
if conn and authenticated and not store.client_has_queue(tenant_id, client_id):
|
||||
if self.send_to_connection(tenant_id, client_id, message.to_json()):
|
||||
return True
|
||||
|
||||
self._queue_undeliverable(tenant_id, client_id, message)
|
||||
return False
|
||||
|
||||
def _client_ids_for_accounts(self, tenant_id, account_ids):
|
||||
"""Expandiert Empfänger-Accounts auf alle bekannten Client-IDs."""
|
||||
client_ids = set()
|
||||
for account_id in account_ids:
|
||||
client_ids.update(
|
||||
self.account_clients.get((tenant_id, account_id), ())
|
||||
)
|
||||
return client_ids
|
||||
"""Expandiert Empfänger-Accounts auf alle bekannten Client-IDs.
|
||||
|
||||
Die Zuordnung liegt in ws_clients und umfasst damit auch Clients, die
|
||||
an anderen Workern verbunden oder momentan getrennt sind.
|
||||
"""
|
||||
return store.client_ids_for_accounts(tenant_id, account_ids)
|
||||
|
||||
def _get_recipients(self, tenant_id, message, sender):
|
||||
"""Bestimmt den Empfängerkreis abhängig vom Nachrichtencode.
|
||||
|
||||
Reference in new issue
Block a user