hooks.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. # Copyright 2012-2014 ksyun.com, Inc. or its affiliates. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"). You
  4. # may not use this file except in compliance with the License. A copy of
  5. # the License is located at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # or in the "license" file accompanying this file. This file is
  10. # distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
  11. # ANY KIND, either express or implied. See the License for the specific
  12. # language governing permissions and limitations under the License.
  13. import copy
  14. import logging
  15. from collections import defaultdict, deque, namedtuple
  16. from kscore.compat import accepts_kwargs, six
  17. logger = logging.getLogger(__name__)
  18. _NodeList = namedtuple('NodeList', ['first', 'middle', 'last'])
  19. _FIRST = 0
  20. _MIDDLE = 1
  21. _LAST = 2
  22. class NodeList(_NodeList):
  23. def __copy__(self):
  24. first_copy = copy.copy(self.first)
  25. middle_copy = copy.copy(self.middle)
  26. last_copy = copy.copy(self.last)
  27. copied = NodeList(first_copy, middle_copy, last_copy)
  28. return copied
  29. def first_non_none_response(responses, default=None):
  30. """Find first non None response in a list of tuples.
  31. This function can be used to find the first non None response from
  32. handlers connected to an event. This is useful if you are interested
  33. in the returned responses from event handlers. Example usage::
  34. print(first_non_none_response([(func1, None), (func2, 'foo'),
  35. (func3, 'bar')]))
  36. # This will print 'foo'
  37. :type responses: list of tuples
  38. :param responses: The responses from the ``EventHooks.emit`` method.
  39. This is a list of tuples, and each tuple is
  40. (handler, handler_response).
  41. :param default: If no non-None responses are found, then this default
  42. value will be returned.
  43. :return: The first non-None response in the list of tuples.
  44. """
  45. for response in responses:
  46. if response[1] is not None:
  47. return response[1]
  48. return default
  49. class BaseEventHooks(object):
  50. def emit(self, event_name, **kwargs):
  51. """Call all handlers subscribed to an event.
  52. :type event_name: str
  53. :param event_name: The name of the event to emit.
  54. :type **kwargs: dict
  55. :param **kwargs: Arbitrary kwargs to pass through to the
  56. subscribed handlers. The ``event_name`` will be injected
  57. into the kwargs so it's not necesary to add this to **kwargs.
  58. :rtype: list of tuples
  59. :return: A list of ``(handler_func, handler_func_return_value)``
  60. """
  61. return []
  62. def register(self, event_name, handler, unique_id=None,
  63. unique_id_uses_count=False):
  64. """Register an event handler for a given event.
  65. If a ``unique_id`` is given, the handler will not be registered
  66. if a handler with the ``unique_id`` has already been registered.
  67. Handlers are called in the order they have been registered.
  68. Note handlers can also be registered with ``register_first()``
  69. and ``register_last()``. All handlers registered with
  70. ``register_first()`` are called before handlers registered
  71. with ``register()`` which are called before handlers registered
  72. with ``register_last()``.
  73. """
  74. self._verify_and_register(event_name, handler, unique_id,
  75. register_method=self._register,
  76. unique_id_uses_count=unique_id_uses_count)
  77. def register_first(self, event_name, handler, unique_id=None,
  78. unique_id_uses_count=False):
  79. """Register an event handler to be called first for an event.
  80. All event handlers registered with ``register_first()`` will
  81. be called before handlers registered with ``register()`` and
  82. ``register_last()``.
  83. """
  84. self._verify_and_register(event_name, handler, unique_id,
  85. register_method=self._register_first,
  86. unique_id_uses_count=unique_id_uses_count)
  87. def register_last(self, event_name, handler, unique_id=None,
  88. unique_id_uses_count=False):
  89. """Register an event handler to be called last for an event.
  90. All event handlers registered with ``register_last()`` will be called
  91. after handlers registered with ``register_first()`` and ``register()``.
  92. """
  93. self._verify_and_register(event_name, handler, unique_id,
  94. register_method=self._register_last,
  95. unique_id_uses_count=unique_id_uses_count)
  96. def _verify_and_register(self, event_name, handler, unique_id,
  97. register_method, unique_id_uses_count):
  98. self._verify_is_callable(handler)
  99. self._verify_accept_kwargs(handler)
  100. register_method(event_name, handler, unique_id, unique_id_uses_count)
  101. def unregister(self, event_name, handler=None, unique_id=None,
  102. unique_id_uses_count=False):
  103. """Unregister an event handler for a given event.
  104. If no ``unique_id`` was given during registration, then the
  105. first instance of the event handler is removed (if the event
  106. handler has been registered multiple times).
  107. """
  108. pass
  109. def _verify_is_callable(self, func):
  110. if not six.callable(func):
  111. raise ValueError("Event handler %s must be callable." % func)
  112. def _verify_accept_kwargs(self, func):
  113. """Verifies a callable accepts kwargs
  114. :type func: callable
  115. :param func: A callable object.
  116. :returns: True, if ``func`` accepts kwargs, otherwise False.
  117. """
  118. try:
  119. if not accepts_kwargs(func):
  120. raise ValueError("Event handler %s must accept keyword "
  121. "arguments (**kwargs)" % func)
  122. except TypeError:
  123. return False
  124. class HierarchicalEmitter(BaseEventHooks):
  125. def __init__(self):
  126. # We keep a reference to the handlers for quick
  127. # read only access (we never modify self._handlers).
  128. # A cache of event name to handler list.
  129. self._lookup_cache = {}
  130. self._handlers = _PrefixTrie()
  131. # This is used to ensure that unique_id's are only
  132. # registered once.
  133. self._unique_id_handlers = {}
  134. def _emit(self, event_name, kwargs, stop_on_response=False):
  135. """
  136. Emit an event with optional keyword arguments.
  137. :type event_name: string
  138. :param event_name: Name of the event
  139. :type kwargs: dict
  140. :param kwargs: Arguments to be passed to the handler functions.
  141. :type stop_on_response: boolean
  142. :param stop_on_response: Whether to stop on the first non-None
  143. response. If False, then all handlers
  144. will be called. This is especially useful
  145. to handlers which mutate data and then
  146. want to stop propagation of the event.
  147. :rtype: list
  148. :return: List of (handler, response) tuples from all processed
  149. handlers.
  150. """
  151. responses = []
  152. # Invoke the event handlers from most specific
  153. # to least specific, each time stripping off a dot.
  154. handlers_to_call = self._lookup_cache.get(event_name)
  155. if handlers_to_call is None:
  156. handlers_to_call = self._handlers.prefix_search(event_name)
  157. self._lookup_cache[event_name] = handlers_to_call
  158. elif not handlers_to_call:
  159. # Short circuit and return an empty response is we have
  160. # no handlers to call. This is the common case where
  161. # for the majority of signals, nothing is listening.
  162. return []
  163. kwargs['event_name'] = event_name
  164. responses = []
  165. for handler in handlers_to_call:
  166. logger.debug('Event %s: calling handler %s', event_name, handler)
  167. response = handler(**kwargs)
  168. responses.append((handler, response))
  169. if stop_on_response and response is not None:
  170. return responses
  171. return responses
  172. def emit(self, event_name, **kwargs):
  173. """
  174. Emit an event by name with arguments passed as keyword args.
  175. >>> responses = emitter.emit(
  176. ... 'my-event.service.operation', arg1='one', arg2='two')
  177. :rtype: list
  178. :return: List of (handler, response) tuples from all processed
  179. handlers.
  180. """
  181. return self._emit(event_name, kwargs)
  182. def emit_until_response(self, event_name, **kwargs):
  183. """
  184. Emit an event by name with arguments passed as keyword args,
  185. until the first non-``None`` response is received. This
  186. method prevents subsequent handlers from being invoked.
  187. >>> handler, response = emitter.emit_until_response(
  188. 'my-event.service.operation', arg1='one', arg2='two')
  189. :rtype: tuple
  190. :return: The first (handler, response) tuple where the response
  191. is not ``None``, otherwise (``None``, ``None``).
  192. """
  193. responses = self._emit(event_name, kwargs, stop_on_response=True)
  194. if responses:
  195. return responses[-1]
  196. else:
  197. return (None, None)
  198. def _register(self, event_name, handler, unique_id=None,
  199. unique_id_uses_count=False):
  200. self._register_section(event_name, handler, unique_id,
  201. unique_id_uses_count, section=_MIDDLE)
  202. def _register_first(self, event_name, handler, unique_id=None,
  203. unique_id_uses_count=False):
  204. self._register_section(event_name, handler, unique_id,
  205. unique_id_uses_count, section=_FIRST)
  206. def _register_last(self, event_name, handler, unique_id,
  207. unique_id_uses_count=False):
  208. self._register_section(event_name, handler, unique_id,
  209. unique_id_uses_count, section=_LAST)
  210. def _register_section(self, event_name, handler, unique_id,
  211. unique_id_uses_count, section):
  212. if unique_id is not None:
  213. if unique_id in self._unique_id_handlers:
  214. # We've already registered a handler using this unique_id
  215. # so we don't need to register it again.
  216. count = self._unique_id_handlers[unique_id].get('count', None)
  217. if unique_id_uses_count:
  218. if not count:
  219. raise ValueError("Initial registration of"
  220. " unique id %s was specified to use a counter."
  221. " Subsequent register calls to unique id must"
  222. " specify use of a counter as well." % unique_id)
  223. else:
  224. self._unique_id_handlers[unique_id]['count'] += 1
  225. else:
  226. if count:
  227. raise ValueError("Initial registration of"
  228. " unique id %s was specified to not use a counter."
  229. " Subsequent register calls to unique id must"
  230. " specify not to use a counter as well." %
  231. unique_id)
  232. return
  233. else:
  234. # Note that the trie knows nothing about the unique
  235. # id. We track uniqueness in this class via the
  236. # _unique_id_handlers.
  237. self._handlers.append_item(event_name, handler,
  238. section=section)
  239. unique_id_handler_item = {'handler': handler}
  240. if unique_id_uses_count:
  241. unique_id_handler_item['count'] = 1
  242. self._unique_id_handlers[unique_id] = unique_id_handler_item
  243. else:
  244. self._handlers.append_item(event_name, handler, section=section)
  245. # Super simple caching strategy for now, if we change the registrations
  246. # clear the cache. This has the opportunity for smarter invalidations.
  247. self._lookup_cache = {}
  248. def unregister(self, event_name, handler=None, unique_id=None,
  249. unique_id_uses_count=False):
  250. if unique_id is not None:
  251. try:
  252. count = self._unique_id_handlers[unique_id].get('count', None)
  253. except KeyError:
  254. # There's no handler matching that unique_id so we have
  255. # nothing to unregister.
  256. return
  257. if unique_id_uses_count:
  258. if count == None:
  259. raise ValueError("Initial registration of"
  260. " unique id %s was specified to use a counter."
  261. " Subsequent unregister calls to unique id must"
  262. " specify use of a counter as well." % unique_id)
  263. elif count == 1:
  264. handler = self._unique_id_handlers.pop(unique_id)['handler']
  265. else:
  266. self._unique_id_handlers[unique_id]['count'] -= 1
  267. return
  268. else:
  269. if count:
  270. raise ValueError("Initial registration of"
  271. " unique id %s was specified to not use a counter."
  272. " Subsequent unregister calls to unique id must"
  273. " specify not to use a counter as well." %
  274. unique_id)
  275. handler = self._unique_id_handlers.pop(unique_id)['handler']
  276. try:
  277. self._handlers.remove_item(event_name, handler)
  278. self._lookup_cache = {}
  279. except ValueError:
  280. pass
  281. def __copy__(self):
  282. new_instance = self.__class__()
  283. new_state = self.__dict__.copy()
  284. new_state['_handlers'] = copy.copy(self._handlers)
  285. new_state['_unique_id_handlers'] = copy.copy(self._unique_id_handlers)
  286. new_instance.__dict__ = new_state
  287. return new_instance
  288. class _PrefixTrie(object):
  289. """Specialized prefix trie that handles wildcards.
  290. The prefixes in this case are based on dot separated
  291. names so 'foo.bar.baz' is::
  292. foo -> bar -> baz
  293. Wildcard support just means that having a key such as 'foo.bar.*.baz' will
  294. be matched with a call to ``get_items(key='foo.bar.ANYTHING.baz')``.
  295. You can think of this prefix trie as the equivalent as defaultdict(list),
  296. except that it can do prefix searches:
  297. foo.bar.baz -> A
  298. foo.bar -> B
  299. foo -> C
  300. Calling ``get_items('foo.bar.baz')`` will return [A + B + C], from
  301. most specific to least specific.
  302. """
  303. def __init__(self):
  304. # Each dictionary can be though of as a node, where a node
  305. # has values associated with the node, and children is a link
  306. # to more nodes. So 'foo.bar' would have a 'foo' node with
  307. # a 'bar' node as a child of foo.
  308. # {'foo': {'children': {'bar': {...}}}}.
  309. self._root = {'chunk': None, 'children': {}, 'values': None}
  310. def append_item(self, key, value, section=_MIDDLE):
  311. """Add an item to a key.
  312. If a value is already associated with that key, the new
  313. value is appended to the list for the key.
  314. """
  315. key_parts = key.split('.')
  316. current = self._root
  317. for part in key_parts:
  318. if part not in current['children']:
  319. new_child = {'chunk': part, 'values': None, 'children': {}}
  320. current['children'][part] = new_child
  321. current = new_child
  322. else:
  323. current = current['children'][part]
  324. if current['values'] is None:
  325. current['values'] = NodeList([], [], [])
  326. current['values'][section].append(value)
  327. def prefix_search(self, key):
  328. """Collect all items that are prefixes of key.
  329. Prefix in this case are delineated by '.' characters so
  330. 'foo.bar.baz' is a 3 chunk sequence of 3 "prefixes" (
  331. "foo", "bar", and "baz").
  332. """
  333. collected = deque()
  334. key_parts = key.split('.')
  335. current = self._root
  336. self._get_items(current, key_parts, collected, 0)
  337. return collected
  338. def _get_items(self, starting_node, key_parts, collected, starting_index):
  339. stack = [(starting_node, starting_index)]
  340. key_parts_len = len(key_parts)
  341. # Traverse down the nodes, where at each level we add the
  342. # next part from key_parts as well as the wildcard element '*'.
  343. # This means for each node we see we potentially add two more
  344. # elements to our stack.
  345. while stack:
  346. current_node, index = stack.pop()
  347. if current_node['values']:
  348. # We're using extendleft because we want
  349. # the values associated with the node furthest
  350. # from the root to come before nodes closer
  351. # to the root. extendleft() also adds its items
  352. # in right-left order so .extendleft([1, 2, 3])
  353. # will result in final_list = [3, 2, 1], which is
  354. # why we reverse the lists.
  355. node_list = current_node['values']
  356. complete_order = (node_list.first + node_list.middle +
  357. node_list.last)
  358. collected.extendleft(reversed(complete_order))
  359. if not index == key_parts_len:
  360. children = current_node['children']
  361. directs = children.get(key_parts[index])
  362. wildcard = children.get('*')
  363. next_index = index + 1
  364. if wildcard is not None:
  365. stack.append((wildcard, next_index))
  366. if directs is not None:
  367. stack.append((directs, next_index))
  368. def remove_item(self, key, value):
  369. """Remove an item associated with a key.
  370. If the value is not associated with the key a ``ValueError``
  371. will be raised. If the key does not exist in the trie, a
  372. ``ValueError`` will be raised.
  373. """
  374. key_parts = key.split('.')
  375. current = self._root
  376. self._remove_item(current, key_parts, value, index=0)
  377. def _remove_item(self, current_node, key_parts, value, index):
  378. if current_node is None:
  379. return
  380. elif index < len(key_parts):
  381. next_node = current_node['children'].get(key_parts[index])
  382. if next_node is not None:
  383. self._remove_item(next_node, key_parts, value, index + 1)
  384. if index == len(key_parts) - 1:
  385. node_list = next_node['values']
  386. if value in node_list.first:
  387. node_list.first.remove(value)
  388. elif value in node_list.middle:
  389. node_list.middle.remove(value)
  390. elif value in node_list.last:
  391. node_list.last.remove(value)
  392. if not next_node['children'] and not next_node['values']:
  393. # Then this is a leaf node with no values so
  394. # we can just delete this link from the parent node.
  395. # This makes subsequent search faster in the case
  396. # where a key does not exist.
  397. del current_node['children'][key_parts[index]]
  398. else:
  399. raise ValueError(
  400. "key is not in trie: %s" % '.'.join(key_parts))
  401. def __copy__(self):
  402. # The fact that we're using a nested dict under the covers
  403. # is an implementation detail, and the user shouldn't have
  404. # to know that they'd normally need a deepcopy so we expose
  405. # __copy__ instead of __deepcopy__.
  406. new_copy = self.__class__()
  407. copied_attrs = self._recursive_copy(self.__dict__)
  408. new_copy.__dict__ = copied_attrs
  409. return new_copy
  410. def _recursive_copy(self, node):
  411. # We can't use copy.deepcopy because we actually only want to copy
  412. # the structure of the trie, not the handlers themselves.
  413. # Each node has a chunk, children, and values.
  414. copied_node = {}
  415. for key, value in node.items():
  416. if isinstance(value, NodeList):
  417. copied_node[key] = copy.copy(value)
  418. elif isinstance(value, dict):
  419. copied_node[key] = self._recursive_copy(value)
  420. else:
  421. copied_node[key] = value
  422. return copied_node