feat(backend_server.py): implement message handling
This commit is contained in:
@@ -6,13 +6,18 @@ import selectors
|
||||
import socket
|
||||
import threading
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
import yaml
|
||||
|
||||
from typing import Any
|
||||
|
||||
from judas_protocol import Category, ControlAction, Message
|
||||
|
||||
from judas_server.backend.client import Client, ClientStatus
|
||||
from judas_server.backend.handler.hello_handler import HelloHandler
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Callable
|
||||
|
||||
from judas_protocol import ActionType
|
||||
|
||||
|
||||
class BackendServer:
|
||||
@@ -41,13 +46,25 @@ class BackendServer:
|
||||
)
|
||||
|
||||
self.clients: dict[str, Client] = {}
|
||||
|
||||
self.known_clients: dict[str, dict[str, str | float]] = (
|
||||
self._load_known_clients()
|
||||
)
|
||||
|
||||
self.message_handlers: dict[
|
||||
tuple[Category, ActionType], Callable[[Client, Message], None]
|
||||
] = {}
|
||||
|
||||
self.running: bool = False
|
||||
|
||||
def _initialize_handlers(self) -> None:
|
||||
"""Initialize message handlers."""
|
||||
|
||||
hello_handler = HelloHandler(self)
|
||||
|
||||
self.message_handlers[(Category.CONTROL, ControlAction.HELLO)] = (
|
||||
hello_handler.handle
|
||||
)
|
||||
|
||||
def _load_known_clients(self) -> dict[str, dict[str, str | float]]:
|
||||
"""Load the list of known clients from a YAML file and validate."""
|
||||
known_clients: dict[str, dict[str, str | float]] = {}
|
||||
@@ -286,6 +303,29 @@ class BackendServer:
|
||||
try:
|
||||
msg = Message.from_bytes(line)
|
||||
self.logger.info(f"[.] Parsed message {msg.id}")
|
||||
|
||||
if client.id is None:
|
||||
self.logger.debug(
|
||||
f"Client {client} has no ID, expecting HELLO message..."
|
||||
)
|
||||
if (
|
||||
msg.category != Category.CONTROL
|
||||
or msg.action != ControlAction.HELLO
|
||||
):
|
||||
self.logger.warning(
|
||||
f"First message from {client} must be HELLO, disconnecting..."
|
||||
)
|
||||
self._disconnect(client)
|
||||
return
|
||||
|
||||
handler: Callable[[Client, Message], None] | None = (
|
||||
self.message_handlers.get(
|
||||
(msg.category, msg.action), None
|
||||
)
|
||||
)
|
||||
if handler is not None:
|
||||
handler(client, msg)
|
||||
|
||||
if msg.ack_required:
|
||||
self.send_ack(client, target_id=msg.id)
|
||||
except Exception as e:
|
||||
|
||||
Reference in New Issue
Block a user