File: listener.py

package info (click to toggle)
mopidy 3.4.2-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,616 kB
  • sloc: python: 16,656; sh: 159; makefile: 126
file content (49 lines) | stat: -rw-r--r-- 1,640 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import logging

import pykka
from pykka.messages import ProxyCall

logger = logging.getLogger(__name__)


def send(cls, event, **kwargs):
    listeners = pykka.ActorRegistry.get_by_class(cls)
    logger.debug("Sending %s to %s: %s", event, cls.__name__, kwargs)
    for listener in listeners:
        # Save time by calling methods on Pykka actor without creating a
        # throwaway actor proxy.
        #
        # Because we use `.tell()` there is no return channel for any errors,
        # so Pykka logs them immediately. The alternative would be to use
        # `.ask()` and `.get()` the returned futures to block for the listeners
        # to react and return their exceptions to us. Since emitting events in
        # practise is making calls upwards in the stack, blocking here would
        # quickly deadlock.
        listener.tell(
            ProxyCall(
                attr_path=["on_event"],
                args=[event],
                kwargs=kwargs,
            )
        )


class Listener:
    def on_event(self, event, **kwargs):
        """
        Called on all events.

        *MAY* be implemented by actor. By default, this method forwards the
        event to the specific event methods.

        :param event: the event name
        :type event: string
        :param kwargs: any other arguments to the specific event handlers
        """
        try:
            getattr(self, event)(**kwargs)
        except Exception:
            # Ensure we don't crash the actor due to "bad" events.
            logger.exception(
                "Triggering event failed: %s(%s)", event, ", ".join(kwargs)
            )