3 from __future__ import absolute_import, print_function
10 from .config import actor_class
12 def _notify_subscribers(response, subscribers):
13 """Send the response to all the subscriber methods.
15 If any of the subscriber actors have stopped, remove them from the
18 dead_subscribers = set()
19 for subscriber in subscribers:
22 except pykka.ActorDeadError:
23 dead_subscribers.add(subscriber)
24 subscribers.difference_update(dead_subscribers)
26 class RemotePollLoopActor(actor_class):
27 """Abstract actor class to regularly poll a remote service.
29 This actor sends regular requests to a remote service, and sends each
30 response to subscribers. It takes care of error handling, and retrying
31 requests with exponential backoff.
33 To use this actor, define CLIENT_ERRORS and the _send_request method.
34 If you also define an _item_key method, this class will support
35 subscribing to a specific item by key in responses.
39 def __init__(self, client, timer_actor, poll_wait=60, max_poll_wait=180):
40 super(RemotePollLoopActor, self).__init__()
42 self._timer = timer_actor
43 self._logger = logging.getLogger(self.LOGGER_NAME)
44 self._later = self.actor_ref.proxy()
45 self._polling_started = False
46 self.log_prefix = "{} (at {})".format(self.__class__.__name__, id(self))
47 self.min_poll_wait = poll_wait
48 self.max_poll_wait = max_poll_wait
49 self.poll_wait = self.min_poll_wait
50 self.all_subscribers = set()
51 self.key_subscribers = {}
52 if hasattr(self, '_item_key'):
53 self.subscribe_to = self._subscribe_to
55 def _start_polling(self):
56 if not self._polling_started:
57 self._polling_started = True
60 def subscribe(self, subscriber):
61 self.all_subscribers.add(subscriber)
62 self._logger.debug("%r subscribed to all events", subscriber)
65 # __init__ exposes this method to the proxy if the subclass defines
67 def _subscribe_to(self, key, subscriber):
68 self.key_subscribers.setdefault(key, set()).add(subscriber)
69 self._logger.debug("%r subscribed to events for '%s'", subscriber, key)
72 def _send_request(self):
73 raise NotImplementedError("subclasses must implement request method")
75 def _got_response(self, response):
76 self._logger.debug("%s got response with %d items",
77 self.log_prefix, len(response))
78 self.poll_wait = self.min_poll_wait
79 _notify_subscribers(response, self.all_subscribers)
80 if hasattr(self, '_item_key'):
81 items = {self._item_key(x): x for x in response}
82 for key, subscribers in self.key_subscribers.iteritems():
83 _notify_subscribers(items.get(key), subscribers)
85 def _got_error(self, error):
86 self.poll_wait = min(self.poll_wait * 2, self.max_poll_wait)
87 return "{} got error: {} - waiting {} seconds".format(
88 self.log_prefix, error, self.poll_wait)
90 def poll(self, scheduled_start=None):
91 self._logger.debug("%s sending poll", self.log_prefix)
92 start_time = time.time()
93 if scheduled_start is None:
94 scheduled_start = start_time
96 response = self._send_request()
97 except Exception as error:
98 errmsg = self._got_error(error)
99 if isinstance(error, self.CLIENT_ERRORS):
100 self._logger.warning(errmsg)
102 self._logger.exception(errmsg)
103 next_poll = start_time + self.poll_wait
105 self._got_response(response)
106 next_poll = scheduled_start + self.poll_wait
107 end_time = time.time()
108 if next_poll < end_time: # We've drifted too much; start fresh.
109 next_poll = end_time + self.poll_wait
110 self._timer.schedule(next_poll, self._later.poll, next_poll)