Debian Codegraph @

src/trio/_core/_instrumentation.py

raw
1 from __future__ import annotations
2
3 import logging
4 import types
5 from collections import UserDict
6 from typing import TYPE_CHECKING, TypeVar
7
8 from .._abc import Instrument
9
10 # Used to log exceptions in instruments
11 INSTRUMENT_LOGGER = logging.getLogger("trio.abc.Instrument")
12
13 if TYPE_CHECKING:
14 from collections.abc import Sequence
15
16 T = TypeVar("T")
17
18
19 # Decorator to mark methods public. This does nothing by itself, but
20 # trio/_tools/gen_exports.py looks for it.
21 def _public(fn: T) -> T:
22 return fn
23
24
25 class Instruments(UserDict[str, dict[Instrument, None]]):
26 """A collection of `trio.abc.Instrument` organized by hook.
27
28 Instrumentation calls are rather expensive, and we don't want a
29 rarely-used instrument (like before_run()) to slow down hot
30 operations (like before_task_step()). Thus, we cache the set of
31 instruments to be called for each hook, and skip the instrumentation
32 call if there's nothing currently installed for that hook.
33 """
34
35 __slots__ = ()
36
37 def __init__(self, incoming: Sequence[Instrument]) -> None:
38 super().__init__({"_all": {}})
39 for instrument in incoming:
40 self.add_instrument(instrument)
41
42 @_public
43 def add_instrument(self, instrument: Instrument) -> None:
44 """Start instrumenting the current run loop with the given instrument.
45
46 Args:
47 instrument (trio.abc.Instrument): The instrument to activate.
48
49 If ``instrument`` is already active, does nothing.
50
51 """
52 if instrument in self.data["_all"]:
53 return
54 self.data["_all"][instrument] = None
55 try:
56 for name in dir(instrument):
57 if name.startswith("_"):
58 continue
59 try:
60 prototype = getattr(Instrument, name)
61 except AttributeError:
62 continue
63 impl = getattr(instrument, name)
64 if isinstance(impl, types.MethodType) and impl.__func__ is prototype:
65 # Inherited unchanged from _abc.Instrument
66 continue
67 self.data.setdefault(name, {})[instrument] = None
68 except:
69 self.remove_instrument(instrument)
70 raise
71
72 @_public
73 def remove_instrument(self, instrument: Instrument) -> None:
74 """Stop instrumenting the current run loop with the given instrument.
75
76 Args:
77 instrument (trio.abc.Instrument): The instrument to de-activate.
78
79 Raises:
80 KeyError: if the instrument is not currently active. This could
81 occur either because you never added it, or because you added it
82 and then it raised an unhandled exception and was automatically
83 deactivated.
84
85 """
86 # If instrument isn't present, the KeyError propagates out
87 self.data["_all"].pop(instrument)
88 for hookname, instruments in list(self.data.items()):
89 if instrument in instruments:
90 del instruments[instrument]
91 if not instruments:
92 del self.data[hookname]
93
94 def call(
95 self,
96 hookname: str,
97 *args: object,
98 ) -> None:
99 """Call hookname(*args) on each applicable instrument.
100
101 You must first check whether there are any instruments installed for
102 that hook, e.g.::
103
104 if "before_task_step" in instruments:
105 instruments.call("before_task_step", task)
106 """
107 for instrument in list(self.data[hookname]):
108 try:
109 getattr(instrument, hookname)(*args)
110 except BaseException:
111 self.remove_instrument(instrument)
112 INSTRUMENT_LOGGER.exception(
113 "Exception raised when calling %r on instrument %r. "
114 "Instrument has been disabled.",
115 hookname,
116 instrument,
117 )