Skip to content

Commit 59c3191

Browse files
committed
Version without timer thread
1 parent 8aad6ae commit 59c3191

File tree

3 files changed

+14
-97
lines changed

3 files changed

+14
-97
lines changed

sentry_sdk/integrations/wsgi.py

Lines changed: 4 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import sys
2-
from contextlib import nullcontext
32
from functools import partial
4-
from threading import Timer
53

64
import sentry_sdk
75
from sentry_sdk._werkzeug import get_host, _get_headers
@@ -132,7 +130,6 @@ def __call__(self, environ, start_response):
132130
transaction = None
133131

134132
with sentry_sdk.continue_trace(environ):
135-
timer = None
136133
if should_trace:
137134
transaction = sentry_sdk.start_span(
138135
op=OP.HTTP_SERVER,
@@ -146,18 +143,6 @@ def __call__(self, environ, start_response):
146143
transaction.__enter__()
147144
current_scope = transaction.scope
148145

149-
timer = Timer(
150-
MAX_TRANSACTION_DURATION_SECONDS,
151-
finish_running_transaction,
152-
kwargs={
153-
"transaction": transaction,
154-
"current_scope": current_scope,
155-
"isolation_scope": scope,
156-
"debug": "from timer!",
157-
},
158-
)
159-
timer.start()
160-
161146
try:
162147
response = self.app(
163148
environ,
@@ -170,7 +155,7 @@ def __call__(self, environ, start_response):
170155
except BaseException:
171156
exc_info = sys.exc_info()
172157
_capture_exception(exc_info)
173-
finish_running_transaction(transaction, exc_info, timer, debug="from except block")
158+
finish_running_transaction(transaction, exc_info)
174159
reraise(*exc_info)
175160

176161
finally:
@@ -180,7 +165,6 @@ def __call__(self, environ, start_response):
180165
response=response,
181166
current_scope=current_scope,
182167
isolation_scope=scope,
183-
timer=timer,
184168
transaction=transaction,
185169
)
186170

@@ -277,21 +261,19 @@ class _ScopedResponse:
277261
- WSGI servers streaming responses interleaved from the same thread
278262
"""
279263

280-
__slots__ = ("_response", "_current_scope", "_isolation_scope", "_timer", "_transaction")
264+
__slots__ = ("_response", "_current_scope", "_isolation_scope", "_transaction")
281265

282266
def __init__(
283267
self,
284268
response, # type: Iterator[bytes]
285269
current_scope, # type: sentry_sdk.scope.Scope
286270
isolation_scope, # type: sentry_sdk.scope.Scope
287-
timer=None, # type: Optional[Timer]
288271
transaction=None, # type: Optional[Transaction]
289272
):
290273
# type: (...) -> None
291274
self._response = response
292275
self._current_scope = current_scope
293276
self._isolation_scope = isolation_scope
294-
self._timer = timer
295277
self._transaction = transaction
296278

297279
def __iter__(self):
@@ -314,14 +296,14 @@ def __iter__(self):
314296
finally:
315297
with sentry_sdk.use_isolation_scope(self._isolation_scope):
316298
with sentry_sdk.use_scope(self._current_scope):
317-
finish_running_transaction(transaction=self._transaction, timer=self._timer, debug="from finally in iterator")
299+
finish_running_transaction(transaction=self._transaction)
318300

319301
def close(self):
320302
# type: () -> None
321303
with sentry_sdk.use_isolation_scope(self._isolation_scope):
322304
with sentry_sdk.use_scope(self._current_scope):
323305
try:
324-
finish_running_transaction(transaction=self._transaction, timer=self._timer, debug="from close()")
306+
finish_running_transaction(transaction=self._transaction)
325307
self._response.close() # type: ignore
326308
except AttributeError:
327309
pass

sentry_sdk/tracing_utils.py

Lines changed: 6 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -739,39 +739,10 @@ def get_current_span(scope=None):
739739
from sentry_sdk.tracing import Span
740740

741741

742-
def finish_running_transaction(transaction=None, exc_info=None, timer=None, current_scope=None, isolation_scope=None, debug=None):
743-
# type: (Optional[sentry_sdk.Transaction], Optional[ExcInfo], Optional[Timer]) -> None
744-
print(f"----")
745-
print(f"\nCALLED finish_running_transaction {id(transaction)} / {transaction} / {exc_info} / {timer} / {current_scope} / {isolation_scope} / debug: {debug}")
746-
import traceback
747-
traceback.print_stack()
748-
# print(f"{id(transaction)} / {sentry_sdk.get_current_scope().transaction}")
749-
print(f"hasattr _ctx_token: {hasattr(transaction, '_ctx_token')}")
750-
# print(f"_ctx_token: {transaction._ctx_token}")
751-
752-
if timer is not None:
753-
timer.cancel()
754-
742+
def finish_running_transaction(transaction=None, exc_info=None):
743+
# type: (Optional[sentry_sdk.Transaction], Optional[ExcInfo]) -> None
755744
if transaction is not None and hasattr(transaction, "_ctx_token"):
756-
with (
757-
sentry_sdk.use_isolation_scope(isolation_scope)
758-
if isolation_scope is not None
759-
else contextlib.nullcontext()
760-
) as scope1:
761-
with (
762-
sentry_sdk.use_scope(current_scope)
763-
if current_scope is not None
764-
else contextlib.nullcontext()
765-
) as scope2:
766-
if exc_info is not None:
767-
transaction.__exit__(*exc_info)
768-
else:
769-
transaction.__exit__(None, None, None)
770-
771-
print(f"End of current scope: {scope2}")
772-
773-
print(f"End of isolation scope: {scope1}")
774-
else:
775-
print(f"Transaction has no _ctx_token")
776-
777-
print("done finish_running_transaction")
745+
if exc_info is not None:
746+
transaction.__exit__(*exc_info)
747+
else:
748+
transaction.__exit__(None, None, None)

tests/integrations/wsgi/test_wsgi.py

Lines changed: 4 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -497,7 +497,7 @@ def dogpark(environ, start_response):
497497

498498
def test_long_running_transaction_finished(sentry_init, capture_events):
499499
"""
500-
Test that a long running transaction is finished after the maximum duration,
500+
Test that a long running transaction is finished after the maximum duration,
501501
no matter if the response is still being generated.
502502
"""
503503
# we allow transactions to be 0.5 seconds as a maximum
@@ -535,42 +535,6 @@ def long_running_app(environ, start_response):
535535
- datetime.fromisoformat(transaction["start_timestamp"])
536536
).total_seconds()
537537
assert (
538-
transaction_duration <= new_max_duration * 1.02
539-
) # we allow 2% margin for processing the request
540-
541-
542-
def test_long_running_transaction_timer_canceled(sentry_init, capture_events):
543-
"""
544-
Test that the timer is canceled when the transaction is finished before the maximum duration.
545-
"""
546-
# we allow transactions to be 0.5 seconds as a maximum
547-
new_max_duration = 0.5
548-
549-
with mock.patch.object(
550-
sentry_sdk.integrations.wsgi,
551-
"MAX_TRANSACTION_DURATION_SECONDS",
552-
new_max_duration,
553-
):
554-
with mock.patch(
555-
"sentry_sdk.integrations.wsgi.finish_running_transaction"
556-
) as mock_finish:
557-
558-
def generate_content():
559-
# This response will take 0.3 seconds to generate
560-
for _ in range(3):
561-
time.sleep(0.1)
562-
yield "ok"
563-
564-
def long_running_app(environ, start_response):
565-
start_response("200 OK", [])
566-
return generate_content()
567-
568-
sentry_init(send_default_pii=True, traces_sample_rate=1.0)
569-
app = SentryWsgiMiddleware(long_running_app)
570-
571-
client = Client(app)
572-
response = client.get("/")
573-
_ = response.get_data()
574-
575-
first_call = mock_finish.mock_calls[0].kwargs
576-
assert first_call["timer"] is not None # if a timer is given, it will be cancelled
538+
transaction_duration
539+
<= new_max_duration * 1.02 # we allow 2% margin for processing the request
540+
), "Long running transaction has not been finished after a set maximum duration"

0 commit comments

Comments
 (0)