baseimage-tutorial-framework/lib/tfw/server/zmq_websocket_router.py

73 lines
2.1 KiB
Python
Raw Normal View History

# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
# All Rights Reserved. See LICENSE file for details.
import json
2019-06-10 13:32:45 +00:00
import logging
from tornado.websocket import WebSocketHandler
2019-05-27 12:09:13 +00:00
from tfw.networking import Scope
LOG = logging.getLogger(__name__)
class ZMQWebSocketRouter(WebSocketHandler):
# pylint: disable=abstract-method
instances = set()
2018-04-06 14:52:23 +00:00
def initialize(self, **kwargs): # pylint: disable=arguments-differ
2019-05-26 16:26:33 +00:00
self.event_handler_connector = kwargs['event_handler_connector']
self.tfw_router = TFWRouter(self.send_to_zmq, self.send_to_websockets)
def send_to_zmq(self, message):
self.event_handler_connector.send_message(message)
@classmethod
def send_to_websockets(cls, message):
for instance in cls.instances:
2019-05-26 16:26:33 +00:00
instance.write_message(message)
def prepare(self):
type(self).instances.add(self)
def on_close(self):
type(self).instances.remove(self)
def open(self, *args, **kwargs):
2019-05-26 16:26:33 +00:00
LOG.debug('WebSocket connection initiated!')
self.event_handler_connector.register_callback(self.zmq_callback)
def zmq_callback(self, message):
LOG.debug('Received on ZMQ pull socket: %s', message)
self.tfw_router.route(message)
def on_message(self, message):
message = json.loads(message)
LOG.debug('Received on WebSocket: %s', message)
2019-05-26 16:26:33 +00:00
self.tfw_router.route(message)
# much secure, very cors, wow
def check_origin(self, origin):
return True
2019-05-26 16:26:33 +00:00
class TFWRouter:
def __init__(self, send_to_zmq, send_to_websockets):
self.send_to_zmq = send_to_zmq
self.send_to_websockets = send_to_websockets
2019-05-26 16:26:33 +00:00
def route(self, message):
scope = Scope(message.get('scope', 'zmq'))
2019-05-26 16:26:33 +00:00
routing_table = {
Scope.ZMQ: self.send_to_zmq,
Scope.WEBSOCKET: self.send_to_websockets,
Scope.BROADCAST: self.broadcast
}
2019-05-26 16:26:33 +00:00
action = routing_table[scope]
action(message)
def broadcast(self, message):
2019-05-26 16:26:33 +00:00
self.send_to_zmq(message)
self.send_to_websockets(message)