Skip to content

Commit 0c82ddb

Browse files
committed
Keep transaction open until all streaming responses are finished.
1 parent 17df886 commit 0c82ddb

File tree

1 file changed

+23
-14
lines changed

1 file changed

+23
-14
lines changed

sentry_sdk/integrations/wsgi.py

Lines changed: 23 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -119,30 +119,30 @@ def __call__(self, environ, start_response):
119119
origin=self.span_origin,
120120
)
121121

122-
with (
123-
sentry_sdk.start_transaction(
122+
if transaction is not None:
123+
transaction = sentry_sdk.start_transaction(
124124
transaction,
125125
custom_sampling_context={"wsgi_environ": environ},
126126
)
127-
if transaction is not None
128-
else nullcontext()
129-
):
130-
try:
131-
response = self.app(
132-
environ,
133-
partial(
134-
_sentry_start_response, start_response, transaction
135-
),
136-
)
137-
except BaseException:
138-
reraise(*_capture_exception())
127+
transaction.__enter__()
128+
129+
try:
130+
response = self.app(
131+
environ,
132+
partial(
133+
_sentry_start_response, start_response, transaction
134+
),
135+
)
136+
except BaseException:
137+
reraise(*_capture_exception())
139138
finally:
140139
_wsgi_middleware_applied.set(False)
141140

142141
return _ScopedResponse(
143142
response=response,
144143
current_scope=current_scope,
145144
isolation_scope=scope,
145+
transaction=transaction,
146146
)
147147

148148

@@ -245,11 +245,13 @@ def __init__(
245245
response, # type: Iterator[bytes]
246246
current_scope, # type: sentry_sdk.scope.Scope
247247
isolation_scope, # type: sentry_sdk.scope.Scope
248+
transaction, # type: Optional[sentry_sdk.tracing.Transaction]
248249
):
249250
# type: (...) -> None
250251
self._response = response
251252
self._current_scope = current_scope
252253
self._isolation_scope = isolation_scope
254+
self._transaction = transaction
253255

254256
def __iter__(self):
255257
# type: () -> Iterator[bytes]
@@ -273,6 +275,13 @@ def close(self):
273275
with use_scope(self._current_scope):
274276
try:
275277
self._response.close() # type: ignore
278+
279+
# Close the Sentry transaction
280+
# This is done here to make sure the Transaction stays
281+
# open until all streaming responses are done.
282+
# Of course this here works also for non streaming responses.
283+
if self._transaction is not None:
284+
self._transaction.__exit__(None, None, None)
276285
except AttributeError:
277286
pass
278287
except BaseException:

0 commit comments

Comments
 (0)