| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import abc |
| 4 |
import typing as t |
| 5 |
|
| 6 |
from contextvars import ContextVar |
| 7 |
|
| 8 |
from ansible.module_utils._internal._datatag import AnsibleTagHelper |
| 9 |
|
| 10 |
|
| 11 |
class NotifiableAccessContextBase(metaclass=abc.ABCMeta): |
| 12 |
"""Base class for a context manager that, when active, receives notification of managed access for types/tags in which it has registered an interest.""" |
| 13 |
|
| 14 |
_type_interest: t.FrozenSet[type] = frozenset() |
| 15 |
"""Set of types (including tag types) for which this context will be notified upon access.""" |
| 16 |
|
| 17 |
_mask: t.ClassVar[bool] = False |
| 18 |
"""When true, only the innermost (most recently created) context of this type will be notified.""" |
| 19 |
|
| 20 |
def __enter__(self): |
| 21 |
# noinspection PyProtectedMember |
| 22 |
AnsibleAccessContext.current()._register_interest(self) |
| 23 |
return self |
| 24 |
|
| 25 |
def __exit__(self, exc_type, exc_val, exc_tb) -> None: |
| 26 |
# noinspection PyProtectedMember |
| 27 |
AnsibleAccessContext.current()._unregister_interest(self) |
| 28 |
return None |
| 29 |
|
| 30 |
@abc.abstractmethod |
| 31 |
def _notify(self, o: t.Any) -> t.Any: |
| 32 |
"""Derived classes implement custom notification behavior when a registered type or tag is accessed.""" |
| 33 |
|
| 34 |
|
| 35 |
class AnsibleAccessContext: |
| 36 |
""" |
| 37 |
Broker object for managed access registration and notification. |
| 38 |
Each thread or other logical callstack has a dedicated `AnsibleAccessContext` object with which `NotifiableAccessContext` objects can register interest. |
| 39 |
When a managed access occurs on an object, each active `NotifiableAccessContext` within the current callstack that has registered interest in that |
| 40 |
object's type or a tag present on it will be notified. |
| 41 |
""" |
| 42 |
|
| 43 |
_contextvar: t.ClassVar[ContextVar[AnsibleAccessContext]] = ContextVar('AnsibleAccessContext') |
| 44 |
|
| 45 |
@staticmethod |
| 46 |
def current() -> AnsibleAccessContext: |
| 47 |
"""Creates or retrieves an `AnsibleAccessContext` for the current logical callstack.""" |
| 48 |
try: |
| 49 |
ctx: AnsibleAccessContext = AnsibleAccessContext._contextvar.get() |
| 50 |
except LookupError: |
| 51 |
# didn't exist; create it |
| 52 |
ctx = AnsibleAccessContext() |
| 53 |
AnsibleAccessContext._contextvar.set(ctx) # we ignore the token, since this should live for the life of the thread/async ctx |
| 54 |
|
| 55 |
return ctx |
| 56 |
|
| 57 |
def __init__(self) -> None: |
| 58 |
self._notify_contexts: list[NotifiableAccessContextBase] = [] |
| 59 |
|
| 60 |
def _register_interest(self, context: NotifiableAccessContextBase) -> None: |
| 61 |
self._notify_contexts.append(context) |
| 62 |
|
| 63 |
def _unregister_interest(self, context: NotifiableAccessContextBase) -> None: |
| 64 |
ctx = self._notify_contexts.pop() |
| 65 |
|
| 66 |
if ctx is not context: |
| 67 |
raise RuntimeError(f'Out-of-order context deactivation detected. Found {ctx} instead of {context}.') |
| 68 |
|
| 69 |
def access(self, value: t.Any) -> None: |
| 70 |
"""Notify all contexts which have registered interest in the given value that it is being accessed.""" |
| 71 |
if not self._notify_contexts: |
| 72 |
return |
| 73 |
|
| 74 |
value_types = AnsibleTagHelper.tag_types(value) | frozenset((type(value),)) |
| 75 |
masked: set[type] = set() |
| 76 |
|
| 77 |
for ctx in reversed(self._notify_contexts): |
| 78 |
if ctx._mask: |
| 79 |
if (ctx_type := type(ctx)) in masked: |
| 80 |
continue |
| 81 |
|
| 82 |
masked.add(ctx_type) |
| 83 |
|
| 84 |
# noinspection PyProtectedMember |
| 85 |
if ctx._type_interest.intersection(value_types): |
| 86 |
ctx._notify(value) |