-
Notifications
You must be signed in to change notification settings - Fork 652
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Make
tracer.start_as_current_span()
decorator work with async funct…
…ions (#3633) * test: add a minimal test that reproduce the bug Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: replaced contextmanager by my own agnosticcontextmanager * docs: changelog Signed-off-by: QuentinN42 <quentin@lieumont.fr> * docs: typo Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: linting Signed-off-by: QuentinN42 <quentin@lieumont.fr> * feat: reimplement the contextlib._GeneratorContextManager inside the trace api Signed-off-by: QuentinN42 <quentin@lieumont.fr> * refactor: merge tests Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: make agnosticcontextmanager as protected Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: changelog Signed-off-by: QuentinN42 <quentin@lieumont.fr> * feat: start typing Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: revert to acdfa03 implementation and fix mypy Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: use super call on the synchronous branch Co-authored-by: Aaron Abbott <aaronabbott@google.com> * fix: typing compliant with 3.8 Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: black Signed-off-by: QuentinN42 <quentin@lieumont.fr> * feat: added tests and fixed lint in python 3.10 Signed-off-by: QuentinN42 <quentin@lieumont.fr> * feat: use_span use the _agnosticcontextmanager Signed-off-by: QuentinN42 <quentin@lieumont.fr> * docs: explain why we have an overriden class Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: use typing.Generic for pre 3.9 compatibility Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: typo Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: mypy api/src Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: ignore reference to privat attributes Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: mv cm inside test Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: define __call__ as Coroutine and not awaitable Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: mypy green Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: py38 tests ok Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: reimplementing __enter__ to avoid the type error. Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: lint Signed-off-by: QuentinN42 <quentin@lieumont.fr> * fix: mypy Signed-off-by: QuentinN42 <quentin@lieumont.fr> * test: rm test_wraps_contextlib Signed-off-by: QuentinN42 <quentin@lieumont.fr> * docs: document why we are overriding the contextlib._GeneratorContextManager class Signed-off-by: QuentinN42 <quentin@lieumont.fr> * docs: mv feat to unreleased section Signed-off-by: QuentinN42 <quentin@lieumont.fr> * test: rename lst with a more readable name Signed-off-by: QuentinN42 <quentin@lieumont.fr> * Remove unused type ignore comment * Fix missing symbol The missing symbol error was caused by a rebase on main and subsequent force push by me, sorry. --------- Signed-off-by: QuentinN42 <quentin@lieumont.fr> Co-authored-by: Aaron Abbott <aaronabbott@google.com> Co-authored-by: Diego Hurtado <ocelotl@users.noreply.github.com>
- Loading branch information
1 parent
d6321d6
commit 5a6da15
Showing
8 changed files
with
186 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import asyncio | ||
import contextlib | ||
import functools | ||
import typing | ||
from typing import Callable, Generic, Iterator, TypeVar | ||
|
||
V = TypeVar("V") | ||
R = TypeVar("R") # Return type | ||
Pargs = TypeVar("Pargs") # Generic type for arguments | ||
Pkwargs = TypeVar("Pkwargs") # Generic type for arguments | ||
|
||
if hasattr(typing, "ParamSpec"): | ||
# only available in python 3.10+ | ||
# https://peps.python.org/pep-0612/ | ||
P = typing.ParamSpec("P") # Generic type for all arguments | ||
|
||
|
||
class _AgnosticContextManager( | ||
contextlib._GeneratorContextManager, Generic[R] # type: ignore # FIXME use contextlib._GeneratorContextManager[R] when we drop the python 3.8 support | ||
): # pylint: disable=protected-access | ||
"""Context manager that can decorate both async and sync functions. | ||
This is an overridden version of the contextlib._GeneratorContextManager | ||
class that will decorate async functions with an async context manager | ||
to end the span AFTER the entire async function coroutine finishes. | ||
Else it will report near zero spans durations for async functions. | ||
We are overriding the contextlib._GeneratorContextManager class as | ||
reimplementing it is a lot of code to maintain and this class (even if it's | ||
marked as protected) doesn't seems like to be evolving a lot. | ||
For more information, see: | ||
https://github.com/open-telemetry/opentelemetry-python/pull/3633 | ||
""" | ||
|
||
def __enter__(self) -> R: | ||
"""Reimplementing __enter__ to avoid the type error. | ||
The original __enter__ method returns Any type, but we want to return R. | ||
""" | ||
del self.args, self.kwds, self.func # type: ignore | ||
try: | ||
return next(self.gen) # type: ignore | ||
except StopIteration: | ||
raise RuntimeError("generator didn't yield") from None | ||
|
||
def __call__(self, func: V) -> V: | ||
if asyncio.iscoroutinefunction(func): | ||
|
||
@functools.wraps(func) # type: ignore | ||
async def async_wrapper(*args: Pargs, **kwargs: Pkwargs) -> R: | ||
with self._recreate_cm(): # type: ignore | ||
return await func(*args, **kwargs) # type: ignore | ||
|
||
return async_wrapper # type: ignore | ||
return super().__call__(func) # type: ignore | ||
|
||
|
||
def _agnosticcontextmanager( | ||
func: "Callable[P, Iterator[R]]", | ||
) -> "Callable[P, _AgnosticContextManager[R]]": | ||
@functools.wraps(func) | ||
def helper(*args: Pargs, **kwargs: Pkwargs) -> _AgnosticContextManager[R]: | ||
return _AgnosticContextManager(func, args, kwargs) | ||
|
||
return helper |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
# Copyright The OpenTelemetry Authors | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import asyncio | ||
import unittest | ||
from typing import Callable, Iterator | ||
|
||
from opentelemetry.util._decorator import _agnosticcontextmanager | ||
|
||
|
||
@_agnosticcontextmanager | ||
def cm() -> Iterator[int]: | ||
yield 3 | ||
|
||
|
||
@_agnosticcontextmanager | ||
def cm_call_when_done(f: Callable[[], None]) -> Iterator[int]: | ||
yield 3 | ||
f() | ||
|
||
|
||
class TestContextManager(unittest.TestCase): | ||
def test_sync_with(self): | ||
with cm() as val: | ||
self.assertEqual(val, 3) | ||
|
||
def test_decorate_sync_func(self): | ||
@cm() | ||
def sync_func(a: str) -> str: | ||
return a + a | ||
|
||
res = sync_func("a") | ||
self.assertEqual(res, "aa") | ||
|
||
def test_decorate_async_func(self): | ||
# Test that a universal context manager decorating an async function runs it's cleanup | ||
# code after the entire async function coroutine finishes. This silently fails when | ||
# using the normal @contextmanager decorator, which runs it's __exit__() after the | ||
# un-started coroutine is returned. | ||
# | ||
# To see this behavior, change cm_call_when_done() to | ||
# be decorated with @contextmanager. | ||
|
||
events = [] | ||
|
||
@cm_call_when_done(lambda: events.append("cm_done")) | ||
async def async_func(a: str) -> str: | ||
events.append("start_async_func") | ||
await asyncio.sleep(0) | ||
events.append("finish_sleep") | ||
return a + a | ||
|
||
res = asyncio.run(async_func("a")) | ||
self.assertEqual(res, "aa") | ||
self.assertEqual( | ||
events, ["start_async_func", "finish_sleep", "cm_done"] | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters