desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
':param url: Raw socket unicode - either path on local server to unix socket (or unix:/path) or tcp://host:port for internet socket :type url: unicode :param realm: The WAMP realm to join the application session to. :type realm: unicode :param extra: Optional extra configuration to forward to the application component. :type extra: dict :param serializer: WAMP serializer to use (or None for default serializer). :type serializer: `autobahn.wamp.interfaces.ISerializer`'
def __init__(self, url, realm, extra=None, serializer=None):
assert (type(url) == six.text_type) assert (type(realm) == six.text_type) assert ((extra is None) or (type(extra) == dict)) self.url = url self.realm = realm self.extra = (extra or dict()) self.serializer = serializer
'Run the application component. :param make: A factory that produces instances of :class:`autobahn.asyncio.wamp.ApplicationSession` when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`. :type make: callable'
def run(self, make, logging_level='info'):
def create(): cfg = ComponentConfig(self.realm, self.extra) try: session = make(cfg) except Exception: self.log.failure('App session could not be created! ') asyncio.get_event_loop().stop() else: return session parsed_url = urlparse(self.url) if (parsed_url.scheme == 'tcp'): is_unix = False if ((not parsed_url.hostname) or (not parsed_url.port)): raise ValueError('Host and port is required in URL') elif ((parsed_url.scheme == 'unix') or (parsed_url.scheme == '')): is_unix = True if (not parsed_url.path): raise ValueError('Path to unix socket must be in URL') transport_factory = WampRawSocketClientFactory(create, serializer=self.serializer) loop = asyncio.get_event_loop() if (logging_level == 'debug'): loop.set_debug(True) txaio.use_asyncio() txaio.config.loop = loop try: loop.add_signal_handler(signal.SIGTERM, loop.stop) except NotImplementedError: pass def handle_error(loop, context): self.log.error('Application Error: {err}', err=context) loop.stop() loop.set_exception_handler(handle_error) if is_unix: coro = loop.create_unix_connection(transport_factory, parsed_url.path) else: coro = loop.create_connection(transport_factory, parsed_url.hostname, parsed_url.port) (_transport, protocol) = loop.run_until_complete(coro) txaio.start_logging(level=logging_level) try: loop.run_forever() except KeyboardInterrupt: pass self.log.debug('Left main loop waiting for completion') if protocol._session: loop.run_until_complete(protocol._session.leave()) loop.close()
':param all_done: Deferred that gets callback() when our process exits (.errback if it exits non-zero) :param launched: Deferred that gets callback() when our process starts.'
def __init__(self, all_done, launched, color=None, prefix=''):
self.all_done = all_done self.launched = launched self.color = (color or '') self.prefix = prefix self._out = '' self._err = ''
'ProcessProtocol override'
def connectionMade(self):
if (not self.launched.called): self.launched.callback(self)
'ProcessProtocol override'
def outReceived(self, data):
self._out += data.decode('utf8') while ('\n' in self._out): idx = self._out.find('\n') line = self._out[:idx] self._out = self._out[(idx + 1):] sys.stdout.write(((((self.prefix + self.color) + line) + Fore.RESET) + '\n'))
'ProcessProtocol override'
def errReceived(self, data):
self._err += data.decode('utf8') while ('\n' in self._err): idx = self._err.find('\n') line = self._err[:idx] self._err = self._err[(idx + 1):] sys.stderr.write(((((self.prefix + self.color) + line) + Fore.RESET) + '\n'))
'IProcessProtocol API'
def processEnded(self, reason):
fail = reason.value if ((fail.exitCode != 0) and (fail.exitCode is not None)): msg = 'Process exited with code "{}".'.format(fail.exitCode) err = RuntimeError(msg) self.all_done.errback(err) if (not self.launched.called): self.launched.errback(err) else: self.all_done.callback(fail) if (not self.launched.called): print('FIXME: _launched should have been callbacked by now.') self.launched.callback(self)
'Constructor. :param serializer: The object serializer to use for WAMP wire-level serialization. :type serializer: An object that implements :class:`autobahn.interfaces.IObjectSerializer`.'
def __init__(self, serializer):
self._serializer = serializer
'Implements :func:`autobahn.wamp.interfaces.ISerializer.serialize`'
def serialize(self, msg):
return (msg.serialize(self._serializer), self._serializer.BINARY)
'Implements :func:`autobahn.wamp.interfaces.ISerializer.unserialize`'
def unserialize(self, payload, isBinary=None):
if (isBinary is not None): if (isBinary != self._serializer.BINARY): raise ProtocolError('invalid serialization of WAMP message (binary {0}, but expected {1})'.format(isBinary, self._serializer.BINARY)) try: raw_msgs = self._serializer.unserialize(payload) except Exception as e: raise ProtocolError('invalid serialization of WAMP message ({0})'.format(e)) msgs = [] for raw_msg in raw_msgs: if (type(raw_msg) != list): raise ProtocolError('invalid type {0} for WAMP message'.format(type(raw_msg))) if (len(raw_msg) == 0): raise ProtocolError(u'missing message type in WAMP message') message_type = raw_msg[0] if (type(message_type) not in six.integer_types): raise ProtocolError('invalid type {0} for WAMP message type'.format(type(message_type))) Klass = self.MESSAGE_TYPE_MAP.get(message_type) if (Klass is None): raise ProtocolError('invalid WAMP message type {0}'.format(message_type)) msg = Klass.parse(raw_msg) msgs.append(msg) return msgs
'Ctor. :param batched: Flag that controls whether serializer operates in batched mode. :type batched: bool'
def __init__(self, batched=False):
self._batched = batched
'Implements :func:`autobahn.wamp.interfaces.IObjectSerializer.serialize`'
def serialize(self, obj):
s = _dumps(obj) if isinstance(s, six.text_type): s = s.encode('utf8') if self._batched: return (s + '\x18') else: return s
'Implements :func:`autobahn.wamp.interfaces.IObjectSerializer.unserialize`'
def unserialize(self, payload):
if self._batched: chunks = payload.split('\x18')[:(-1)] else: chunks = [payload] if (len(chunks) == 0): raise Exception('batch format error') return [_loads(data.decode('utf8')) for data in chunks]
'Ctor. :param batched: Flag to control whether to put this serialized into batched mode. :type batched: bool'
def __init__(self, batched=False):
Serializer.__init__(self, JsonObjectSerializer(batched=batched)) if batched: self.SERIALIZER_ID = u'json.batched'
':param error: The URI of the error that occurred, e.g. ``wamp.error.not_authorized``. :type error: str'
def __init__(self, error, *args, **kwargs):
Exception.__init__(self, *args) self.kwargs = kwargs self.error = error self.enc_algo = kwargs.pop('enc_algo', None)
'Get the error message of this exception. :returns: The error message. :rtype: str'
@public def error_message(self):
return u'{0}: {1}'.format(self.error, u' '.join([six.text_type(a) for a in self.args]))
''
def __init__(self, idx, kind, url, endpoint, serializers, max_retries=15, max_retry_delay=300, initial_retry_delay=1.5, retry_delay_growth=1.5, retry_delay_jitter=0.1, options=dict()):
self.idx = idx self.type = kind self.url = url self.endpoint = endpoint self.options = options self.serializers = serializers if ((self.type == 'rawsocket') and (len(serializers) != 1)): raise ValueError("'rawsocket' transport requires exactly one serializer") self.max_retries = max_retries self.max_retry_delay = max_retry_delay self.initial_retry_delay = initial_retry_delay self.retry_delay_growth = retry_delay_growth self.retry_delay_jitter = retry_delay_jitter self._permanent_failure = False self.reset()
'set connection failure rates and retry-delay to initial values'
def reset(self):
self.connect_attempts = 0 self.connect_sucesses = 0 self.connect_failures = 0 self.retry_delay = self.initial_retry_delay
'Mark this transport as failed, meaning we won\'t try to connect to it any longer (that is: can_reconnect() will always return False afer calling this).'
def failed(self):
self._permanent_failure = True
'returns a human-readable description of the endpoint'
def describe_endpoint(self):
if isinstance(self.endpoint, dict): return self.endpoint['type'] return repr(self.endpoint)
'A decorator as a shortcut for subscribing during on-join For example:: @component.subscribe( u"some.topic", options=SubscribeOptions(match=u\'prefix\'), def topic(*args, **kw): print("some.topic({}, {}): event received".format(args, kw))'
def subscribe(self, topic, options=None):
assert ((options is None) or isinstance(options, SubscribeOptions)) def decorator(fn): def do_subscription(session, details): return session.subscribe(fn, topic=topic, options=options) self.on('join', do_subscription) return decorator
'A decorator as a shortcut for registering during on-join For example:: @component.register( u"com.example.add", options=RegisterOptions(invoke=\'round_robin\'), def add(*args, **kw): print("add({}, {}): event received".format(args, kw))'
def register(self, uri, options=None):
assert ((options is None) or isinstance(options, RegisterOptions)) def decorator(fn): def do_registration(session, details): return session.register(fn, procedure=uri, options=options) self.on('join', do_registration) return decorator
':param main: After a transport has been connected and a session has been established and joined to a realm, this (async) procedure will be run until it finishes -- which signals that the component has run to completion. In this case, it usually doesn\'t make sense to use the ``on_*`` kwargs. If you do not pass a main() procedure, the session will not be closed (unless you arrange for .leave() to be called). :type main: callable taking 2 args: reactor, ISession :param transports: Transport configurations for creating transports. Each transport can be a WAMP URL, or a dict containing the following configuration keys: - ``type`` (optional): ``websocket`` (default) or ``rawsocket`` - ``url``: the WAMP URL - ``endpoint`` (optional, derived from URL if not provided): - ``type``: "tcp" or "unix" - ``host``, ``port``: only for TCP - ``path``: only for unix - ``timeout``: in seconds - ``tls``: ``True`` or (under Twisted) an ``twisted.internet.ssl.IOpenSSLClientComponentCreator`` instance (such as returned from ``twisted.internet.ssl.optionsForClientTLS``) or ``CertificateOptions`` instance. :type transports: None or unicode or list of dicts :param config: Session configuration (currently unused?) :type config: None or dict :param realm: the realm to join :type realm: unicode :param authentication: configuration of authenticators :type authentication: dict mapping auth_type to dict'
def __init__(self, main=None, transports=None, config=None, realm=u'default', extra=None, authentication=None):
self.set_valid_events(['start', 'connect', 'join', 'ready', 'leave', 'disconnect']) if ((main is not None) and (not callable(main))): raise RuntimeError('"main" must be a callable if given') self._entry = main if (transports is None): transports = u'ws://127.0.0.1:8080/ws' if isinstance(transports, (six.text_type, str)): url = transports transport = {'type': 'websocket', 'url': url} transports = [transport] elif isinstance(transports, dict): transports = [transports] self._transports = [] for (idx, transport) in enumerate(transports): self._transports.append(_create_transport(idx, transport, self._check_native_endpoint)) self._authentication = (authentication or {}) self._realm = realm self._extra = extra
'A decorator as a shortcut for listening for \'join\' events. For example:: @component.on_join def joined(session, details): print("Session {} joined: {}".format(session, details))'
def on_join(self, fn):
self.on('join', fn)
'A decorator as a shortcut for listening for \'leave\' events.'
def on_leave(self, fn):
self.on('leave', fn)
'A decorator as a shortcut for listening for \'connect\' events.'
def on_connect(self, fn):
self.on('connect', fn)
'A decorator as a shortcut for listening for \'disconnect\' events.'
def on_disconnect(self, fn):
self.on('disconnect', fn)
'A decorator as a shortcut for listening for \'ready\' events.'
def on_ready(self, fn):
self.on('ready', fn)
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onOpen`'
def onOpen(self):
try: self._session = self.factory._factory() self._session.onOpen(self) except Exception as e: self.log.critical('{tb}', tb=traceback.format_exc()) reason = u'WAMP Internal Error ({0})'.format(e) self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_INTERNAL_ERROR, reason=reason)
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onClose`'
def onClose(self, wasClean, code, reason):
if (self._session is not None): try: self.log.debug('WAMP-over-WebSocket transport lost: wasClean={wasClean}, code={code}, reason="{reason}"', wasClean=wasClean, code=code, reason=reason) self._session.onClose(wasClean) except Exception: self.log.critical('{tb}', tb=traceback.format_exc()) self._session = None
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onMessage`'
def onMessage(self, payload, isBinary):
try: for msg in self._serializer.unserialize(payload, isBinary): self.log.trace('WAMP RECV: message={message}, session={session}, authid={authid}', authid=self._session._authid, session=self._session._session_id, message=msg) self._session.onMessage(msg) except ProtocolError as e: self.log.critical('{tb}', tb=traceback.format_exc()) reason = u'WAMP Protocol Error ({0})'.format(e) self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_PROTOCOL_ERROR, reason=reason) except Exception as e: self.log.critical('{tb}', tb=traceback.format_exc()) reason = u'WAMP Internal Error ({0})'.format(e) self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_INTERNAL_ERROR, reason=reason)
'Implements :func:`autobahn.wamp.interfaces.ITransport.send`'
def send(self, msg):
if self.isOpen(): try: self.log.trace('WAMP SEND: message={message}, session={session}, authid={authid}', authid=self._session._authid, session=self._session._session_id, message=msg) (payload, isBinary) = self._serializer.serialize(msg) except Exception as e: self.log.error('WAMP message serialization error: {}'.format(e)) raise SerializationError(u'WAMP message serialization error: {0}'.format(e)) else: self.sendMessage(payload, isBinary) else: raise TransportLost()
'Implements :func:`autobahn.wamp.interfaces.ITransport.isOpen`'
def isOpen(self):
return (self._session is not None)
'Implements :func:`autobahn.wamp.interfaces.ITransport.close`'
def close(self):
if self.isOpen(): self.sendClose(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_NORMAL) else: raise TransportLost()
'Implements :func:`autobahn.wamp.interfaces.ITransport.abort`'
def abort(self):
if self.isOpen(): self._bailout(protocol.WebSocketProtocol.CLOSE_STATUS_CODE_GOING_AWAY) else: raise TransportLost()
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onConnect`'
def onConnect(self, request):
headers = {} for subprotocol in request.protocols: (version, serializerId) = parseSubprotocolIdentifier(subprotocol) if ((version == 2) and (serializerId in self.factory._serializers.keys())): self._serializer = self.factory._serializers[serializerId] return (subprotocol, headers) if self.STRICT_PROTOCOL_NEGOTIATION: raise ConnectionDeny(ConnectionDeny.BAD_REQUEST, u'This server only speaks WebSocket subprotocols {}'.format(u', '.join(self.factory.protocols))) else: self._serializer = self.factory._serializers[u'json'] return (None, headers)
'Callback from :func:`autobahn.websocket.interfaces.IWebSocketChannel.onConnect`'
def onConnect(self, response):
if (response.protocol not in self.factory.protocols): if self.STRICT_PROTOCOL_NEGOTIATION: raise Exception(u'The server does not speak any of the WebSocket subprotocols {} we requested.'.format(u', '.join(self.factory.protocols))) else: serializerId = u'json' else: (version, serializerId) = parseSubprotocolIdentifier(response.protocol) self._serializer = self.factory._serializers[serializerId]
'Ctor. :param factory: A callable that produces instances that implement :class:`autobahn.wamp.interfaces.ITransportHandler` :type factory: callable :param serializers: A list of WAMP serializers to use (or None for default serializers). Serializers must implement :class:`autobahn.wamp.interfaces.ISerializer`. :type serializers: list'
def __init__(self, factory, serializers=None):
if callable(factory): self._factory = factory else: self._factory = (lambda : factory) if (serializers is None): serializers = [] try: from autobahn.wamp.serializer import CBORSerializer serializers.append(CBORSerializer(batched=True)) serializers.append(CBORSerializer()) except ImportError: pass try: from autobahn.wamp.serializer import MsgPackSerializer serializers.append(MsgPackSerializer(batched=True)) serializers.append(MsgPackSerializer()) except ImportError: pass try: from autobahn.wamp.serializer import UBJSONSerializer serializers.append(UBJSONSerializer(batched=True)) serializers.append(UBJSONSerializer()) except ImportError: pass try: from autobahn.wamp.serializer import JsonSerializer serializers.append(JsonSerializer(batched=True)) serializers.append(JsonSerializer()) except ImportError: pass if (not serializers): raise Exception(u'Could not import any WAMP serializer') self._serializers = {} for ser in serializers: self._serializers[ser.SERIALIZER_ID] = ser self._protocols = [u'wamp.2.{}'.format(ser.SERIALIZER_ID) for ser in serializers]
''
def __init__(self):
self.set_valid_events(valid_events=['join', 'leave', 'ready', 'connect', 'disconnect']) self.traceback_app = False self._ecls_to_uri_pat = {} self._uri_to_ecls = {ApplicationError.INVALID_PAYLOAD: SerializationError} self._authid = None self._authrole = None self._authmethod = None self._authprovider = None self._payload_codec = None self._request_id_gen = IdGenerator()
'Implements :func:`autobahn.wamp.interfaces.ISession.define`'
def define(self, exception, error=None):
if (error is None): assert hasattr(exception, '_wampuris') self._ecls_to_uri_pat[exception] = exception._wampuris self._uri_to_ecls[exception._wampuris[0].uri()] = exception else: assert (not hasattr(exception, '_wampuris')) self._ecls_to_uri_pat[exception] = [uri.Pattern(six.u(error), uri.Pattern.URI_TARGET_HANDLER)] self._uri_to_ecls[six.u(error)] = exception
'Create a WAMP error message from an exception. :param request_type: The request type this WAMP error message is for. :type request_type: int :param request: The request ID this WAMP error message is for. :type request: int :param exc: The exception. :type exc: Instance of :class:`Exception` or subclass thereof. :param tb: Optional traceback. If present, it\'ll be included with the WAMP error message. :type tb: list or None'
def _message_from_exception(self, request_type, request, exc, tb=None, enc_algo=None):
args = None if hasattr(exc, 'args'): args = list(exc.args) kwargs = None if hasattr(exc, 'kwargs'): kwargs = exc.kwargs if tb: if kwargs: kwargs['traceback'] = tb else: kwargs = {'traceback': tb} if isinstance(exc, exception.ApplicationError): error = (exc.error if (type(exc.error) == six.text_type) else six.u(exc.error)) elif (exc.__class__ in self._ecls_to_uri_pat): error = self._ecls_to_uri_pat[exc.__class__][0]._uri else: error = u'wamp.error.runtime_error' encoded_payload = None if self._payload_codec: encoded_payload = self._payload_codec.encode(False, error, args, kwargs) if encoded_payload: msg = message.Error(request_type, request, error, payload=encoded_payload.payload, enc_algo=encoded_payload.enc_algo, enc_key=encoded_payload.enc_key, enc_serializer=encoded_payload.enc_serializer) else: msg = message.Error(request_type, request, error, args, kwargs) return msg
'Create a user (or generic) exception from a WAMP error message. :param msg: A WAMP error message. :type msg: instance of :class:`autobahn.wamp.message.Error`'
def _exception_from_message(self, msg):
exc = None enc_err = None if msg.enc_algo: if (not self._payload_codec): log_msg = u'received encoded payload, but no payload codec active' self.log.warn(log_msg) enc_err = ApplicationError(ApplicationError.ENC_NO_PAYLOAD_CODEC, log_msg, enc_algo=msg.enc_algo) else: try: encoded_payload = EncodedPayload(msg.payload, msg.enc_algo, msg.enc_serializer, msg.enc_key) (decrypted_error, msg.args, msg.kwargs) = self._payload_codec.decode(True, msg.error, encoded_payload) except Exception as e: self.log.warn('failed to decrypt application payload 1: {err}', err=e) enc_err = ApplicationError(ApplicationError.ENC_DECRYPT_ERROR, u'failed to decrypt application payload 1: {}'.format(e), enc_algo=msg.enc_algo) else: if (msg.error != decrypted_error): self.log.warn(u"URI within encrypted payload ('{decrypted_error}') does not match the envelope ('{error}')", decrypted_error=decrypted_error, error=msg.error) enc_err = ApplicationError(ApplicationError.ENC_TRUSTED_URI_MISMATCH, u"URI within encrypted payload ('{}') does not match the envelope ('{}')".format(decrypted_error, msg.error), enc_algo=msg.enc_algo) if enc_err: return enc_err if (msg.error in self._uri_to_ecls): ecls = self._uri_to_ecls[msg.error] try: if msg.kwargs: if msg.args: exc = ecls(*msg.args, **msg.kwargs) else: exc = ecls(**msg.kwargs) elif msg.args: exc = ecls(*msg.args) else: exc = ecls() except Exception: try: self.onUserError(txaio.create_failure(), 'While re-constructing exception') except: pass if (not exc): if msg.kwargs: if msg.args: exc = exception.ApplicationError(msg.error, *msg.args, **msg.kwargs) else: exc = exception.ApplicationError(msg.error, **msg.kwargs) elif msg.args: exc = exception.ApplicationError(msg.error, *msg.args) else: exc = exception.ApplicationError(msg.error) if hasattr(exc, 'enc_algo'): exc.enc_algo = msg.enc_algo return exc
'Implements :func:`autobahn.wamp.interfaces.ISession`'
def __init__(self, config=None):
BaseSession.__init__(self) self.config = (config or types.ComponentConfig(realm=u'default')) self._transport = None self._session_id = None self._realm = None self._goodbye_sent = False self._transport_is_closing = False self._publish_reqs = {} self._subscribe_reqs = {} self._unsubscribe_reqs = {} self._call_reqs = {} self._register_reqs = {} self._unregister_reqs = {} self._subscriptions = {} self._registrations = {} self._invocations = {}
'Implements :func:`autobahn.wamp.interfaces.ISession.set_payload_codec`'
@public def set_payload_codec(self, payload_codec):
assert ((payload_codec is None) or isinstance(payload_codec, IPayloadCodec)) self._payload_codec = payload_codec
'Implements :func:`autobahn.wamp.interfaces.ISession.get_payload_codec`'
@public def get_payload_codec(self):
return self._payload_codec
'Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onOpen`'
@public def onOpen(self, transport):
self._transport = transport d = self.fire('connect', self, transport) txaio.add_callbacks(d, None, (lambda fail: self._swallow_error(fail, "While notifying 'connect'"))) txaio.add_callbacks(d, (lambda _: txaio.as_future(self.onConnect)), None)
'Implements :func:`autobahn.wamp.interfaces.ISession.onConnect`'
@public def onConnect(self):
self.join(self.config.realm)
'Implements :func:`autobahn.wamp.interfaces.ISession.join`'
@public def join(self, realm, authmethods=None, authid=None, authrole=None, authextra=None, resumable=None, resume_session=None, resume_token=None):
assert ((realm is None) or (type(realm) == six.text_type)) assert ((authmethods is None) or (type(authmethods) == list)) if (type(authmethods) == list): for authmethod in authmethods: assert (type(authmethod) == six.text_type) assert ((authid is None) or (type(authid) == six.text_type)) assert ((authrole is None) or (type(authrole) == six.text_type)) assert ((authextra is None) or (type(authextra) == dict)) if self._session_id: raise Exception('already joined') self._realm = realm self._goodbye_sent = False msg = message.Hello(realm=realm, roles=role.DEFAULT_CLIENT_ROLES, authmethods=authmethods, authid=authid, authrole=authrole, authextra=authextra, resumable=resumable, resume_session=resume_session, resume_token=resume_token) self._transport.send(msg)
'Implements :func:`autobahn.wamp.interfaces.ISession.disconnect`'
@public def disconnect(self):
if self._transport: self._transport.close()
'Implements :func:`autobahn.wamp.interfaces.ISession.is_connected`'
@public def is_connected(self):
return (self._transport is not None)
'Implements :func:`autobahn.wamp.interfaces.ISession.is_attached`'
@public def is_attached(self):
return ((self._transport is not None) and (self._session_id is not None))
'Implements :func:`autobahn.wamp.interfaces.ISession.onUserError`'
@public def onUserError(self, fail, msg):
if (False and isinstance(fail.value, exception.ApplicationError)): self.log.error(fail.value.error_message()) else: self.log.error(u'{msg}: {traceback}', msg=msg, traceback=txaio.failure_format_traceback(fail))
'This is an internal generic error-handler for errors encountered when calling down to on*() handlers that can reasonably be expected to be overridden in user code. Note that it *cancels* the error, so use with care! Specifically, this should *never* be added to the errback chain for a Deferred/coroutine that will make it out to user code.'
def _swallow_error(self, fail, msg):
try: self.onUserError(fail, msg) except Exception: self.log.error('Internal error: {tb}', tb=txaio.failure_format_traceback(txaio.create_failure())) return None
'Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onMessage`'
def onMessage(self, msg):
if (self._session_id is None): if isinstance(msg, message.Welcome): if msg.realm: self._realm = msg.realm self._session_id = msg.session self._router_roles = msg.roles details = SessionDetails(realm=self._realm, session=self._session_id, authid=msg.authid, authrole=msg.authrole, authmethod=msg.authmethod, authprovider=msg.authprovider, authextra=msg.authextra, resumed=msg.resumed, resumable=msg.resumable, resume_token=msg.resume_token) d = self.fire('join', self, details) txaio.add_callbacks(d, None, (lambda e: self._swallow_error(e, "While notifying 'join'"))) txaio.add_callbacks(d, (lambda _: txaio.as_future(self.onJoin, details)), None) txaio.add_callbacks(d, None, (lambda e: self._swallow_error(e, 'While firing onJoin'))) txaio.add_callbacks(d, (lambda _: self.fire('ready', self)), None) txaio.add_callbacks(d, None, (lambda e: self._swallow_error(e, "While notifying 'ready'"))) elif isinstance(msg, message.Abort): details = types.CloseDetails(msg.reason, msg.message) d = txaio.as_future(self.onLeave, details) def success(arg): d = self.fire('leave', self, details) def return_arg(_): return arg def _error(e): return self._swallow_error(e, "While firing 'leave' event") txaio.add_callbacks(d, return_arg, _error) return d def _error(e): return self._swallow_error(e, 'While firing onLeave') txaio.add_callbacks(d, success, _error) elif isinstance(msg, message.Challenge): challenge = types.Challenge(msg.method, msg.extra) d = txaio.as_future(self.onChallenge, challenge) def success(signature): if (signature is None): raise Exception('onChallenge user callback did not return a signature') if (type(signature) == six.binary_type): signature = signature.decode('utf8') if (type(signature) != six.text_type): raise Exception('signature must be unicode (was {})'.format(type(signature))) reply = message.Authenticate(signature) self._transport.send(reply) def error(err): self.onUserError(err, 'Authentication failed') reply = message.Abort(u'wamp.error.cannot_authenticate', u'{0}'.format(err.value)) self._transport.send(reply) details = types.CloseDetails(reply.reason, reply.message) d = txaio.as_future(self.onLeave, details) def success(arg): self.fire('leave', self, details) return arg def _error(e): return self._swallow_error(e, 'While firing onLeave') txaio.add_callbacks(d, success, _error) return d txaio.add_callbacks(d, success, error) else: raise ProtocolError('Received {0} message, and session is not yet established'.format(msg.__class__)) elif isinstance(msg, message.Goodbye): if (not self._goodbye_sent): reply = message.Goodbye() self._transport.send(reply) self._session_id = None details = types.CloseDetails(msg.reason, msg.message) d = txaio.as_future(self.onLeave, details) def success(arg): self.fire('leave', self, details) return arg def _error(e): errmsg = 'While firing onLeave for reason "{0}" and message "{1}"'.format(msg.reason, msg.message) return self._swallow_error(e, errmsg) txaio.add_callbacks(d, success, _error) elif isinstance(msg, message.Event): if (msg.subscription in self._subscriptions): for subscription in self._subscriptions[msg.subscription]: handler = subscription.handler topic = (msg.topic or subscription.topic) if msg.enc_algo: if (not self._payload_codec): self.log.warn('received encoded payload with enc_algo={enc_algo}, but no payload codec active - ignoring encoded payload!', enc_algo=msg.enc_algo) return else: try: encoded_payload = EncodedPayload(msg.payload, msg.enc_algo, msg.enc_serializer, msg.enc_key) (decoded_topic, msg.args, msg.kwargs) = self._payload_codec.decode(False, topic, encoded_payload) except Exception as e: self.log.warn('failed to decode application payload encoded with enc_algo={enc_algo}: {error}', error=e, enc_algo=msg.enc_algo) return else: if (topic != decoded_topic): self.log.warn('envelope topic URI does not match encoded one') return invoke_args = ((handler.obj,) if handler.obj else tuple()) if msg.args: invoke_args = (invoke_args + tuple(msg.args)) invoke_kwargs = (msg.kwargs if msg.kwargs else dict()) if handler.details_arg: invoke_kwargs[handler.details_arg] = types.EventDetails(subscription, msg.publication, publisher=msg.publisher, publisher_authid=msg.publisher_authid, publisher_authrole=msg.publisher_authrole, topic=topic, retained=msg.retained, enc_algo=msg.enc_algo) def _success(_): if (msg.x_acknowledged_delivery and self._router_roles['broker'].x_acknowledged_event_delivery): if self._transport: response = message.EventReceived(msg.publication) self._transport.send(response) else: self.log.warn('successfully processed event with acknowledged delivery, but could not send ACK, since the transport was lost in the meantime') def _error(e): errmsg = 'While firing {0} subscribed under {1}.'.format(handler.fn, msg.subscription) return self._swallow_error(e, errmsg) future = txaio.as_future(handler.fn, *invoke_args, **invoke_kwargs) txaio.add_callbacks(future, _success, _error) else: raise ProtocolError('EVENT received for non-subscribed subscription ID {0}'.format(msg.subscription)) elif isinstance(msg, message.Published): if (msg.request in self._publish_reqs): publish_request = self._publish_reqs.pop(msg.request) publication = Publication(msg.publication, was_encrypted=publish_request.was_encrypted) txaio.resolve(publish_request.on_reply, publication) else: raise ProtocolError('PUBLISHED received for non-pending request ID {0}'.format(msg.request)) elif isinstance(msg, message.Subscribed): if (msg.request in self._subscribe_reqs): request = self._subscribe_reqs.pop(msg.request) if (msg.subscription not in self._subscriptions): self._subscriptions[msg.subscription] = [] subscription = Subscription(msg.subscription, request.topic, self, request.handler) self._subscriptions[msg.subscription].append(subscription) txaio.resolve(request.on_reply, subscription) else: raise ProtocolError('SUBSCRIBED received for non-pending request ID {0}'.format(msg.request)) elif isinstance(msg, message.Unsubscribed): if (msg.request in self._unsubscribe_reqs): request = self._unsubscribe_reqs.pop(msg.request) if (request.subscription_id in self._subscriptions): for subscription in self._subscriptions[request.subscription_id]: subscription.active = False del self._subscriptions[request.subscription_id] txaio.resolve(request.on_reply, 0) else: raise ProtocolError('UNSUBSCRIBED received for non-pending request ID {0}'.format(msg.request)) elif isinstance(msg, message.Result): if (msg.request in self._call_reqs): call_request = self._call_reqs[msg.request] proc = call_request.procedure enc_err = None if msg.enc_algo: if (not self._payload_codec): log_msg = u'received encoded payload, but no payload codec active' self.log.warn(log_msg) enc_err = ApplicationError(ApplicationError.ENC_NO_PAYLOAD_CODEC, log_msg) else: try: encoded_payload = EncodedPayload(msg.payload, msg.enc_algo, msg.enc_serializer, msg.enc_key) (decrypted_proc, msg.args, msg.kwargs) = self._payload_codec.decode(True, proc, encoded_payload) except Exception as e: self.log.warn('failed to decrypt application payload 1: {err}', err=e) enc_err = ApplicationError(ApplicationError.ENC_DECRYPT_ERROR, u'failed to decrypt application payload 1: {}'.format(e)) else: if (proc != decrypted_proc): self.log.warn("URI within encrypted payload ('{decrypted_proc}') does not match the envelope ('{proc}')", decrypted_proc=decrypted_proc, proc=proc) enc_err = ApplicationError(ApplicationError.ENC_TRUSTED_URI_MISMATCH, u"URI within encrypted payload ('{}') does not match the envelope ('{}')".format(decrypted_proc, proc)) if msg.progress: if call_request.options.on_progress: if enc_err: self.onUserError(enc_err, 'could not deliver progressive call result, because payload decryption failed') else: kw = (msg.kwargs or dict()) args = (msg.args or tuple()) try: call_request.options.on_progress(*args, **kw) except Exception: try: self.onUserError(txaio.create_failure(), 'While firing on_progress') except: pass else: del self._call_reqs[msg.request] on_reply = call_request.on_reply if enc_err: txaio.reject(on_reply, enc_err) elif msg.kwargs: if msg.args: res = types.CallResult(*msg.args, **msg.kwargs) else: res = types.CallResult(**msg.kwargs) txaio.resolve(on_reply, res) elif msg.args: if (len(msg.args) > 1): res = types.CallResult(*msg.args) txaio.resolve(on_reply, res) else: txaio.resolve(on_reply, msg.args[0]) else: txaio.resolve(on_reply, None) else: raise ProtocolError('RESULT received for non-pending request ID {0}'.format(msg.request)) elif isinstance(msg, message.Invocation): if (msg.request in self._invocations): raise ProtocolError('INVOCATION received for request ID {0} already invoked'.format(msg.request)) elif (msg.registration not in self._registrations): raise ProtocolError('INVOCATION received for non-registered registration ID {0}'.format(msg.registration)) else: registration = self._registrations[msg.registration] endpoint = registration.endpoint proc = (msg.procedure or registration.procedure) enc_err = None if msg.enc_algo: if (not self._payload_codec): log_msg = u'received encrypted INVOCATION payload, but no keyring active' self.log.warn(log_msg) enc_err = ApplicationError(ApplicationError.ENC_NO_PAYLOAD_CODEC, log_msg) else: try: encoded_payload = EncodedPayload(msg.payload, msg.enc_algo, msg.enc_serializer, msg.enc_key) (decrypted_proc, msg.args, msg.kwargs) = self._payload_codec.decode(False, proc, encoded_payload) except Exception as e: self.log.warn('failed to decrypt INVOCATION payload: {err}', err=e) enc_err = ApplicationError(ApplicationError.ENC_DECRYPT_ERROR, 'failed to decrypt INVOCATION payload: {}'.format(e)) else: if (proc != decrypted_proc): self.log.warn("URI within encrypted INVOCATION payload ('{decrypted_proc}') does not match the envelope ('{proc}')", decrypted_proc=decrypted_proc, proc=proc) enc_err = ApplicationError(ApplicationError.ENC_TRUSTED_URI_MISMATCH, u"URI within encrypted INVOCATION payload ('{}') does not match the envelope ('{}')".format(decrypted_proc, proc)) if enc_err: reply = self._message_from_exception(message.Invocation.MESSAGE_TYPE, msg.request, enc_err) self._transport.send(reply) else: if (endpoint.obj is not None): invoke_args = (endpoint.obj,) else: invoke_args = tuple() if msg.args: invoke_args = (invoke_args + tuple(msg.args)) invoke_kwargs = (msg.kwargs if msg.kwargs else dict()) if endpoint.details_arg: if msg.receive_progress: def progress(*args, **kwargs): encoded_payload = None if msg.enc_algo: if (not self._payload_codec): raise Exception(u'trying to send encrypted payload, but no keyring active') encoded_payload = self._payload_codec.encode(False, proc, args, kwargs) if encoded_payload: progress_msg = message.Yield(msg.request, payload=encoded_payload.payload, progress=True, enc_algo=encoded_payload.enc_algo, enc_key=encoded_payload.enc_key, enc_serializer=encoded_payload.enc_serializer) else: progress_msg = message.Yield(msg.request, args=args, kwargs=kwargs, progress=True) self._transport.send(progress_msg) else: progress = None invoke_kwargs[endpoint.details_arg] = types.CallDetails(registration, progress=progress, caller=msg.caller, caller_authid=msg.caller_authid, caller_authrole=msg.caller_authrole, procedure=proc, enc_algo=msg.enc_algo) on_reply = txaio.as_future(endpoint.fn, *invoke_args, **invoke_kwargs) def success(res): del self._invocations[msg.request] encoded_payload = None if msg.enc_algo: if (not self._payload_codec): log_msg = u'trying to send encrypted payload, but no keyring active' self.log.warn(log_msg) else: try: if isinstance(res, types.CallResult): encoded_payload = self._payload_codec.encode(False, proc, res.results, res.kwresults) else: encoded_payload = self._payload_codec.encode(False, proc, [res]) except Exception as e: self.log.warn('failed to encrypt application payload: {err}', err=e) if encoded_payload: reply = message.Yield(msg.request, payload=encoded_payload.payload, enc_algo=encoded_payload.enc_algo, enc_key=encoded_payload.enc_key, enc_serializer=encoded_payload.enc_serializer) elif isinstance(res, types.CallResult): reply = message.Yield(msg.request, args=res.results, kwargs=res.kwresults) else: reply = message.Yield(msg.request, args=[res]) try: self._transport.send(reply) except SerializationError as e: reply = message.Error(message.Invocation.MESSAGE_TYPE, msg.request, ApplicationError.INVALID_PAYLOAD, args=[u'success return value from invoked procedure "{0}" could not be serialized: {1}'.format(registration.procedure, e)]) self._transport.send(reply) def error(err): del self._invocations[msg.request] errmsg = txaio.failure_message(err) try: self.onUserError(err, errmsg) except: pass formatted_tb = None if self.traceback_app: formatted_tb = txaio.failure_format_traceback(err) reply = self._message_from_exception(message.Invocation.MESSAGE_TYPE, msg.request, err.value, formatted_tb, msg.enc_algo) try: self._transport.send(reply) except SerializationError as e: reply = message.Error(message.Invocation.MESSAGE_TYPE, msg.request, ApplicationError.INVALID_PAYLOAD, args=[u'error return value from invoked procedure "{0}" could not be serialized: {1}'.format(registration.procedure, e)]) self._transport.send(reply) return None self._invocations[msg.request] = InvocationRequest(msg.request, on_reply) txaio.add_callbacks(on_reply, success, error) elif isinstance(msg, message.Interrupt): if (msg.request not in self._invocations): raise ProtocolError('INTERRUPT received for non-pending invocation {0}'.format(msg.request)) else: try: self._invocations[msg.request].cancel() except Exception: try: self.onUserError(txaio.create_failure(), 'While cancelling call.') except: pass finally: del self._invocations[msg.request] elif isinstance(msg, message.Registered): if (msg.request in self._register_reqs): request = self._register_reqs.pop(msg.request) if (msg.registration not in self._registrations): registration = Registration(self, msg.registration, request.procedure, request.endpoint) self._registrations[msg.registration] = registration else: raise ProtocolError('REGISTERED received for already existing registration ID {0}'.format(msg.registration)) txaio.resolve(request.on_reply, registration) else: raise ProtocolError('REGISTERED received for non-pending request ID {0}'.format(msg.request)) elif isinstance(msg, message.Unregistered): if (msg.request == 0): try: reg = self._registrations[msg.registration] except KeyError: raise ProtocolError('UNREGISTERED received for non-existant registration ID {0}'.format(msg.registration)) self.log.info(u"Router unregistered procedure '{proc}' with ID {id}", proc=reg.procedure, id=msg.registration) elif (msg.request in self._unregister_reqs): request = self._unregister_reqs.pop(msg.request) if (request.registration_id in self._registrations): self._registrations[request.registration_id].active = False del self._registrations[request.registration_id] txaio.resolve(request.on_reply) else: raise ProtocolError('UNREGISTERED received for non-pending request ID {0}'.format(msg.request)) elif isinstance(msg, message.Error): on_reply = None if ((msg.request_type == message.Call.MESSAGE_TYPE) and (msg.request in self._call_reqs)): on_reply = self._call_reqs.pop(msg.request).on_reply elif ((msg.request_type == message.Publish.MESSAGE_TYPE) and (msg.request in self._publish_reqs)): on_reply = self._publish_reqs.pop(msg.request).on_reply elif ((msg.request_type == message.Subscribe.MESSAGE_TYPE) and (msg.request in self._subscribe_reqs)): on_reply = self._subscribe_reqs.pop(msg.request).on_reply elif ((msg.request_type == message.Unsubscribe.MESSAGE_TYPE) and (msg.request in self._unsubscribe_reqs)): on_reply = self._unsubscribe_reqs.pop(msg.request).on_reply elif ((msg.request_type == message.Register.MESSAGE_TYPE) and (msg.request in self._register_reqs)): on_reply = self._register_reqs.pop(msg.request).on_reply elif ((msg.request_type == message.Unregister.MESSAGE_TYPE) and (msg.request in self._unregister_reqs)): on_reply = self._unregister_reqs.pop(msg.request).on_reply if on_reply: txaio.reject(on_reply, self._exception_from_message(msg)) else: raise ProtocolError('WampAppSession.onMessage(): ERROR received for non-pending request_type {0} and request ID {1}'.format(msg.request_type, msg.request)) else: raise ProtocolError('Unexpected message {0}'.format(msg.__class__))
'Implements :func:`autobahn.wamp.interfaces.ITransportHandler.onClose`'
@public def onClose(self, wasClean):
self._transport = None if self._session_id: details = types.CloseDetails(reason=types.CloseDetails.REASON_TRANSPORT_LOST, message=u'WAMP transport was lost without closing the session before') d = txaio.as_future(self.onLeave, details) def success(arg): self.fire('leave', self, details) return arg def _error(e): return self._swallow_error(e, 'While firing onLeave') txaio.add_callbacks(d, success, _error) self._session_id = None d = txaio.as_future(self.onDisconnect) def success(arg): return self.fire('disconnect', self, was_clean=wasClean) def _error(e): return self._swallow_error(e, 'While firing onDisconnect') txaio.add_callbacks(d, success, _error)
'Implements :func:`autobahn.wamp.interfaces.ISession.onChallenge`'
@public def onChallenge(self, challenge):
raise Exception('received authentication challenge, but onChallenge not implemented')
'Errback any still outstanding requests with exc.'
def _errback_outstanding_requests(self, exc):
d = txaio.create_future_success(None) all_requests = [self._publish_reqs, self._subscribe_reqs, self._unsubscribe_reqs, self._call_reqs, self._register_reqs, self._unregister_reqs] outstanding = [] for requests in all_requests: outstanding.extend(requests.values()) requests.clear() if outstanding: self.log.info('Cancelling {count} outstanding requests', count=len(outstanding)) for request in outstanding: self.log.debug('cleaning up outstanding {request_type} request {request_id}, firing errback on user handler {request_on_reply}', request_on_reply=request.on_reply, request_id=request.request_id, request_type=request.__class__.__name__) txaio.reject(request.on_reply, exc) txaio.add_callbacks(d, (lambda _: request.on_reply), (lambda _: request.on_reply)) return d
'Implements :func:`autobahn.wamp.interfaces.ISession.onLeave`'
@public def onLeave(self, details):
if (details.reason != CloseDetails.REASON_DEFAULT): self.log.warn('session closed with reason {reason} [{message}]', reason=details.reason, message=details.message) exc = ApplicationError(details.reason, details.message) d = self._errback_outstanding_requests(exc) def disconnect(_): if self._transport: self.disconnect() txaio.add_callbacks(d, disconnect, disconnect) return d
'Implements :func:`autobahn.wamp.interfaces.ISession.leave`'
@public def leave(self, reason=None, message=None):
if (not self._session_id): raise SessionNotReady(u"session hasn't joined a realm") if (not self._goodbye_sent): if (not reason): reason = u'wamp.close.normal' msg = wamp.message.Goodbye(reason=reason, message=message) self._transport.send(msg) self._goodbye_sent = True is_closed = ((self._transport is None) or self._transport.is_closed) return is_closed else: raise SessionNotReady(u'session was alread requested to leave')
'Implements :func:`autobahn.wamp.interfaces.ISession.onDisconnect`'
@public def onDisconnect(self):
exc = exception.TransportLost() self._errback_outstanding_requests(exc)
'Implements :func:`autobahn.wamp.interfaces.IPublisher.publish`'
@public def publish(self, topic, *args, **kwargs):
assert (type(topic) == six.text_type) if (not self._transport): raise exception.TransportLost() options = kwargs.pop('options', None) if (options and (not isinstance(options, types.PublishOptions))): raise Exception('options must be of type a.w.t.PublishOptions') request_id = self._request_id_gen.next() encoded_payload = None if self._payload_codec: encoded_payload = self._payload_codec.encode(True, topic, args, kwargs) if encoded_payload: if options: msg = message.Publish(request_id, topic, payload=encoded_payload.payload, enc_algo=encoded_payload.enc_algo, enc_key=encoded_payload.enc_key, enc_serializer=encoded_payload.enc_serializer, **options.message_attr()) else: msg = message.Publish(request_id, topic, payload=encoded_payload.payload, enc_algo=encoded_payload.enc_algo, enc_key=encoded_payload.enc_key, enc_serializer=encoded_payload.enc_serializer) elif options: msg = message.Publish(request_id, topic, args=args, kwargs=kwargs, **options.message_attr()) else: msg = message.Publish(request_id, topic, args=args, kwargs=kwargs) if (options and options.acknowledge): on_reply = txaio.create_future() self._publish_reqs[request_id] = PublishRequest(request_id, on_reply, was_encrypted=(encoded_payload is not None)) else: on_reply = None try: self._transport.send(msg) except Exception as e: if (request_id in self._publish_reqs): del self._publish_reqs[request_id] raise e return on_reply
'Implements :func:`autobahn.wamp.interfaces.ISubscriber.subscribe`'
@public def subscribe(self, handler, topic=None, options=None):
assert ((callable(handler) and (topic is not None)) or hasattr(handler, '__class__')) assert ((topic is None) or (type(topic) == six.text_type)) assert ((options is None) or isinstance(options, types.SubscribeOptions)) if (not self._transport): raise exception.TransportLost() def _subscribe(obj, fn, topic, options): request_id = self._request_id_gen.next() on_reply = txaio.create_future() handler_obj = Handler(fn, obj, (options.details_arg if options else None)) self._subscribe_reqs[request_id] = SubscribeRequest(request_id, topic, on_reply, handler_obj) if options: msg = message.Subscribe(request_id, topic, **options.message_attr()) else: msg = message.Subscribe(request_id, topic) self._transport.send(msg) return on_reply if callable(handler): return _subscribe(None, handler, topic, options) else: on_replies = [] for k in inspect.getmembers(handler.__class__, is_method_or_function): proc = k[1] if ('_wampuris' in proc.__dict__): for pat in proc.__dict__['_wampuris']: if pat.is_handler(): _uri = pat.uri() subopts = (pat.options or options) if (subopts is None): if (pat.uri_type == uri.Pattern.URI_TYPE_WILDCARD): subopts = types.SubscribeOptions(match=u'wildcard') else: subopts = types.SubscribeOptions(match=u'exact') on_replies.append(_subscribe(handler, proc, _uri, subopts)) return txaio.gather(on_replies, consume_exceptions=True)
'Called from :meth:`autobahn.wamp.protocol.Subscription.unsubscribe`'
def _unsubscribe(self, subscription):
assert isinstance(subscription, Subscription) assert subscription.active assert (subscription.id in self._subscriptions) assert (subscription in self._subscriptions[subscription.id]) if (not self._transport): raise exception.TransportLost() self._subscriptions[subscription.id].remove(subscription) subscription.active = False scount = len(self._subscriptions[subscription.id]) if (scount == 0): request_id = self._request_id_gen.next() on_reply = txaio.create_future() self._unsubscribe_reqs[request_id] = UnsubscribeRequest(request_id, on_reply, subscription.id) msg = message.Unsubscribe(request_id, subscription.id) self._transport.send(msg) return on_reply else: return txaio.create_future_success(scount)
'Implements :func:`autobahn.wamp.interfaces.ICaller.call`'
@public def call(self, procedure, *args, **kwargs):
assert (type(procedure) == six.text_type) if (not self._transport): raise exception.TransportLost() options = kwargs.pop('options', None) if (options and (not isinstance(options, types.CallOptions))): raise Exception('options must be of type a.w.t.CallOptions') request_id = self._request_id_gen.next() encoded_payload = None if self._payload_codec: try: encoded_payload = self._payload_codec.encode(True, procedure, args, kwargs) except: self.log.failure() raise if encoded_payload: if options: msg = message.Call(request_id, procedure, payload=encoded_payload.payload, enc_algo=encoded_payload.enc_algo, enc_key=encoded_payload.enc_key, enc_serializer=encoded_payload.enc_serializer, **options.message_attr()) else: msg = message.Call(request_id, procedure, payload=encoded_payload.payload, enc_algo=encoded_payload.enc_algo, enc_key=encoded_payload.enc_key, enc_serializer=encoded_payload.enc_serializer) elif options: msg = message.Call(request_id, procedure, args=args, kwargs=kwargs, **options.message_attr()) else: msg = message.Call(request_id, procedure, args=args, kwargs=kwargs) on_reply = txaio.create_future() self._call_reqs[request_id] = CallRequest(request_id, procedure, on_reply, options) try: self._transport.send(msg) except: if (request_id in self._call_reqs): del self._call_reqs[request_id] raise return on_reply
'Implements :func:`autobahn.wamp.interfaces.ICallee.register`'
@public def register(self, endpoint, procedure=None, options=None):
assert ((callable(endpoint) and (procedure is not None)) or hasattr(endpoint, '__class__')) assert ((procedure is None) or (type(procedure) == six.text_type)) assert ((options is None) or isinstance(options, types.RegisterOptions)) if (not self._transport): raise exception.TransportLost() def _register(obj, fn, procedure, options): request_id = self._request_id_gen.next() on_reply = txaio.create_future() endpoint_obj = Endpoint(fn, obj, (options.details_arg if options else None)) self._register_reqs[request_id] = RegisterRequest(request_id, on_reply, procedure, endpoint_obj) if options: msg = message.Register(request_id, procedure, **options.message_attr()) else: msg = message.Register(request_id, procedure) self._transport.send(msg) return on_reply if callable(endpoint): return _register(None, endpoint, procedure, options) else: on_replies = [] for k in inspect.getmembers(endpoint.__class__, is_method_or_function): proc = k[1] if ('_wampuris' in proc.__dict__): for pat in proc.__dict__['_wampuris']: if pat.is_endpoint(): _uri = pat.uri() regopts = (pat.options or options) on_replies.append(_register(endpoint, proc, _uri, regopts)) return txaio.gather(on_replies, consume_exceptions=True)
'Called from :meth:`autobahn.wamp.protocol.Registration.unregister`'
def _unregister(self, registration):
assert isinstance(registration, Registration) assert registration.active assert (registration.id in self._registrations) if (not self._transport): raise exception.TransportLost() request_id = self._request_id_gen.next() on_reply = txaio.create_future() self._unregister_reqs[request_id] = UnregisterRequest(request_id, on_reply, registration.id) msg = message.Unregister(request_id, registration.id) self._transport.send(msg) return on_reply
':param config: The default component configuration. :type config: instance of :class:`autobahn.wamp.types.ComponentConfig`'
def __init__(self, config=None):
self.config = (config or types.ComponentConfig(realm=u'default'))
'Creates a new WAMP application session. :returns: -- An instance of the WAMP application session class as given by `self.session`.'
def __call__(self):
session = self.session(self.config) session.factory = self return session
'Unicode arguments in ApplicationError will not raise an exception when str()\'d.'
def test_unicode_str(self):
error = ApplicationError(u'some.url', u'\u2603') if PY3: self.assertIn(u'\u2603', str(error)) else: self.assertIn('\\u2603', str(error))
'Unicode arguments in ApplicationError will not raise an exception when the error_message method is called.'
def test_unicode_errormessage(self):
error = ApplicationError(u'some.url', u'\u2603') print error.error_message() self.assertIn(u'\u2603', error.error_message())
'Test deep object equality assert (because I am paranoid).'
def test_deep_equal(self):
v = os.urandom(10) o1 = [1, 2, {u'foo': u'bar', u'bar': v, u'baz': [9, 3, 2], u'goo': {u'moo': [1, 2, 3]}}, v] o2 = [1, 2, {u'goo': {u'moo': [1, 2, 3]}, u'bar': v, u'baz': [9, 3, 2], u'foo': u'bar'}, v] self.assertEqual(o1, o2)
'Test round-tripping over each serializer.'
def test_roundtrip(self):
for ser in self._test_serializers: for (contains_binary, msg) in self._test_messages: if (not must_skip(ser, contains_binary)): (payload, binary) = ser.serialize(msg) msg2 = ser.unserialize(payload, binary) self.assertEqual([msg], msg2)
'Test cross-tripping over 2 serializers (as is done by WAMP routers).'
def test_crosstrip(self):
for ser1 in self._test_serializers: for (contains_binary, msg) in self._test_messages: if (not must_skip(ser1, contains_binary)): (payload, binary) = ser1.serialize(msg) msg1 = ser1.unserialize(payload, binary) msg1 = msg1[0] for ser2 in self._test_serializers: if (not must_skip(ser2, contains_binary)): (payload, binary) = ser2.serialize(msg1) msg2 = ser2.unserialize(payload, binary) self.assertEqual([msg], msg2)
'Test message serialization caching.'
def test_caching(self):
for (contains_binary, msg) in self._test_messages: self.assertEqual(msg._serialized, {}) for ser in self._test_serializers: if (not must_skip(ser, contains_binary)): self.assertFalse((ser._serializer in msg._serialized)) (payload, binary) = ser.serialize(msg) self.assertTrue((ser._serializer in msg._serialized)) self.assertEqual(msg._serialized[ser._serializer], payload) msg.uncache() self.assertFalse((ser._serializer in msg._serialized))
'Retain, when not specified, is False-y by default.'
def test_retain_default_false(self):
wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1'] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.retain, None) self.assertIsNot(msg.retain, True) self.assertEqual(msg.marshal(), wmsg)
'Retain, when specified as False, shows up in the message.'
def test_retain_explicit_false(self):
wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'retain': False, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1'] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.retain, False) self.assertIsNot(msg.retain, True) self.assertEqual(msg.marshal(), wmsg)
'Retain, when specified as True, shows up in the message.'
def test_retain_explicit_true(self):
wmsg = [message.Publish.MESSAGE_TYPE, 123456, {u'exclude_me': False, u'retain': True, u'exclude': [300], u'eligible': [100, 200, 300]}, u'com.myapp.topic1'] msg = message.Publish.parse(wmsg) self.assertIsInstance(msg, message.Publish) self.assertEqual(msg.retain, True) self.assertIs(msg.retain, True) self.assertEqual(msg.marshal(), wmsg)
'Compare this message to another message for equality. :param other: The other message to compare with. :type other: obj :returns: ``True`` iff the messages are equal. :rtype: bool'
def __eq__(self, other):
if (not isinstance(other, self.__class__)): return False for k in self.__slots__: if (k not in ['_serialized']): if (not (getattr(self, k) == getattr(other, k))): return False return True
'Compare this message to another message for inequality. :param other: The other message to compare with. :type other: obj :returns: ``True`` iff the messages are not equal. :rtype: bool'
def __ne__(self, other):
return (not self.__eq__(other))
'Resets the serialization cache.'
def uncache(self):
self._serialized = {}
'Serialize this object into a wire level bytes representation and cache the resulting bytes. If the cache already contains an entry for the given serializer, return the cached representation directly. :param serializer: The wire level serializer to use. :type serializer: An instance that implements :class:`autobahn.interfaces.ISerializer` :returns: The serialized bytes. :rtype: bytes'
def serialize(self, serializer):
if (serializer not in self._serialized): self._serialized[serializer] = serializer.serialize(self.marshal()) return self._serialized[serializer]
':param realm: The URI of the WAMP realm to join. :type realm: str :param roles: The WAMP session roles and features to announce. :type roles: dict of :class:`autobahn.wamp.role.RoleFeatures` :param authmethods: The authentication methods to announce. :type authmethods: list of str or None :param authid: The authentication ID to announce. :type authid: str or None :param authrole: The authentication role to announce. :type authrole: str or None :param authextra: Application-specific "extra data" to be forwarded to the client. :type authextra: dict or None :param resumable: Whether the client wants this to be a session that can be later resumed. :type resumable: bool or None :param resume_session: The session the client would like to resume. :type resume_session: int or None :param resume_token: The secure authorisation token to resume the session. :type resume_token: str or None'
def __init__(self, realm, roles, authmethods=None, authid=None, authrole=None, authextra=None, resumable=None, resume_session=None, resume_token=None):
assert ((realm is None) or isinstance(realm, six.text_type)) assert (type(roles) == dict) assert (len(roles) > 0) for role in roles: assert (role in [u'subscriber', u'publisher', u'caller', u'callee']) assert isinstance(roles[role], autobahn.wamp.role.ROLE_NAME_TO_CLASS[role]) if authmethods: assert (type(authmethods) == list) for authmethod in authmethods: assert (type(authmethod) == six.text_type) assert ((authid is None) or (type(authid) == six.text_type)) assert ((authrole is None) or (type(authrole) == six.text_type)) assert ((authextra is None) or (type(authextra) == dict)) assert ((resumable is None) or (type(resumable) == bool)) assert ((resume_session is None) or (type(resume_session) == int)) assert ((resume_token is None) or (type(resume_token) == six.text_type)) Message.__init__(self) self.realm = realm self.roles = roles self.authmethods = authmethods self.authid = authid self.authrole = authrole self.authextra = authextra self.resumable = resumable self.resume_session = resume_session self.resume_token = resume_token
'Verifies and parses an unserialized raw message into an actual WAMP message instance. :param wmsg: The unserialized raw message. :type wmsg: list :returns: An instance of this class.'
@staticmethod def parse(wmsg):
assert ((len(wmsg) > 0) and (wmsg[0] == Hello.MESSAGE_TYPE)) if (len(wmsg) != 3): raise ProtocolError('invalid message length {0} for HELLO'.format(len(wmsg))) realm = check_or_raise_uri(wmsg[1], u"'realm' in HELLO", allow_none=True) details = check_or_raise_extra(wmsg[2], u"'details' in HELLO") roles = {} if (u'roles' not in details): raise ProtocolError(u'missing mandatory roles attribute in options in HELLO') details_roles = check_or_raise_extra(details[u'roles'], u"'roles' in 'details' in HELLO") if (len(details_roles) == 0): raise ProtocolError(u"empty 'roles' in 'details' in HELLO") for role in details_roles: if (role not in [u'subscriber', u'publisher', u'caller', u'callee']): raise ProtocolError("invalid role '{0}' in 'roles' in 'details' in HELLO".format(role)) role_cls = ROLE_NAME_TO_CLASS[role] details_role = check_or_raise_extra(details_roles[role], "role '{0}' in 'roles' in 'details' in HELLO".format(role)) if (u'features' in details_role): check_or_raise_extra(details_role[u'features'], "'features' in role '{0}' in 'roles' in 'details' in HELLO".format(role)) role_features = role_cls(**details_role[u'features']) else: role_features = role_cls() roles[role] = role_features authmethods = None if (u'authmethods' in details): details_authmethods = details[u'authmethods'] if (type(details_authmethods) != list): raise ProtocolError("invalid type {0} for 'authmethods' detail in HELLO".format(type(details_authmethods))) for auth_method in details_authmethods: if (type(auth_method) != six.text_type): raise ProtocolError("invalid type {0} for item in 'authmethods' detail in HELLO".format(type(auth_method))) authmethods = details_authmethods authid = None if (u'authid' in details): details_authid = details[u'authid'] if (type(details_authid) != six.text_type): raise ProtocolError("invalid type {0} for 'authid' detail in HELLO".format(type(details_authid))) authid = details_authid authrole = None if (u'authrole' in details): details_authrole = details[u'authrole'] if (type(details_authrole) != six.text_type): raise ProtocolError("invalid type {0} for 'authrole' detail in HELLO".format(type(details_authrole))) authrole = details_authrole authextra = None if (u'authextra' in details): details_authextra = details[u'authextra'] if (type(details_authextra) != dict): raise ProtocolError("invalid type {0} for 'authextra' detail in HELLO".format(type(details_authextra))) authextra = details_authextra resumable = None if (u'resumable' in details): resumable = details[u'resumable'] if (type(resumable) != bool): raise ProtocolError("invalid type {0} for 'resumable' detail in HELLO".format(type(resumable))) resume_session = None if (u'resume-session' in details): resume_session = details[u'resume-session'] if (type(resume_session) != int): raise ProtocolError("invalid type {0} for 'resume-session' detail in HELLO".format(type(resume_session))) resume_token = None if (u'resume-token' in details): resume_token = details[u'resume-token'] if (type(resume_token) != six.text_type): raise ProtocolError("invalid type {0} for 'resume-token' detail in HELLO".format(type(resume_token))) elif resume_session: raise ProtocolError('resume-token must be provided if resume-session is provided in HELLO') obj = Hello(realm, roles, authmethods, authid, authrole, authextra, resumable, resume_session, resume_token) return obj
'Marshal this object into a raw message for subsequent serialization to bytes. :returns: The serialized raw message. :rtype: list'
def marshal(self):
details = {u'roles': {}} for role in self.roles.values(): details[u'roles'][role.ROLE] = {} for feature in role.__dict__: if ((not feature.startswith('_')) and (feature != 'ROLE') and (getattr(role, feature) is not None)): if (u'features' not in details[u'roles'][role.ROLE]): details[u'roles'][role.ROLE] = {u'features': {}} details[u'roles'][role.ROLE][u'features'][six.u(feature)] = getattr(role, feature) if (self.authmethods is not None): details[u'authmethods'] = self.authmethods if (self.authid is not None): details[u'authid'] = self.authid if (self.authrole is not None): details[u'authrole'] = self.authrole if (self.authextra is not None): details[u'authextra'] = self.authextra if (self.resumable is not None): details[u'resumable'] = self.resumable if (self.resume_session is not None): details[u'resume-session'] = self.resume_session if (self.resume_token is not None): details[u'resume-token'] = self.resume_token return [Hello.MESSAGE_TYPE, self.realm, details]
'Return a string representation of this message.'
def __str__(self):
return u'Hello(realm={}, roles={}, authmethods={}, authid={}, authrole={}, authextra={}, resumable={}, resume_session={}, resume_token={})'.format(self.realm, self.roles, self.authmethods, self.authid, self.authrole, self.authextra, self.resumable, self.resume_session, self.resume_token)
':param session: The WAMP session ID the other peer is assigned. :type session: int :param roles: The WAMP roles to announce. :type roles: dict of :class:`autobahn.wamp.role.RoleFeatures` :param realm: The effective realm the session is joined on. :type realm: str or None :param authid: The authentication ID assigned. :type authid: str or None :param authrole: The authentication role assigned. :type authrole: str or None :param authmethod: The authentication method in use. :type authmethod: str or None :param authprovider: The authentication provided in use. :type authprovider: str or None :param authextra: Application-specific "extra data" to be forwarded to the client. :type authextra: arbitrary or None :param resumed: Whether the session is a resumed one. :type resumed: bool or None :param resumable: Whether this session can be resumed later. :type resumable: bool or None :param resume_token: The secure authorisation token to resume the session. :type resume_token: str or None :param custom: Implementation-specific "custom attributes" (`x_my_impl_attribute`) to be set. :type custom: dict or None'
def __init__(self, session, roles, realm=None, authid=None, authrole=None, authmethod=None, authprovider=None, authextra=None, resumed=None, resumable=None, resume_token=None, custom=None):
assert (type(session) in six.integer_types) assert (type(roles) == dict) assert (len(roles) > 0) for role in roles: assert (role in [u'broker', u'dealer']) assert isinstance(roles[role], autobahn.wamp.role.ROLE_NAME_TO_CLASS[role]) assert ((realm is None) or (type(realm) == six.text_type)) assert ((authid is None) or (type(authid) == six.text_type)) assert ((authrole is None) or (type(authrole) == six.text_type)) assert ((authmethod is None) or (type(authmethod) == six.text_type)) assert ((authprovider is None) or (type(authprovider) == six.text_type)) assert ((authextra is None) or (type(authextra) == dict)) assert ((resumed is None) or (type(resumed) == bool)) assert ((resumable is None) or (type(resumable) == bool)) assert ((resume_token is None) or (type(resume_token) == six.text_type)) assert ((custom is None) or (type(custom) == dict)) if custom: for k in custom: assert _CUSTOM_ATTRIBUTE.match(k) Message.__init__(self) self.session = session self.roles = roles self.realm = realm self.authid = authid self.authrole = authrole self.authmethod = authmethod self.authprovider = authprovider self.authextra = authextra self.resumed = resumed self.resumable = resumable self.resume_token = resume_token self.custom = (custom or {})
'Verifies and parses an unserialized raw message into an actual WAMP message instance. :param wmsg: The unserialized raw message. :type wmsg: list :returns: An instance of this class.'
@staticmethod def parse(wmsg):
assert ((len(wmsg) > 0) and (wmsg[0] == Welcome.MESSAGE_TYPE)) if (len(wmsg) != 3): raise ProtocolError('invalid message length {0} for WELCOME'.format(len(wmsg))) session = check_or_raise_id(wmsg[1], u"'session' in WELCOME") details = check_or_raise_extra(wmsg[2], u"'details' in WELCOME") realm = details.get(u'realm', None) authid = details.get(u'authid', None) authrole = details.get(u'authrole', None) authmethod = details.get(u'authmethod', None) authprovider = details.get(u'authprovider', None) authextra = details.get(u'authextra', None) resumed = None if (u'resumed' in details): resumed = details[u'resumed'] if (not (type(resumed) == bool)): raise ProtocolError("invalid type {0} for 'resumed' detail in WELCOME".format(type(resumed))) resumable = None if (u'resumable' in details): resumable = details[u'resumable'] if (not (type(resumable) == bool)): raise ProtocolError("invalid type {0} for 'resumable' detail in WELCOME".format(type(resumable))) resume_token = None if (u'resume_token' in details): resume_token = details[u'resume_token'] if (not (type(resume_token) == six.text_type)): raise ProtocolError("invalid type {0} for 'resume_token' detail in WELCOME".format(type(resume_token))) elif resumable: raise ProtocolError('resume_token required when resumable is given in WELCOME') roles = {} if (u'roles' not in details): raise ProtocolError(u'missing mandatory roles attribute in options in WELCOME') details_roles = check_or_raise_extra(details['roles'], u"'roles' in 'details' in WELCOME") if (len(details_roles) == 0): raise ProtocolError(u"empty 'roles' in 'details' in WELCOME") for role in details_roles: if (role not in [u'broker', u'dealer']): raise ProtocolError("invalid role '{0}' in 'roles' in 'details' in WELCOME".format(role)) role_cls = ROLE_NAME_TO_CLASS[role] details_role = check_or_raise_extra(details_roles[role], "role '{0}' in 'roles' in 'details' in WELCOME".format(role)) if (u'features' in details_role): check_or_raise_extra(details_role[u'features'], "'features' in role '{0}' in 'roles' in 'details' in WELCOME".format(role)) role_features = role_cls(**details_roles[role][u'features']) else: role_features = role_cls() roles[role] = role_features custom = {} for k in details: if _CUSTOM_ATTRIBUTE.match(k): custom[k] = details[k] obj = Welcome(session, roles, realm, authid, authrole, authmethod, authprovider, authextra, resumed, resumable, resume_token, custom) return obj
'Marshal this object into a raw message for subsequent serialization to bytes. :returns: The serialized raw message. :rtype: list'
def marshal(self):
details = {} details.update(self.custom) if self.realm: details[u'realm'] = self.realm if self.authid: details[u'authid'] = self.authid if self.authrole: details[u'authrole'] = self.authrole if self.authrole: details[u'authmethod'] = self.authmethod if self.authprovider: details[u'authprovider'] = self.authprovider if self.authextra: details[u'authextra'] = self.authextra if self.resumed: details[u'resumed'] = self.resumed if self.resumable: details[u'resumable'] = self.resumable if self.resume_token: details[u'resume_token'] = self.resume_token details[u'roles'] = {} for role in self.roles.values(): details[u'roles'][role.ROLE] = {} for feature in role.__dict__: if ((not feature.startswith('_')) and (feature != 'ROLE') and (getattr(role, feature) is not None)): if (u'features' not in details[u'roles'][role.ROLE]): details[u'roles'][role.ROLE] = {u'features': {}} details[u'roles'][role.ROLE][u'features'][six.u(feature)] = getattr(role, feature) return [Welcome.MESSAGE_TYPE, self.session, details]
'Returns string representation of this message.'
def __str__(self):
return u'Welcome(session={}, roles={}, realm={}, authid={}, authrole={}, authmethod={}, authprovider={}, authextra={}, resumed={}, resumable={}, resume_token={})'.format(self.session, self.roles, self.realm, self.authid, self.authrole, self.authmethod, self.authprovider, self.authextra, self.resumed, self.resumable, self.resume_token)
':param reason: WAMP or application error URI for aborting reason. :type reason: str :param message: Optional human-readable closing message, e.g. for logging purposes. :type message: str or None'
def __init__(self, reason, message=None):
assert (type(reason) == six.text_type) assert ((message is None) or (type(message) == six.text_type)) Message.__init__(self) self.reason = reason self.message = message
'Verifies and parses an unserialized raw message into an actual WAMP message instance. :param wmsg: The unserialized raw message. :type wmsg: list :returns: An instance of this class.'
@staticmethod def parse(wmsg):
assert ((len(wmsg) > 0) and (wmsg[0] == Abort.MESSAGE_TYPE)) if (len(wmsg) != 3): raise ProtocolError('invalid message length {0} for ABORT'.format(len(wmsg))) details = check_or_raise_extra(wmsg[1], u"'details' in ABORT") reason = check_or_raise_uri(wmsg[2], u"'reason' in ABORT") message = None if (u'message' in details): details_message = details[u'message'] if (type(details_message) != six.text_type): raise ProtocolError("invalid type {0} for 'message' detail in ABORT".format(type(details_message))) message = details_message obj = Abort(reason, message) return obj
'Marshal this object into a raw message for subsequent serialization to bytes. :returns: The serialized raw message. :rtype: list'
def marshal(self):
details = {} if self.message: details[u'message'] = self.message return [Abort.MESSAGE_TYPE, details, self.reason]
'Returns string representation of this message.'
def __str__(self):
return u'Abort(message={0}, reason={1})'.format(self.message, self.reason)
':param method: The authentication method. :type method: str :param extra: Authentication method specific information. :type extra: dict or None'
def __init__(self, method, extra=None):
assert (type(method) == six.text_type) assert ((extra is None) or (type(extra) == dict)) Message.__init__(self) self.method = method self.extra = (extra or {})
'Verifies and parses an unserialized raw message into an actual WAMP message instance. :param wmsg: The unserialized raw message. :type wmsg: list :returns: An instance of this class.'
@staticmethod def parse(wmsg):
assert ((len(wmsg) > 0) and (wmsg[0] == Challenge.MESSAGE_TYPE)) if (len(wmsg) != 3): raise ProtocolError('invalid message length {0} for CHALLENGE'.format(len(wmsg))) method = wmsg[1] if (type(method) != six.text_type): raise ProtocolError("invalid type {0} for 'method' in CHALLENGE".format(type(method))) extra = check_or_raise_extra(wmsg[2], u"'extra' in CHALLENGE") obj = Challenge(method, extra) return obj
'Marshal this object into a raw message for subsequent serialization to bytes. :returns: The serialized raw message. :rtype: list'
def marshal(self):
return [Challenge.MESSAGE_TYPE, self.method, self.extra]
'Returns string representation of this message.'
def __str__(self):
return u'Challenge(method={0}, extra={1})'.format(self.method, self.extra)
':param signature: The signature for the authentication challenge. :type signature: str :param extra: Authentication method specific information. :type extra: dict or None'
def __init__(self, signature, extra=None):
assert (type(signature) == six.text_type) assert ((extra is None) or (type(extra) == dict)) Message.__init__(self) self.signature = signature self.extra = (extra or {})
'Verifies and parses an unserialized raw message into an actual WAMP message instance. :param wmsg: The unserialized raw message. :type wmsg: list :returns: An instance of this class.'
@staticmethod def parse(wmsg):
assert ((len(wmsg) > 0) and (wmsg[0] == Authenticate.MESSAGE_TYPE)) if (len(wmsg) != 3): raise ProtocolError('invalid message length {0} for AUTHENTICATE'.format(len(wmsg))) signature = wmsg[1] if (type(signature) != six.text_type): raise ProtocolError("invalid type {0} for 'signature' in AUTHENTICATE".format(type(signature))) extra = check_or_raise_extra(wmsg[2], u"'extra' in AUTHENTICATE") obj = Authenticate(signature, extra) return obj
'Marshal this object into a raw message for subsequent serialization to bytes. :returns: The serialized raw message. :rtype: list'
def marshal(self):
return [Authenticate.MESSAGE_TYPE, self.signature, self.extra]