Skip to content

Commit b38f9c7

Browse files
ref(integrations): Use ensure_integration_enabled decorator (#2906)
--------- Co-authored-by: Anton Pirker <[email protected]>
1 parent 9e3ae56 commit b38f9c7

23 files changed

+139
-181
lines changed

sentry_sdk/integrations/aiohttp.py

+3-4
Original file line numberDiff line numberDiff line change
@@ -190,12 +190,9 @@ def init(*args, **kwargs):
190190
def create_trace_config():
191191
# type: () -> TraceConfig
192192

193+
@ensure_integration_enabled_async(AioHttpIntegration)
193194
async def on_request_start(session, trace_config_ctx, params):
194195
# type: (ClientSession, SimpleNamespace, TraceRequestStartParams) -> None
195-
client = sentry_sdk.get_client()
196-
if client.get_integration(AioHttpIntegration) is None:
197-
return
198-
199196
method = params.method.upper()
200197

201198
parsed_url = None
@@ -213,6 +210,8 @@ async def on_request_start(session, trace_config_ctx, params):
213210
span.set_data(SPANDATA.HTTP_QUERY, parsed_url.query)
214211
span.set_data(SPANDATA.HTTP_FRAGMENT, parsed_url.fragment)
215212

213+
client = sentry_sdk.get_client()
214+
216215
if should_propagate_trace(client, str(params.url)):
217216
for key, value in Scope.get_current_scope().iter_trace_propagation_headers(
218217
span=span

sentry_sdk/integrations/asyncpg.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -58,14 +58,13 @@ def setup_once() -> None:
5858

5959

6060
def _wrap_execute(f: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
61+
@ensure_integration_enabled_async(AsyncPGIntegration, f)
6162
async def _inner(*args: Any, **kwargs: Any) -> T:
62-
integration = sentry_sdk.get_client().get_integration(AsyncPGIntegration)
63-
6463
# Avoid recording calls to _execute twice.
6564
# Calls to Connection.execute with args also call
6665
# Connection._execute, which is recorded separately
6766
# args[0] = the connection object, args[1] is the query
68-
if integration is None or len(args) > 2:
67+
if len(args) > 2:
6968
return await f(*args, **kwargs)
7069

7170
query = args[1]

sentry_sdk/integrations/atexit.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
from sentry_sdk import Scope
77
from sentry_sdk.utils import logger
88
from sentry_sdk.integrations import Integration
9-
9+
from sentry_sdk.utils import ensure_integration_enabled
1010
from sentry_sdk._types import TYPE_CHECKING
1111

1212
if TYPE_CHECKING:
@@ -44,13 +44,13 @@ def __init__(self, callback=None):
4444
def setup_once():
4545
# type: () -> None
4646
@atexit.register
47+
@ensure_integration_enabled(AtexitIntegration)
4748
def _shutdown():
4849
# type: () -> None
4950
logger.debug("atexit: got shutdown signal")
5051
client = sentry_sdk.get_client()
5152
integration = client.get_integration(AtexitIntegration)
52-
if integration is not None:
53-
logger.debug("atexit: shutting down client")
5453

55-
Scope.get_isolation_scope().end_session()
56-
client.close(callback=integration.callback)
54+
logger.debug("atexit: shutting down client")
55+
Scope.get_isolation_scope().end_session()
56+
client.close(callback=integration.callback)

sentry_sdk/integrations/aws_lambda.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from sentry_sdk.utils import (
1212
AnnotatedValue,
1313
capture_internal_exceptions,
14+
ensure_integration_enabled,
1415
event_from_exception,
1516
logger,
1617
TimeoutThread,
@@ -37,12 +38,10 @@
3738

3839
def _wrap_init_error(init_error):
3940
# type: (F) -> F
41+
@ensure_integration_enabled(AwsLambdaIntegration, init_error)
4042
def sentry_init_error(*args, **kwargs):
4143
# type: (*Any, **Any) -> Any
4244
client = sentry_sdk.get_client()
43-
integration = client.get_integration(AwsLambdaIntegration)
44-
if integration is None:
45-
return init_error(*args, **kwargs)
4645

4746
with capture_internal_exceptions():
4847
Scope.get_isolation_scope().clear_breadcrumbs()
@@ -63,6 +62,7 @@ def sentry_init_error(*args, **kwargs):
6362

6463
def _wrap_handler(handler):
6564
# type: (F) -> F
65+
@ensure_integration_enabled(AwsLambdaIntegration, handler)
6666
def sentry_handler(aws_event, aws_context, *args, **kwargs):
6767
# type: (Any, Any, *Any, **Any) -> Any
6868

@@ -91,8 +91,6 @@ def sentry_handler(aws_event, aws_context, *args, **kwargs):
9191

9292
client = sentry_sdk.get_client()
9393
integration = client.get_integration(AwsLambdaIntegration)
94-
if integration is None:
95-
return handler(aws_event, aws_context, *args, **kwargs)
9694

9795
configured_time = aws_context.get_remaining_time_in_millis()
9896

sentry_sdk/integrations/boto3.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,12 @@
66
from sentry_sdk.tracing import Span
77

88
from sentry_sdk._types import TYPE_CHECKING
9-
from sentry_sdk.utils import capture_internal_exceptions, parse_url, parse_version
9+
from sentry_sdk.utils import (
10+
capture_internal_exceptions,
11+
ensure_integration_enabled,
12+
parse_url,
13+
parse_version,
14+
)
1015

1116
if TYPE_CHECKING:
1217
from typing import Any
@@ -57,11 +62,9 @@ def sentry_patched_init(self, *args, **kwargs):
5762
BaseClient.__init__ = sentry_patched_init
5863

5964

65+
@ensure_integration_enabled(Boto3Integration)
6066
def _sentry_request_created(service_id, request, operation_name, **kwargs):
6167
# type: (str, AWSRequest, str, **Any) -> None
62-
if sentry_sdk.get_client().get_integration(Boto3Integration) is None:
63-
return
64-
6568
description = "aws.%s.%s" % (service_id, operation_name)
6669
span = sentry_sdk.start_span(
6770
op=OP.HTTP_CLIENT,

sentry_sdk/integrations/bottle.py

+2-5
Original file line numberDiff line numberDiff line change
@@ -77,11 +77,10 @@ def sentry_patched_wsgi_app(self, environ, start_response):
7777

7878
old_handle = Bottle._handle
7979

80+
@ensure_integration_enabled(BottleIntegration, old_handle)
8081
def _patched_handle(self, environ):
8182
# type: (Bottle, Dict[str, Any]) -> Any
8283
integration = sentry_sdk.get_client().get_integration(BottleIntegration)
83-
if integration is None:
84-
return old_handle(self, environ)
8584

8685
scope = Scope.get_isolation_scope()
8786
scope._name = "bottle"
@@ -96,13 +95,11 @@ def _patched_handle(self, environ):
9695

9796
old_make_callback = Route._make_callback
9897

98+
@ensure_integration_enabled(BottleIntegration, old_make_callback)
9999
def patched_make_callback(self, *args, **kwargs):
100100
# type: (Route, *object, **object) -> Any
101101
client = sentry_sdk.get_client()
102-
integration = client.get_integration(BottleIntegration)
103102
prepared_callback = old_make_callback(self, *args, **kwargs)
104-
if integration is None:
105-
return prepared_callback
106103

107104
def wrapped_callback(*args, **kwargs):
108105
# type: (*object, **object) -> Any

sentry_sdk/integrations/clickhouse_driver.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from sentry_sdk.tracing import Span
55
from sentry_sdk._types import TYPE_CHECKING
66
from sentry_sdk.scope import should_send_default_pii
7-
from sentry_sdk.utils import capture_internal_exceptions
7+
from sentry_sdk.utils import capture_internal_exceptions, ensure_integration_enabled
88

99
from typing import TypeVar
1010

@@ -74,9 +74,8 @@ def setup_once() -> None:
7474

7575

7676
def _wrap_start(f: Callable[P, T]) -> Callable[P, T]:
77+
@ensure_integration_enabled(ClickhouseDriverIntegration, f)
7778
def _inner(*args: P.args, **kwargs: P.kwargs) -> T:
78-
if sentry_sdk.get_client().get_integration(ClickhouseDriverIntegration) is None:
79-
return f(*args, **kwargs)
8079
connection = args[0]
8180
query = args[1]
8281
query_id = args[2] if len(args) > 2 else kwargs.get("query_id")

sentry_sdk/integrations/django/__init__.py

+15-15
Original file line numberDiff line numberDiff line change
@@ -392,13 +392,11 @@ def _set_transaction_name_and_source(scope, transaction_style, request):
392392
pass
393393

394394

395+
@ensure_integration_enabled(DjangoIntegration)
395396
def _before_get_response(request):
396397
# type: (WSGIRequest) -> None
397398
integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
398399

399-
if integration is None:
400-
return
401-
402400
_patch_drf()
403401

404402
scope = Scope.get_current_scope()
@@ -423,10 +421,11 @@ def _attempt_resolve_again(request, scope, transaction_style):
423421
_set_transaction_name_and_source(scope, transaction_style, request)
424422

425423

424+
@ensure_integration_enabled(DjangoIntegration)
426425
def _after_get_response(request):
427426
# type: (WSGIRequest) -> None
428427
integration = sentry_sdk.get_client().get_integration(DjangoIntegration)
429-
if integration is None or integration.transaction_style != "url":
428+
if integration.transaction_style != "url":
430429
return
431430

432431
scope = Scope.get_current_scope()
@@ -492,21 +491,22 @@ def wsgi_request_event_processor(event, hint):
492491
return wsgi_request_event_processor
493492

494493

494+
@ensure_integration_enabled(DjangoIntegration)
495495
def _got_request_exception(request=None, **kwargs):
496496
# type: (WSGIRequest, **Any) -> None
497497
client = sentry_sdk.get_client()
498498
integration = client.get_integration(DjangoIntegration)
499-
if integration is not None:
500-
if request is not None and integration.transaction_style == "url":
501-
scope = Scope.get_current_scope()
502-
_attempt_resolve_again(request, scope, integration.transaction_style)
503-
504-
event, hint = event_from_exception(
505-
sys.exc_info(),
506-
client_options=client.options,
507-
mechanism={"type": "django", "handled": False},
508-
)
509-
sentry_sdk.capture_event(event, hint=hint)
499+
500+
if request is not None and integration.transaction_style == "url":
501+
scope = Scope.get_current_scope()
502+
_attempt_resolve_again(request, scope, integration.transaction_style)
503+
504+
event, hint = event_from_exception(
505+
sys.exc_info(),
506+
client_options=client.options,
507+
mechanism={"type": "django", "handled": False},
508+
)
509+
sentry_sdk.capture_event(event, hint=hint)
510510

511511

512512
class DjangoRequestExtractor(RequestExtractor):

sentry_sdk/integrations/django/templates.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,9 @@ def patch_templates():
6565
real_rendered_content = SimpleTemplateResponse.rendered_content
6666

6767
@property # type: ignore
68+
@ensure_integration_enabled(DjangoIntegration, real_rendered_content.fget)
6869
def rendered_content(self):
6970
# type: (SimpleTemplateResponse) -> str
70-
if sentry_sdk.get_client().get_integration(DjangoIntegration) is None:
71-
return real_rendered_content.fget(self)
72-
7371
with sentry_sdk.start_span(
7472
op=OP.TEMPLATE_RENDER,
7573
description=_get_template_name_description(self.template_name),

sentry_sdk/integrations/excepthook.py

+7-2
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
import sys
22

33
import sentry_sdk
4-
from sentry_sdk.utils import capture_internal_exceptions, event_from_exception
4+
from sentry_sdk.utils import (
5+
capture_internal_exceptions,
6+
ensure_integration_enabled,
7+
event_from_exception,
8+
)
59
from sentry_sdk.integrations import Integration
610

711
from sentry_sdk._types import TYPE_CHECKING
@@ -43,11 +47,12 @@ def setup_once():
4347

4448
def _make_excepthook(old_excepthook):
4549
# type: (Excepthook) -> Excepthook
50+
@ensure_integration_enabled(ExcepthookIntegration, old_excepthook)
4651
def sentry_sdk_excepthook(type_, value, traceback):
4752
# type: (Type[BaseException], BaseException, Optional[TracebackType]) -> None
4853
integration = sentry_sdk.get_client().get_integration(ExcepthookIntegration)
4954

50-
if integration is not None and _should_send(integration.always_run):
55+
if _should_send(integration.always_run):
5156
with capture_internal_exceptions():
5257
event, hint = event_from_exception(
5358
(type_, value, traceback),

sentry_sdk/integrations/falcon.py

+4-6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
from sentry_sdk.tracing import SOURCE_FOR_STYLE
77
from sentry_sdk.utils import (
88
capture_internal_exceptions,
9+
ensure_integration_enabled,
910
event_from_exception,
1011
parse_version,
1112
)
@@ -167,6 +168,7 @@ def _patch_handle_exception():
167168
# type: () -> None
168169
original_handle_exception = falcon_app_class._handle_exception
169170

171+
@ensure_integration_enabled(FalconIntegration, original_handle_exception)
170172
def sentry_patched_handle_exception(self, *args):
171173
# type: (falcon.API, *Any) -> Any
172174
# NOTE(jmagnusson): falcon 2.0 changed falcon.API._handle_exception
@@ -187,14 +189,10 @@ def sentry_patched_handle_exception(self, *args):
187189
# capture_internal_exceptions block above.
188190
return was_handled
189191

190-
client = sentry_sdk.get_client()
191-
integration = client.get_integration(FalconIntegration)
192-
193-
if integration is not None and _exception_leads_to_http_5xx(ex, response):
194-
# If an integration is there, a client has to be there.
192+
if _exception_leads_to_http_5xx(ex, response):
195193
event, hint = event_from_exception(
196194
ex,
197-
client_options=client.options,
195+
client_options=sentry_sdk.get_client().options,
198196
mechanism={"type": "falcon", "handled": False},
199197
)
200198
sentry_sdk.capture_event(event, hint=hint)

sentry_sdk/integrations/flask.py

+6-9
Original file line numberDiff line numberDiff line change
@@ -76,9 +76,11 @@ def setup_once():
7676

7777
old_app = Flask.__call__
7878

79-
@ensure_integration_enabled(FlaskIntegration, old_app)
8079
def sentry_patched_wsgi_app(self, environ, start_response):
8180
# type: (Any, Dict[str, str], Callable[..., Any]) -> _ScopedResponse
81+
if sentry_sdk.get_client().get_integration(FlaskIntegration) is None:
82+
return old_app(self, environ, start_response)
83+
8284
return SentryWsgiMiddleware(lambda *a, **kw: old_app(self, *a, **kw))(
8385
environ, start_response
8486
)
@@ -112,12 +114,10 @@ def _set_transaction_name_and_source(scope, transaction_style, request):
112114
pass
113115

114116

117+
@ensure_integration_enabled(FlaskIntegration)
115118
def _request_started(app, **kwargs):
116119
# type: (Flask, **Any) -> None
117120
integration = sentry_sdk.get_client().get_integration(FlaskIntegration)
118-
if integration is None:
119-
return
120-
121121
request = flask_request._get_current_object()
122122

123123
# Set the transaction name and source here,
@@ -192,15 +192,12 @@ def inner(event, hint):
192192
return inner
193193

194194

195+
@ensure_integration_enabled(FlaskIntegration)
195196
def _capture_exception(sender, exception, **kwargs):
196197
# type: (Flask, Union[ValueError, BaseException], **Any) -> None
197-
client = sentry_sdk.get_client()
198-
if client.get_integration(FlaskIntegration) is None:
199-
return
200-
201198
event, hint = event_from_exception(
202199
exception,
203-
client_options=client.options,
200+
client_options=sentry_sdk.get_client().options,
204201
mechanism={"type": "flask", "handled": False},
205202
)
206203

sentry_sdk/integrations/gcp.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
from sentry_sdk.utils import (
1414
AnnotatedValue,
1515
capture_internal_exceptions,
16+
ensure_integration_enabled,
1617
event_from_exception,
1718
logger,
1819
TimeoutThread,
@@ -38,13 +39,12 @@
3839

3940
def _wrap_func(func):
4041
# type: (F) -> F
42+
@ensure_integration_enabled(GcpIntegration, func)
4143
def sentry_func(functionhandler, gcp_event, *args, **kwargs):
4244
# type: (Any, Any, *Any, **Any) -> Any
4345
client = sentry_sdk.get_client()
4446

4547
integration = client.get_integration(GcpIntegration)
46-
if integration is None:
47-
return func(functionhandler, gcp_event, *args, **kwargs)
4848

4949
configured_time = environ.get("FUNCTION_TIMEOUT_SEC")
5050
if not configured_time:

0 commit comments

Comments
 (0)