| 1 |
# Copyright (c) 2024 Ansible Project |
| 2 |
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause) |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
import contextlib |
| 7 |
import contextvars |
| 8 |
|
| 9 |
# deprecated: description='typing.Self exists in Python 3.11+' python_version='3.10' |
| 10 |
from ..compat import typing as t |
| 11 |
|
| 12 |
|
| 13 |
class AmbientContextBase: |
| 14 |
""" |
| 15 |
An abstract base context manager that, once entered, will be accessible via its `current` classmethod to any code in the same |
| 16 |
`contextvars` context (e.g. same thread/coroutine), until it is exited. |
| 17 |
""" |
| 18 |
|
| 19 |
__slots__ = ('_contextvar_token',) |
| 20 |
|
| 21 |
# DTFIX-FUTURE: subclasses need to be able to opt-in to blocking nested contexts of the same type (basically optional per-callstack singleton behavior) |
| 22 |
# DTFIX-FUTURE: this class should enforce strict nesting of contexts; overlapping context lifetimes leads to incredibly difficult to |
| 23 |
# debug situations with undefined behavior, so it should fail fast. |
| 24 |
# DTFIX-FUTURE: make frozen=True dataclass subclasses work (fix the mutability of the contextvar instance) |
| 25 |
|
| 26 |
_contextvar: t.ClassVar[contextvars.ContextVar] # pylint: disable=declare-non-slot # pylint bug, see https://github.com/pylint-dev/pylint/issues/9950 |
| 27 |
_contextvar_token: contextvars.Token |
| 28 |
|
| 29 |
def __init_subclass__(cls, **kwargs) -> None: |
| 30 |
cls._contextvar = contextvars.ContextVar(cls.__name__) |
| 31 |
|
| 32 |
@classmethod |
| 33 |
def when(cls, condition: bool, /, *args, **kwargs) -> t.Self | contextlib.nullcontext: |
| 34 |
"""Return an instance of the context if `condition` is `True`, otherwise return a `nullcontext` instance.""" |
| 35 |
return cls(*args, **kwargs) if condition else contextlib.nullcontext() |
| 36 |
|
| 37 |
@classmethod |
| 38 |
def current(cls, optional: bool = False) -> t.Self | None: |
| 39 |
""" |
| 40 |
Return the currently active context value for the current thread or coroutine. |
| 41 |
Raises ReferenceError if a context is not active, unless `optional` is `True`. |
| 42 |
""" |
| 43 |
try: |
| 44 |
return cls._contextvar.get() |
| 45 |
except LookupError: |
| 46 |
if optional: |
| 47 |
return None |
| 48 |
|
| 49 |
raise ReferenceError(f"A required {cls.__name__} context is not active.") from None |
| 50 |
|
| 51 |
def __enter__(self) -> t.Self: |
| 52 |
# DTFIX-FUTURE: actively block multiple entry |
| 53 |
self._contextvar_token = self.__class__._contextvar.set(self) |
| 54 |
return self |
| 55 |
|
| 56 |
def __exit__(self, exc_type, exc_val, exc_tb) -> None: |
| 57 |
self.__class__._contextvar.reset(self._contextvar_token) |
| 58 |
del self._contextvar_token |