2014-02-07 01:58:26 +00:00
|
|
|
import json
|
|
|
|
import threading
|
2015-04-03 16:13:33 +00:00
|
|
|
import logging
|
|
|
|
|
2017-01-18 16:27:00 +00:00
|
|
|
import redis
|
|
|
|
|
2015-04-03 16:13:33 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
2014-02-07 01:58:26 +00:00
|
|
|
|
2016-06-28 19:35:21 +00:00
|
|
|
class CannotReadUserEventsException(Exception):
|
|
|
|
""" Exception raised if user events cannot be read. """
|
|
|
|
|
2014-02-07 01:58:26 +00:00
|
|
|
class UserEventBuilder(object):
|
|
|
|
"""
|
|
|
|
Defines a helper class for constructing UserEvent and UserEventListener
|
|
|
|
instances.
|
|
|
|
"""
|
2014-10-01 18:16:42 +00:00
|
|
|
def __init__(self, redis_config):
|
|
|
|
self._redis_config = redis_config
|
2014-02-07 01:58:26 +00:00
|
|
|
|
|
|
|
def get_event(self, username):
|
2014-10-01 18:16:42 +00:00
|
|
|
return UserEvent(self._redis_config, username)
|
2014-02-07 01:58:26 +00:00
|
|
|
|
|
|
|
def get_listener(self, username, events):
|
2014-10-01 18:16:42 +00:00
|
|
|
return UserEventListener(self._redis_config, username, events)
|
2014-02-07 01:58:26 +00:00
|
|
|
|
|
|
|
|
2014-05-30 18:25:29 +00:00
|
|
|
class UserEventsBuilderModule(object):
|
|
|
|
def __init__(self, app=None):
|
|
|
|
self.app = app
|
|
|
|
if app is not None:
|
|
|
|
self.state = self.init_app(app)
|
|
|
|
else:
|
|
|
|
self.state = None
|
|
|
|
|
|
|
|
def init_app(self, app):
|
2014-10-01 18:16:42 +00:00
|
|
|
redis_config = app.config.get('USER_EVENTS_REDIS')
|
|
|
|
if not redis_config:
|
|
|
|
# This is the old key name.
|
|
|
|
redis_config = {
|
2014-10-14 18:37:02 +00:00
|
|
|
'host': app.config.get('USER_EVENTS_REDIS_HOSTNAME'),
|
2014-10-01 18:16:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
user_events = UserEventBuilder(redis_config)
|
2014-05-30 18:25:29 +00:00
|
|
|
|
|
|
|
# register extension with app
|
|
|
|
app.extensions = getattr(app, 'extensions', {})
|
|
|
|
app.extensions['userevents'] = user_events
|
|
|
|
return user_events
|
|
|
|
|
|
|
|
def __getattr__(self, name):
|
|
|
|
return getattr(self.state, name, None)
|
|
|
|
|
|
|
|
|
2014-02-07 01:58:26 +00:00
|
|
|
class UserEvent(object):
|
2014-10-14 18:37:02 +00:00
|
|
|
"""
|
2014-02-07 01:58:26 +00:00
|
|
|
Defines a helper class for publishing to realtime user events
|
|
|
|
as backed by Redis.
|
|
|
|
"""
|
2014-10-01 18:16:42 +00:00
|
|
|
def __init__(self, redis_config, username):
|
2017-01-18 16:27:00 +00:00
|
|
|
self._redis = redis.StrictRedis(socket_connect_timeout=2, **redis_config)
|
2014-02-07 01:58:26 +00:00
|
|
|
self._username = username
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _user_event_key(username, event_id):
|
|
|
|
return 'user/%s/events/%s' % (username, event_id)
|
|
|
|
|
|
|
|
def publish_event_data_sync(self, event_id, data_obj):
|
|
|
|
return self._redis.publish(self._user_event_key(self._username, event_id), json.dumps(data_obj))
|
|
|
|
|
|
|
|
def publish_event_data(self, event_id, data_obj):
|
|
|
|
"""
|
|
|
|
Publishes the serialized form of the data object for the given event. Note that this occurs
|
|
|
|
in a thread to prevent blocking.
|
|
|
|
"""
|
|
|
|
def conduct():
|
|
|
|
try:
|
|
|
|
self.publish_event_data_sync(event_id, data_obj)
|
2015-04-03 16:13:33 +00:00
|
|
|
logger.debug('Published user event %s: %s', event_id, data_obj)
|
2017-01-18 16:27:00 +00:00
|
|
|
except redis.RedisError:
|
2015-04-03 16:13:33 +00:00
|
|
|
logger.exception('Could not publish user event')
|
2014-02-07 01:58:26 +00:00
|
|
|
|
|
|
|
thread = threading.Thread(target=conduct)
|
|
|
|
thread.start()
|
|
|
|
|
2014-10-14 18:37:02 +00:00
|
|
|
|
2014-02-07 01:58:26 +00:00
|
|
|
class UserEventListener(object):
|
|
|
|
"""
|
|
|
|
Defines a helper class for subscribing to realtime user events as
|
|
|
|
backed by Redis.
|
|
|
|
"""
|
2017-01-18 16:27:00 +00:00
|
|
|
def __init__(self, redis_config, username, events=None):
|
|
|
|
events = events or set([])
|
2014-02-07 01:58:26 +00:00
|
|
|
channels = [self._user_event_key(username, e) for e in events]
|
|
|
|
|
2016-06-28 19:35:21 +00:00
|
|
|
try:
|
|
|
|
self._redis = redis.StrictRedis(socket_connect_timeout=5, **redis_config)
|
|
|
|
self._pubsub = self._redis.pubsub()
|
|
|
|
self._pubsub.subscribe(channels)
|
|
|
|
except redis.RedisError as re:
|
|
|
|
logger.exception('Could not reach user events redis: %s', re)
|
|
|
|
raise CannotReadUserEventsException
|
2014-02-07 01:58:26 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _user_event_key(username, event_id):
|
|
|
|
return 'user/%s/events/%s' % (username, event_id)
|
2014-10-14 18:37:02 +00:00
|
|
|
|
2014-02-07 01:58:26 +00:00
|
|
|
def event_stream(self):
|
|
|
|
"""
|
|
|
|
Starts listening for events on the channel(s), yielding for each event
|
|
|
|
found.
|
|
|
|
"""
|
|
|
|
for item in self._pubsub.listen():
|
|
|
|
channel = item['channel']
|
|
|
|
event_id = channel.split('/')[3] # user/{username}/{events}/{id}
|
|
|
|
data = None
|
|
|
|
|
|
|
|
try:
|
2014-11-24 21:07:38 +00:00
|
|
|
data = json.loads(item['data'] or '{}')
|
2017-01-18 16:27:00 +00:00
|
|
|
except ValueError:
|
|
|
|
continue
|
2014-02-07 01:58:26 +00:00
|
|
|
|
|
|
|
if data:
|
|
|
|
yield event_id, data
|
2014-11-24 21:07:38 +00:00
|
|
|
|
2014-02-07 01:58:26 +00:00
|
|
|
def stop(self):
|
|
|
|
"""
|
|
|
|
Unsubscribes from the channel(s). Should be called once the connection
|
|
|
|
has terminated.
|
|
|
|
"""
|
|
|
|
self._pubsub.unsubscribe()
|