mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-09 17:47:16 +00:00
147 lines
4.5 KiB
Python
147 lines
4.5 KiB
Python
# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
|
|
# All Rights Reserved. See LICENSE file for details.
|
|
|
|
from abc import ABC, abstractmethod
|
|
from json import dumps
|
|
from hashlib import md5
|
|
|
|
from tfw.networking.event_handlers import ServerConnector
|
|
from tfw.config.logs import logging
|
|
|
|
LOG = logging.getLogger(__name__)
|
|
|
|
|
|
class EventHandlerBase(ABC):
|
|
"""
|
|
Abstract base class for all Python based EventHandlers. Useful implementation template
|
|
for other languages.
|
|
|
|
Derived classes must implement the handle_event() method
|
|
"""
|
|
def __init__(self, key):
|
|
self.server_connector = ServerConnector()
|
|
self.key = key
|
|
self.subscribe(self.key, 'reset')
|
|
self.server_connector.register_callback(self.event_handler_callback)
|
|
|
|
def event_handler_callback(self, message):
|
|
"""
|
|
Callback that is invoked when receiving a message.
|
|
Dispatches messages to handler methods and sends
|
|
a response back in case the handler returned something.
|
|
This is subscribed in __init__().
|
|
"""
|
|
response = self.dispatch_handling(message)
|
|
if response:
|
|
self.server_connector.send(response)
|
|
|
|
def dispatch_handling(self, message):
|
|
"""
|
|
Used to dispatch messages to their specific handlers.
|
|
|
|
:param message: the message received
|
|
:returns: the message to send back
|
|
"""
|
|
if message['key'] != 'reset':
|
|
return self.handle_event(message)
|
|
return self.handle_reset(message)
|
|
|
|
@abstractmethod
|
|
def handle_event(self, message):
|
|
"""
|
|
Abstract method that implements the handling of messages.
|
|
|
|
:param message: the message received
|
|
:returns: the message to send back
|
|
"""
|
|
raise NotImplementedError
|
|
|
|
def handle_reset(self, message):
|
|
# pylint: disable=unused-argument,no-self-use
|
|
"""
|
|
Usually 'reset' events receive some sort of special treatment.
|
|
|
|
:param message: the message received
|
|
:returns: the message to send back
|
|
"""
|
|
return None
|
|
|
|
def subscribe(self, *keys):
|
|
"""
|
|
Subscribe this EventHandler to receive events for given keys.
|
|
Note that you can subscribe to the same key several times in which
|
|
case you will need to unsubscribe multiple times in order to stop
|
|
receiving events.
|
|
|
|
:param keys: list of keys to subscribe to
|
|
"""
|
|
for key in keys:
|
|
self.server_connector.subscribe(key)
|
|
|
|
def unsubscribe(self, *keys):
|
|
"""
|
|
Unsubscribe this eventhandler from the given keys.
|
|
|
|
:param keys: list of keys to unsubscribe from
|
|
"""
|
|
for key in keys:
|
|
self.server_connector.unsubscribe(key)
|
|
|
|
def cleanup(self):
|
|
"""
|
|
Perform cleanup actions such as releasing database
|
|
connections and stuff like that.
|
|
"""
|
|
pass
|
|
|
|
|
|
class TriggeredEventHandler(EventHandlerBase, ABC):
|
|
# pylint: disable=abstract-method
|
|
"""
|
|
Abstract base class for EventHandlers which are only triggered in case
|
|
TFWServer has successfully triggered an FSM step defined in __init__.
|
|
"""
|
|
def __init__(self, key, trigger):
|
|
super().__init__(key)
|
|
self.trigger = trigger
|
|
|
|
def dispatch_handling(self, message):
|
|
if message.get('trigger') == self.trigger:
|
|
return super().dispatch_handling(message)
|
|
return None
|
|
|
|
|
|
class BroadcastingEventHandler(EventHandlerBase, ABC):
|
|
# pylint: disable=abstract-method
|
|
"""
|
|
Abstract base class for EventHandlers which broadcast responses
|
|
and intelligently ignore their own broadcasted messages they receive.
|
|
"""
|
|
def __init__(self, key):
|
|
super().__init__(key)
|
|
self.own_message_hashes = []
|
|
|
|
def event_handler_callback(self, message):
|
|
message_hash = self.hash_message(message)
|
|
|
|
if message_hash in self.own_message_hashes:
|
|
self.own_message_hashes.remove(message_hash)
|
|
return
|
|
|
|
response = self.dispatch_handling(message)
|
|
if response:
|
|
self.own_message_hashes.append(self.hash_message(response))
|
|
self.server_connector.send(self.make_broadcast_message(response))
|
|
|
|
@staticmethod
|
|
def hash_message(message):
|
|
message_bytes = dumps(message, sort_keys=True).encode()
|
|
return md5(message_bytes).hexdigest()
|
|
|
|
@staticmethod
|
|
def make_broadcast_message(message):
|
|
return {
|
|
'key': 'broadcast',
|
|
'data': message
|
|
}
|