def _connect_subscriptions(self):
     logger.info('connect_subscriptions')
     for _, s in six.iteritems(self.subscriptions):
         s.connect()
 def on_connection_closed(self):
     logger.info('on_connection_closed')
     self._queue.put(a.ConnectionClosed())
 def _drain_offline_queue(self):
     logger.info('_drain_offline_queue')
     while self._offline_queue:
         action = self._offline_queue.popleft()
         self._queue.put(action)
Ejemplo n.º 4
0
def make_client(*args, **kwargs):
    r"""
make_client(\*args, \*\*kwargs)
-------------------------------

Description
    The `make_client()` function is a context manager. Call `make_client()`
    using a `with` statement and the SDK automatically starts the WebSocket
    connection. The SDK stops and then closes the WebSocket connection when the
    statement completes or terminates due to an error.

    This function takes the same parameters as the Client constructor plus
    optional `auth_delegate`.

    To use this function, import it from the client module::

        `from satori.rtm.client import make_client`

Parameters
    * endpoint {string} [required] - RTM endpoint as a string. Example:
      "wss://rtm:8443/foo/bar". If port number is omitted, it defaults to 80 for
      ws:// and 443 for wss://. Available from the Dev Portal.
    * appkey {string} [required] - Appkey used to access RTM.
      Available from the Dev Portal.
    * reconnect_interval {int} [optional] - Time period, in seconds, between
      reconnection attempts. The timeout period between each successive
      connection attempt increases, but starts with this value. Use
      max_reconnect_interval to specify the maximum number of seconds between
      reconnection attempts. Default is 1.
    * max_reconnect_interval {int} [optional] - Maximum period of time, in
      seconds, to wait between reconnection attempts. Default is 300.
    * fail_count_threshold {int} [optional] - Number of times the SDK should
      attempt to reconnect if the connection disconnects. Specify any value
      that resolves to an integer. Default is inf (infinity).
    * observer {client_observer} [optional] - Instance of a client observer
      class, used to define functionality based on the state changes of a
      Client.

      Set this property with client.observer or in the `make_client(*args,
      **kwargs)` or `Client(*args, **kwargs)` methods.
    * restore_auth_on_reconnect {boolean} optional - Whether to restore
      authentication after reconnects. Default is True.
    * max_queue_size {int} optional - this parameter limits the amount of
      concurrent requests in order to avoid 'out of memory' situation.
      For example is max_queue_size is 10 and the client code sends 11
      publish requests so fast that by the time it sends 11th one the reply
      for the first one has not yet arrived, this 11th call to `client.publish`
      will throw the `satori.rtm.client.Full` exception.
    * auth_delegate {AuthDelegate} [optional] - if auth_delegate parameter is
      present, the client yielded by make_client will be already authenticated.

Syntax
    ::

        import satori.rtm.client as sc

        endpoint = 'ENDPOINT'
        appkey = 'APPKEY'

        with sc.make_client(endpoint=endpoint, appkey=appkey) as client:

Client Observer
---------------

Use the client observer callback functions in an observer to implement
functionality based on the Client object state changes.

Set this observer with the `client.observer` property on the Client.

The following table lists the Client object states and the associated
callback functions:

============ ====================== =====================
Client State Enter Callback         Exit Callback
============ ====================== =====================
Awaiting     on_enter_awaiting()    on_leave_awaiting()
Connecting   on_enter_connecting()  on_leave_connecting()
Connected    on_enter_connected()   on_leave_connected()
Stopped      on_enter_stopped()     on_leave_stopped()
Disposed     on_enter_disposed()    n/a
============ ====================== =====================

The following figure shows an example client observer with implemented callback
function::

    class ClientObserver(object):
        def __init__(self):
            self.connection_attempt_count = 0

        def on_enter_connecting(self):
            self.connection_attempt_count += 1
            print('Establishing connection #{0}'.format(
                self.connection_attempt_count))

    client = Client(endpoint='<ENDPOINT>', appkey=None)
    client.observer = ClientObserver()
    client.start()
    client.stop()
    client.start()

Subscription Observer
---------------------

Use callback functions in a subscription observer to implement functionality
based on the state changes for a channel subscription. The subscribe(channel,
SubscriptionMode.RELIABLE, subscription_observer, args) method takes
a subscription observer for the subscription_observer parameter.

.. note:: Depending on your application, these callbacks are optional, except
          `on_subscription_data`. To process received messages, you must
          implement `on_subscription_data(data)` callback.

The following table lists a subscription observer subscription states and
callback functions:

============= ======================== ========================
State         Enter Callback           Exit Callback
============= ======================== ========================
Subscribing   on_enter_subscribing()   on_leave_subscribing()
Subscribed    on_enter_subscribed()    on_leave_subscribed()
Unsubscribing on_enter_unsubscribing() on_leave_unsubscribing()
Unsubscribed  on_enter_unsubscribed()  on_leave_unsubscribed()
Failed        on_enter_failed()        on_leave_failed()
Deleted       on_deleted()             n/a
============= ======================== ========================

Other Callbacks

=================== ======================
Event               Callback
=================== ======================
Created             on_created()
Message(s) Received on_subscription_data()
=================== ======================

The following figure shows an example subscription observer with an implemented
callback function::

    class SubscriptionObserver(object):
        def __init__(self, channel):
                self.message_count = 0
                self.channel = channel

        def on_subscription_data(self, data):
                for message in data['messages']:
                        print('Got message {0}'.format(message))
                self.message_count += len(data['messages'])

        def on_enter_subscribed(self):
                print('Subscription is now active')

        def on_deleted(self):
                print('Received {0} messages from channel ""{1}""'.format(
                        self.message_count, self.channel))

    subscription_observer = SubscriptionObserver()
    client.subscribe(
        channel,
        SubscriptionMode.RELIABLE,
        subscription_observer(channel))

    # wait for some time

    client.unsubscribe(channel)

    """

    observer = kwargs.get('observer')
    auth_delegate = kwargs.get('auth_delegate')
    if 'auth_delegate' in kwargs:
        del kwargs['auth_delegate']

    client = Client(*args, **kwargs)
    ready_event = threading.Event()

    class Observer(ClientStateObserver):
        def on_enter_connected(self):
            ClientStateObserver.on_enter_connected(self)
            ready_event.set()

        def on_enter_stopped(self):
            ClientStateObserver.on_enter_stopped(self)
            ready_event.set()

    client.observer = Observer()
    client.start()
    if not ready_event.wait(70):
        if client.last_connecting_error():
            client.dispose()
            raise RuntimeError(
                "Client connection timeout, last connection error: {0}".format(
                    client.last_connecting_error()))
        else:
            raise RuntimeError("Client connection timeout")
    ready_event.clear()
    if not client.is_connected():
        client.dispose()
        raise RuntimeError("Client connection error: {0}".format(
            client.last_connecting_error()))

    auth_mailbox = []

    def auth_callback(auth_result):
        auth_mailbox.append(auth_result)
        ready_event.set()

    if auth_delegate:
        client.authenticate(auth_delegate, callback=auth_callback)

        if not ready_event.wait(20):
            client.dispose()
            raise AuthError('Authentication process has timed out')

        auth_result = auth_mailbox[0]

        if type(auth_result) == auth.Error:
            raise AuthError(auth_result.message)

        logger.debug('Auth success in make_client')

    try:
        client.observer = observer
        yield client
    finally:
        logger.info('make_client.finally')
        client.dispose()
 def on_fast_forward(self, channel, payload):
     logger.info('on_fast_forward')
     self._queue.put(a.FastForward(channel, payload))
Ejemplo n.º 6
0
 def on_enter_stopping(self):
     logger.info('on_enter_stopping')
Ejemplo n.º 7
0
 def on_leave_stopping(self):
     logger.info('on_leave_stopping')
Ejemplo n.º 8
0
 def on_leave_connected(self):
     logger.info('on_leave_connected')
Ejemplo n.º 9
0
 def on_enter_disposed(self):
     logger.info('on_enter_disposed')
Ejemplo n.º 10
0
 def on_leave_awaiting(self):
     logger.info('on_leave_awaiting')
Ejemplo n.º 11
0
 def on_enter_connected(self):
     logger.info('on_enter_connected')
Ejemplo n.º 12
0
 def on_enter_awaiting(self):
     logger.info('on_enter_awaiting')
Ejemplo n.º 13
0
 def on_leave_connecting(self):
     logger.info('on_leave_connecting')
Ejemplo n.º 14
0
 def on_enter_connecting(self):
     logger.info('on_enter_connecting')
Ejemplo n.º 15
0
 def on_leave_stopped(self):
     logger.info('on_leave_stopped')
Ejemplo n.º 16
0
 def on_enter_stopped(self):
     logger.info('on_enter_stopped')