Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

127 changes: 101 additions & 26 deletions aws_lambda_powertools/tracing/tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,15 @@
T = TypeVar("T")


async def _async_generator_placeholder(): # pragma: no cover
yield


# Every function built by contextlib.asynccontextmanager shares this code object. Matching it tells an
# async context manager apart from any other wrapper (functools.wraps) around an async generator.
_ASYNC_CONTEXT_MANAGER_CODE = contextlib.asynccontextmanager(_async_generator_placeholder).__code__


def _is_cold_start() -> bool:
"""Verifies whether is cold start

Expand Down Expand Up @@ -567,35 +576,26 @@
choice=capture_error,
)

# Maintenance: Need a factory/builder here to simplify this now
wrapped = getattr(method, "__wrapped__", None)
if inspect.iscoroutinefunction(method):
return self._decorate_async_function(
method=method,
capture_response=capture_response,
capture_error=capture_error,
method_name=method_name,
)
decorate = self._decorate_async_function
elif inspect.isasyncgenfunction(method):
decorate = self._decorate_async_generator_function
elif getattr(method, "__code__", None) is _ASYNC_CONTEXT_MANAGER_CODE:
decorate = self._decorate_async_generator_function_with_context_manager
elif inspect.isgeneratorfunction(method):
return self._decorate_generator_function(
method=method,
capture_response=capture_response,
capture_error=capture_error,
method_name=method_name,
)
elif hasattr(method, "__wrapped__") and inspect.isgeneratorfunction(method.__wrapped__):
return self._decorate_generator_function_with_context_manager(
method=method,
capture_response=capture_response,
capture_error=capture_error,
method_name=method_name,
)
decorate = self._decorate_generator_function
elif wrapped is not None and inspect.isgeneratorfunction(wrapped):
decorate = self._decorate_generator_function_with_context_manager
else:
return self._decorate_sync_function(
method=method,
capture_response=capture_response,
capture_error=capture_error,
method_name=method_name,
)
decorate = self._decorate_sync_function

return decorate(
method=method,
capture_response=capture_response,
capture_error=capture_error,
method_name=method_name,
)

def _decorate_async_function(
self,
Expand Down Expand Up @@ -663,6 +663,81 @@

return decorate

def _decorate_async_generator_function(
self,
method: Callable,
capture_response: bool | str | None = None, # an async generator has no return value to capture
capture_error: bool | str | None = None,
method_name: str | None = None,
):
@functools.wraps(method)
async def decorate(*args, **kwargs):
async with self.provider.in_subsegment_async(name=f"## {method_name}") as subsegment:
try:
logger.debug(f"Calling method: {method_name}")
# Async generators have no `yield from`, so forward sent values and thrown
# exceptions by hand; asynccontextmanager relies on athrow reaching the method
agen = method(*args, **kwargs)
try:
value = await agen.__anext__()
while True:
try:
sent = yield value
except GeneratorExit:
await agen.aclose()
raise
except BaseException as exc:

Check failure on line 689 in aws_lambda_powertools/tracing/tracer.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Catch a more specific exception or reraise the exception

See more on https://sonarcloud.io/project/issues?id=aws-powertools_powertools-lambda-python&issues=AaJDIOPPCAqMBt_T_Wrr&open=AaJDIOPPCAqMBt_T_Wrr&pullRequest=8956
value = await agen.athrow(exc)
else:
value = await agen.asend(sent)
except StopAsyncIteration:
pass
except Exception as err:
logger.exception(f"Exception received from '{method_name}' method")
self._add_full_exception_as_metadata(
method_name=method_name,
error=err,
subsegment=subsegment,
capture_error=capture_error,
)
raise

return decorate

def _decorate_async_generator_function_with_context_manager(
self,
method: Callable,
capture_response: bool | str | None = None,
capture_error: bool | str | None = None,
method_name: str | None = None,
):
@functools.wraps(method)
@contextlib.asynccontextmanager
async def decorate(*args, **kwargs):
async with self.provider.in_subsegment_async(name=f"## {method_name}") as subsegment:
try:
logger.debug(f"Calling method: {method_name}")
async with method(*args, **kwargs) as return_val:
result = return_val
yield result
self._add_response_as_metadata(
method_name=method_name,
data=result,
subsegment=subsegment,
capture_response=capture_response,
)
except Exception as err:
logger.exception(f"Exception received from '{method_name}' method")
self._add_full_exception_as_metadata(
method_name=method_name,
error=err,
subsegment=subsegment,
capture_error=capture_error,
)
raise

return decorate

def _decorate_generator_function_with_context_manager(
self,
method: Callable,
Expand Down
2 changes: 1 addition & 1 deletion docs/core/tracer.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ You can trace synchronous functions using the `capture_method` decorator.
???+ warning
We do not support asynchronous Lambda handler

You can trace asynchronous functions and generator functions (including context managers) using `capture_method`.
You can trace asynchronous functions, generator functions and async generator functions (including context managers built with `contextlib.contextmanager` or `contextlib.asynccontextmanager`) using `capture_method`. For generators, the subsegment stays open until iteration ends.

=== "capture_method_async.py"

Expand Down
134 changes: 134 additions & 0 deletions tests/unit/test_tracing.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import contextlib
import functools
from typing import TYPE_CHECKING, NamedTuple
from unittest import mock

Expand Down Expand Up @@ -725,3 +726,136 @@
tracer.ignore_endpoint(hostname="https://foo.com/")
# THEN don't call xray add_ignored
assert mock_add_ignored.call_count == 0


@pytest.mark.asyncio
async def test_tracer_async_generator_keeps_subsegment_open_while_iterating(mocker, provider_stub):
# GIVEN tracer is initialized with a provider that records when the subsegment opens and closes
events = []
subsegment = mocker.MagicMock()

@contextlib.asynccontextmanager
async def in_subsegment_async(name=None, **kwargs):
events.append("open")
yield subsegment
events.append("close")

tracer = Tracer(provider=provider_stub(in_subsegment_async=in_subsegment_async), service="booking")

# WHEN capture_method decorator is used on an async generator function
@tracer.capture_method
async def fetch_pages():
yield "page 1"
yield "page 2"

async for page in fetch_pages():
events.append(page)

# THEN the subsegment stays open while the caller iterates
# and no generator object is added as response metadata
assert events == ["open", "page 1", "page 2", "close"]
assert subsegment.put_metadata.call_count == 0


@pytest.mark.asyncio
async def test_tracer_async_generator_exception_metadata(provider_stub, in_subsegment_mock):
# GIVEN tracer is initialized
provider = provider_stub(in_subsegment_async=in_subsegment_mock.in_subsegment)
tracer = Tracer(provider=provider, service="booking")

# WHEN an async generator decorated with capture_method raises while iterating
@tracer.capture_method
async def fetch_pages():
yield "page 1"
raise ValueError("test")

with pytest.raises(ValueError):
_ = [page async for page in fetch_pages()]

# THEN we should add the exception using method name as key plus error
put_metadata_mock_args = in_subsegment_mock.put_metadata.call_args[1]
assert (
put_metadata_mock_args["key"]
== f"{MODULE_PREFIX}.test_tracer_async_generator_exception_metadata.locals.fetch_pages error"
)
assert put_metadata_mock_args["namespace"] == "booking"
assert isinstance(put_metadata_mock_args["value"], ValueError)


@pytest.mark.asyncio
async def test_tracer_async_context_manager_over_capture_method(provider_stub, in_subsegment_mock):
# GIVEN tracer is initialized
provider = provider_stub(in_subsegment_async=in_subsegment_mock.in_subsegment)
tracer = Tracer(provider=provider, service="booking")
cleanup = []

# WHEN asynccontextmanager wraps a method decorated with capture_method
@contextlib.asynccontextmanager
@tracer.capture_method
async def collect_payment():
try:
yield "receipt"
except KeyError:
cleanup.append("handled")
raise

# THEN an exception raised in the with block reaches the generator, as it does without tracing
with pytest.raises(KeyError):

Check warning on line 803 in tests/unit/test_tracing.py

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this exception test to have only one invocation possibly throwing an exception.

See more on https://sonarcloud.io/project/issues?id=aws-powertools_powertools-lambda-python&issues=AaJDIOLKCAqMBt_T_Wrq&open=AaJDIOLKCAqMBt_T_Wrq&pullRequest=8956
async with collect_payment() as receipt:
assert receipt == "receipt"
raise KeyError("missing")

assert cleanup == ["handled"]
assert isinstance(in_subsegment_mock.put_metadata.call_args[1]["value"], KeyError)


@pytest.mark.asyncio
async def test_tracer_capture_method_over_async_context_manager(mocker, provider_stub):
# GIVEN tracer is initialized with a provider that records when the subsegment opens and closes
events = []
subsegment = mocker.MagicMock()

@contextlib.asynccontextmanager
async def in_subsegment_async(name=None, **kwargs):
events.append("open")
yield subsegment
events.append("close")

tracer = Tracer(provider=provider_stub(in_subsegment_async=in_subsegment_async), service="booking")

# WHEN capture_method decorates an async context manager
@tracer.capture_method
@contextlib.asynccontextmanager
async def collect_payment():
yield "receipt"

async with collect_payment() as receipt:
events.append(receipt)

# THEN the subsegment stays open inside the with block
# and the yielded value is added as response metadata
assert events == ["open", "receipt", "close"]
assert subsegment.put_metadata.call_args[1]["value"] == "receipt"


@pytest.mark.asyncio
async def test_tracer_wrapped_async_generator_that_is_not_a_context_manager(provider_stub, in_subsegment_mock):
# GIVEN tracer is initialized
provider = provider_stub(in_subsegment=in_subsegment_mock.in_subsegment)
tracer = Tracer(provider=provider, service="booking")

def passthrough(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)

return wrapper

# WHEN capture_method decorates a plain wrapper around an async generator
@tracer.capture_method
@passthrough
async def fetch_pages():
yield "page 1"

# THEN the wrapper is still called like a regular function and the generator works
assert [page async for page in fetch_pages()] == ["page 1"]