Skip to content

Commit 42b55d6

Browse files
committed
experimenting with wrappingcontext for dd-trace-api integration
1 parent 94a7494 commit 42b55d6

File tree

1 file changed

+43
-2
lines changed
  • ddtrace/contrib/internal/dd_trace_api

1 file changed

+43
-2
lines changed

ddtrace/contrib/internal/dd_trace_api/patch.py

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,53 @@
44
from typing import List
55
from typing import Optional
66
from typing import Tuple
7+
from typing import TypeVar
78
import weakref
89

910
import dd_trace_api
11+
from wrapt.importer import when_imported
1012

1113
import ddtrace
14+
from ddtrace.internal.logger import get_logger
15+
from ddtrace.internal.wrapping.context import WrappingContext
1216

1317

1418
_DD_HOOK_NAME = "dd.hook"
1519
_TRACER_KEY = "Tracer"
1620
_STUB_TO_REAL = weakref.WeakKeyDictionary()
1721
_STUB_TO_REAL[dd_trace_api.tracer] = ddtrace.tracer
22+
log = get_logger(__name__)
23+
T = TypeVar("T")
24+
25+
26+
class DDTraceAPIWrappingContextBase(WrappingContext):
27+
def _handle_return(self) -> None:
28+
method_name = self.__frame__.f_code.co_name
29+
stub_self = self.get_local("self")
30+
api_return_value = self.get_local("retval")
31+
_call_on_real_instance(stub_self, method_name, api_return_value, self.get_local("name"))
32+
33+
def _handle_enter(self) -> None:
34+
pass
35+
36+
def __enter__(self) -> "DDTraceAPIWrappingContextBase":
37+
super().__enter__()
38+
39+
try:
40+
self._handle_enter()
41+
except Exception: # noqa: E722
42+
log.debug("Error handling dd_trace_api instrumentation enter", exc_info=True)
43+
44+
return self
45+
46+
def __return__(self, value: T) -> T:
47+
"""Always return the original value no matter what our instrumentation does"""
48+
try:
49+
self._handle_return()
50+
except Exception: # noqa: E722
51+
log.debug("Error handling instrumentation return", exc_info=True)
52+
53+
return value
1854

1955

2056
def _proxy_span_arguments(args: List, kwargs: Dict) -> Tuple[List, Dict]:
@@ -57,12 +93,17 @@ def get_version() -> str:
5793
def patch(tracer=None):
5894
if getattr(dd_trace_api, "__datadog_patch", False):
5995
return
60-
dd_trace_api.__datadog_patch = True
6196
_STUB_TO_REAL[dd_trace_api.tracer] = tracer
62-
if not getattr(dd_trace_api, "__dd_has_audit_hook", False):
97+
if False and not getattr(dd_trace_api, "__dd_has_audit_hook", False):
6398
addaudithook(_hook)
6499
dd_trace_api.__dd_has_audit_hook = True
65100

101+
@when_imported("dd_trace_api")
102+
def _(m):
103+
DDTraceAPIWrappingContextBase(m.Tracer.start_span).wrap()
104+
105+
dd_trace_api.__datadog_patch = True
106+
66107

67108
def unpatch():
68109
if not getattr(dd_trace_api, "__datadog_patch", False):

0 commit comments

Comments
 (0)