/usr/lib/python3/dist-packages/tornadio2/conn.py is in python3-tornadio2 0.0.4-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 | # -*- coding: utf-8 -*-
#
# Copyright: (c) 2011 by the Serge S. Koval, see AUTHORS for more details.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
tornadio2.conn
~~~~~~~~~~~~~~
Tornadio connection implementation.
"""
import time
import logging
from inspect import ismethod, getmembers
from tornadio2 import proto
from tornadio2.py2compat import with_metaclass
def event(name_or_func):
"""Event handler decorator.
Can be used with event name or will automatically use function name
if not provided::
# Will handle 'foo' event
@event('foo')
def bar(self):
pass
# Will handle 'baz' event
@event
def baz(self):
pass
"""
if callable(name_or_func):
name_or_func._event_name = name_or_func.__name__
return name_or_func
def handler(f):
f._event_name = name_or_func
return f
return handler
class EventMagicMeta(type):
"""Event handler metaclass"""
def __init__(cls, name, bases, attrs):
# find events, also in bases
is_event = lambda x: hasattr(x, '_event_name')
events = [(e._event_name, e) for _, e in getmembers(cls, is_event)]
setattr(cls, '_events', dict(events))
# Call base
super(EventMagicMeta, cls).__init__(name, bases, attrs)
class SocketConnection(with_metaclass(EventMagicMeta, object)):
"""Subclass this class and define at least `on_message()` method to make a Socket.IO
connection handler.
To support socket.io connection multiplexing, define `_endpoints_`
dictionary on class level, where key is endpoint name and value is
connection class::
class MyConnection(SocketConnection):
__endpoints__ = {'/clock'=ClockConnection,
'/game'=GameConnection}
``ClockConnection`` and ``GameConnection`` should derive from the ``SocketConnection`` class as well.
``SocketConnection`` has useful ``event`` decorator. Wrap method with it::
class MyConnection(SocketConnection):
@event('test')
def test(self, msg):
print msg
and then, when client will emit 'test' event, you should see 'Hello World' printed::
sock.emit('test', {msg:'Hello World'});
"""
__endpoints__ = dict()
def __init__(self, session, endpoint=None):
"""Connection constructor.
`session`
Associated session
`endpoint`
Endpoint name
"""
self.session = session
self.endpoint = endpoint
self.is_closed = False
self.ack_id = 1
self.ack_queue = dict()
self._event_worker = None
# Public API
def on_open(self, request):
"""Default on_open() handler.
Override when you need to do some initialization or request validation.
If you return False, connection will be rejected.
You can also throw Tornado HTTPError to close connection.
`request`
``ConnectionInfo`` object which contains caller IP address, query string
parameters and cookies associated with this request.
For example::
class MyConnection(SocketConnection):
def on_open(self, request):
self.user_id = request.get_argument('id', None)
if not self.user_id:
return False
"""
pass
def on_message(self, message):
"""Default on_message handler. Must be overridden in your application"""
raise NotImplementedError()
def on_event(self, name, args=[], kwargs=dict()):
"""Default on_event handler.
By default, it uses decorator-based approach to handle events,
but you can override it to implement custom event handling.
`name`
Event name
`args`
Event args
`kwargs`
Event kwargs
There's small magic around event handling.
If you send exactly one parameter from the client side and it is dict,
then you will receive parameters in dict in `kwargs`. In all other
cases you will have `args` list.
For example, if you emit event like this on client-side::
sock.emit('test', {msg='Hello World'})
you will have following parameter values in your on_event callback::
name = 'test'
args = []
kwargs = {msg: 'Hello World'}
However, if you emit event like this::
sock.emit('test', 'a', 'b', {msg='Hello World'})
you will have following parameter values::
name = 'test'
args = ['a', 'b', {msg: 'Hello World'}]
kwargs = {}
"""
handler = self._events.get(name)
if handler:
try:
if args:
return handler(self, *args)
else:
return handler(self, **kwargs)
except TypeError:
if args:
logging.error(('Attempted to call event handler %s ' +
'with %s arguments.') % (handler,
repr(args)))
else:
logging.error(('Attempted to call event handler %s ' +
'with %s arguments.') % (handler,
repr(kwargs)))
raise
else:
logging.error('Invalid event name: %s' % name)
def on_close(self):
"""Default on_close handler."""
pass
def send(self, message, callback=None, force_json=False):
"""Send message to the client.
`message`
Message to send.
`callback`
Optional callback. If passed, callback will be called
when client received sent message and sent acknowledgment
back.
`force_json`
Optional argument. If set to True (and message is a string)
then the message type will be JSON (Type 4 in socket_io protocol).
This is what you want, when you send already json encoded strings.
"""
if self.is_closed:
return
if callback is not None:
msg = proto.message(self.endpoint,
message,
self.queue_ack(callback, message), force_json)
else:
msg = proto.message(self.endpoint, message, force_json=force_json)
self.session.send_message(msg)
def emit(self, name, *args, **kwargs):
"""Send socket.io event.
`name`
Name of the event
`kwargs`
Optional event parameters
"""
if self.is_closed:
return
msg = proto.event(self.endpoint, name, None, *args, **kwargs)
self.session.send_message(msg)
def emit_ack(self, callback, name, *args, **kwargs):
"""Send socket.io event with acknowledgment.
`callback`
Acknowledgment callback
`name`
Name of the event
`kwargs`
Optional event parameters
"""
if self.is_closed:
return
msg = proto.event(self.endpoint,
name,
self.queue_ack(callback, (name, args, kwargs)),
*args,
**kwargs)
self.session.send_message(msg)
def close(self):
"""Forcibly close client connection"""
self.session.close(self.endpoint)
# TODO: Notify about unconfirmed messages?
# ACKS
def queue_ack(self, callback, message):
"""Queue acknowledgment callback"""
ack_id = self.ack_id
self.ack_queue[ack_id] = (time.time(),
callback,
message)
self.ack_id += 1
return ack_id
def deque_ack(self, msg_id, ack_data):
"""Dequeue acknowledgment callback"""
if msg_id in self.ack_queue:
time_stamp, callback, message = self.ack_queue.pop(msg_id)
callback(message, ack_data)
else:
logging.error('Received invalid msg_id for ACK: %s' % msg_id)
# Endpoint factory
def get_endpoint(self, endpoint):
"""Get connection class by endpoint name.
By default, will get endpoint from associated list of endpoints
(from __endpoints__ class level variable).
You can override this method to implement different endpoint
connection class creation logic.
"""
if endpoint in self.__endpoints__:
return self.__endpoints__[endpoint]
|