|
| 1 | +from functools import partial |
| 2 | +import uuid |
| 3 | + |
| 4 | +import json |
| 5 | +import pickle |
| 6 | +import six |
| 7 | + |
| 8 | +from .asyncio_manager import AsyncManager |
| 9 | + |
| 10 | + |
| 11 | +class AsyncPubSubManager(AsyncManager): |
| 12 | + """Manage a client list attached to a pub/sub backend under asyncio. |
| 13 | +
|
| 14 | + This is a base class that enables multiple servers to share the list of |
| 15 | + clients, with the servers communicating events through a pub/sub backend. |
| 16 | + The use of a pub/sub backend also allows any client connected to the |
| 17 | + backend to emit events addressed to Socket.IO clients. |
| 18 | +
|
| 19 | + The actual backends must be implemented by subclasses, this class only |
| 20 | + provides a pub/sub generic framework for asyncio applications. |
| 21 | +
|
| 22 | + :param channel: The channel name on which the server sends and receives |
| 23 | + notifications. |
| 24 | + """ |
| 25 | + name = 'asyncpubsub' |
| 26 | + |
| 27 | + def __init__(self, channel='socketio', write_only=False): |
| 28 | + super().__init__() |
| 29 | + self.channel = channel |
| 30 | + self.write_only = write_only |
| 31 | + self.host_id = uuid.uuid4().hex |
| 32 | + |
| 33 | + def initialize(self): |
| 34 | + super().initialize() |
| 35 | + if not self.write_only: |
| 36 | + self.thread = self.server.start_background_task(self._thread) |
| 37 | + self.server.logger.info(self.name + ' backend initialized.') |
| 38 | + |
| 39 | + async def emit(self, event, data, namespace=None, room=None, skip_sid=None, |
| 40 | + callback=None, **kwargs): |
| 41 | + """Emit a message to a single client, a room, or all the clients |
| 42 | + connected to the namespace. |
| 43 | +
|
| 44 | + This method takes care or propagating the message to all the servers |
| 45 | + that are connected through the message queue. |
| 46 | +
|
| 47 | + The parameters are the same as in :meth:`.Server.emit`. |
| 48 | +
|
| 49 | + Note: this method is a coroutine. |
| 50 | + """ |
| 51 | + if kwargs.get('ignore_queue'): |
| 52 | + return await super().emit( |
| 53 | + event, data, namespace=namespace, room=room, skip_sid=skip_sid, |
| 54 | + callback=callback) |
| 55 | + namespace = namespace or '/' |
| 56 | + if callback is not None: |
| 57 | + if self.server is None: |
| 58 | + raise RuntimeError('Callbacks can only be issued from the ' |
| 59 | + 'context of a server.') |
| 60 | + if room is None: |
| 61 | + raise ValueError('Cannot use callback without a room set.') |
| 62 | + id = self._generate_ack_id(room, namespace, callback) |
| 63 | + callback = (room, namespace, id) |
| 64 | + else: |
| 65 | + callback = None |
| 66 | + await self._publish({'method': 'emit', 'event': event, 'data': data, |
| 67 | + 'namespace': namespace, 'room': room, |
| 68 | + 'skip_sid': skip_sid, 'callback': callback}) |
| 69 | + |
| 70 | + async def close_room(self, room, namespace=None): |
| 71 | + await self._publish({'method': 'close_room', 'room': room, |
| 72 | + 'namespace': namespace or '/'}) |
| 73 | + |
| 74 | + async def _publish(self, data): |
| 75 | + """Publish a message on the Socket.IO channel. |
| 76 | +
|
| 77 | + This method needs to be implemented by the different subclasses that |
| 78 | + support pub/sub backends. |
| 79 | + """ |
| 80 | + raise NotImplementedError('This method must be implemented in a ' |
| 81 | + 'subclass.') # pragma: no cover |
| 82 | + |
| 83 | + async def _listen(self): |
| 84 | + """Return the next message published on the Socket.IO channel, |
| 85 | + blocking until a message is available. |
| 86 | +
|
| 87 | + This method needs to be implemented by the different subclasses that |
| 88 | + support pub/sub backends. |
| 89 | + """ |
| 90 | + raise NotImplementedError('This method must be implemented in a ' |
| 91 | + 'subclass.') # pragma: no cover |
| 92 | + |
| 93 | + async def _handle_emit(self, message): |
| 94 | + # Events with callbacks are very tricky to handle across hosts |
| 95 | + # Here in the receiving end we set up a local callback that preserves |
| 96 | + # the callback host and id from the sender |
| 97 | + remote_callback = message.get('callback') |
| 98 | + if remote_callback is not None and len(remote_callback) == 3: |
| 99 | + callback = partial(self._return_callback, self.host_id, |
| 100 | + *remote_callback) |
| 101 | + else: |
| 102 | + callback = None |
| 103 | + await super().emit(message['event'], message['data'], |
| 104 | + namespace=message.get('namespace'), |
| 105 | + room=message.get('room'), |
| 106 | + skip_sid=message.get('skip_sid'), |
| 107 | + callback=callback) |
| 108 | + |
| 109 | + async def _handle_callback(self, message): |
| 110 | + if self.host_id == message.get('host_id'): |
| 111 | + try: |
| 112 | + sid = message['sid'] |
| 113 | + namespace = message['namespace'] |
| 114 | + id = message['id'] |
| 115 | + args = message['args'] |
| 116 | + except KeyError: |
| 117 | + return |
| 118 | + await self.trigger_callback(sid, namespace, id, args) |
| 119 | + |
| 120 | + async def _return_callback(self, host_id, sid, namespace, callback_id, |
| 121 | + *args): |
| 122 | + # When an event callback is received, the callback is returned back |
| 123 | + # the sender, which is identified by the host_id |
| 124 | + await self._publish({'method': 'callback', 'host_id': host_id, |
| 125 | + 'sid': sid, 'namespace': namespace, |
| 126 | + 'id': callback_id, 'args': args}) |
| 127 | + |
| 128 | + async def _handle_close_room(self, message): |
| 129 | + await super().close_room( |
| 130 | + room=message.get('room'), namespace=message.get('namespace')) |
| 131 | + |
| 132 | + async def _thread(self): |
| 133 | + while True: |
| 134 | + try: |
| 135 | + message = await self._listen() |
| 136 | + except: |
| 137 | + import traceback |
| 138 | + traceback.print_exc() |
| 139 | + break |
| 140 | + data = None |
| 141 | + if isinstance(message, dict): |
| 142 | + data = message |
| 143 | + else: |
| 144 | + if isinstance(message, six.binary_type): # pragma: no cover |
| 145 | + try: |
| 146 | + data = pickle.loads(message) |
| 147 | + except: |
| 148 | + pass |
| 149 | + if data is None: |
| 150 | + try: |
| 151 | + data = json.loads(message) |
| 152 | + except: |
| 153 | + pass |
| 154 | + if data and 'method' in data: |
| 155 | + if data['method'] == 'emit': |
| 156 | + await self._handle_emit(data) |
| 157 | + elif data['method'] == 'callback': |
| 158 | + await self._handle_callback(data) |
| 159 | + elif data['method'] == 'close_room': |
| 160 | + await self._handle_close_room(data) |
0 commit comments