diff --git a/docs/introduction/configuration.md b/docs/introduction/configuration.md index 9be8f18..6a4797c 100644 --- a/docs/introduction/configuration.md +++ b/docs/introduction/configuration.md @@ -49,6 +49,17 @@ Before 2.0, Sentry was the second most expensive instrument in the stack, and it entirely from sentry-sdk's framework integration. Since 2.0, lite-bootstrap replaces that integration on Litestar, FastAPI and FastMCP while Sentry tracing is off; see [Performance](performance.md). +### Sentry shutdown + +Teardown closes the client initialized by the instrument with a two-second flush +timeout. A replacement global client stays untouched. If closing raises, teardown +still clears the owned global binding and propagates the error. + +With the SDK's optional `AsyncHttpTransport`, save the initialized client and await +`client.close_async(timeout=2)` before lite-bootstrap's teardown runs. Synchronous +teardown cannot await the async transport's flush and connection-pool cleanup. Use +the default synchronous transport for shutdown managed entirely by lite-bootstrap. + ### Sentry logging integration lite-bootstrap supports sentry-sdk 2.70 and later 2.x releases. sentry-sdk 3.0 is not supported diff --git a/lite_bootstrap/instruments/sentry_instrument.py b/lite_bootstrap/instruments/sentry_instrument.py index 2d32891..d22dd6b 100644 --- a/lite_bootstrap/instruments/sentry_instrument.py +++ b/lite_bootstrap/instruments/sentry_instrument.py @@ -264,6 +264,9 @@ def run_before_breadcrumb( class SentryInstrument(BaseInstrument[SentryConfigT]): not_configured_reason = "sentry_dsn is empty" missing_dependency_message = "sentry_sdk is not installed" + _client: "sentry_sdk.client.BaseClient | None" = dataclasses.field( + default=None, init=False, repr=False, compare=False + ) @classmethod def is_configured(cls, bootstrap_config: "SentryConfig") -> bool: @@ -316,17 +319,18 @@ def _build_init_params(self) -> dict[str, typing.Any]: def bootstrap(self) -> None: sentry_sdk.init(**self._build_init_params()) + self._client = sentry_sdk.get_global_scope().client tags: dict[str, str] = self.bootstrap_config.sentry_tags or {} sentry_sdk.set_tags(tags) def teardown(self) -> None: - """Flush pending events and reset the SDK to a no-op state. - - Clear the global client to disable capture even when SENTRY_DSN is set. This - cleans up after a bootstrap so the same process can be torn down and re-tested - without leaking the previous DSN/transport into subsequent code. - """ + """Close the owned client and disable its global capture.""" + if self._client is None: + return + client, self._client = self._client, None try: - sentry_sdk.flush(timeout=2) + client.close(timeout=2) finally: - sentry_sdk.get_global_scope().set_client(None) + scope = sentry_sdk.get_global_scope() + if scope.client is client: + scope.set_client(None) diff --git a/tests/instruments/test_sentry_instrument.py b/tests/instruments/test_sentry_instrument.py index fb4ec87..56fe7fd 100644 --- a/tests/instruments/test_sentry_instrument.py +++ b/tests/instruments/test_sentry_instrument.py @@ -12,6 +12,7 @@ import structlog from sentry_sdk.envelope import Envelope from sentry_sdk.integrations.logging import LoggingIntegration +from sentry_sdk.transport import AsyncHttpTransport from lite_bootstrap.instruments.logging_instrument import LoggingConfig, LoggingInstrument, SentryJSONRenderer from lite_bootstrap.instruments.sentry_instrument import enrich_sentry_event_from_structlog_log @@ -94,6 +95,73 @@ def test_sentry_instrument_empty_dsn() -> None: SentryInstrument(bootstrap_config=SentryConfig(sentry_dsn="")).bootstrap() +def test_sentry_teardown_closes_owned_client( + minimal_sentry_config: SentryConfig, sentry_mock: SentryTestTransport +) -> None: + instrument = SentryInstrument(bootstrap_config=minimal_sentry_config) + instrument.bootstrap() + client = sentry_sdk.get_client() + try: + with ( + patch.object(sentry_mock, "flush", wraps=sentry_mock.flush) as flush, + patch.object(sentry_mock, "kill", wraps=sentry_mock.kill) as kill, + ): + instrument.teardown() + expected_timeout = 2 + assert flush.call_args.kwargs["timeout"] == expected_timeout + kill.assert_called_once() + assert client.transport is None + finally: + client.close() + + +@pytest.mark.parametrize("cleanup_raises", [False, True]) +def test_sentry_teardown_preserves_replacement_client( + minimal_sentry_config: SentryConfig, sentry_mock: SentryTestTransport, *, cleanup_raises: bool +) -> None: + instrument = SentryInstrument(bootstrap_config=minimal_sentry_config) + instrument.bootstrap() + owned = sentry_sdk.get_client() + replacement_transport = SentryTestTransport() + sentry_sdk.init(dsn=minimal_sentry_config.sentry_dsn, transport=replacement_transport) + replacement = sentry_sdk.get_client() + try: + with patch.object( + owned, "close", wraps=owned.close, side_effect=RuntimeError("close boom") if cleanup_raises else None + ): + if cleanup_raises: + with pytest.raises(RuntimeError, match="close boom"): + instrument.teardown() + else: + instrument.teardown() + assert owned.transport is None + instrument.teardown() + assert sentry_sdk.get_global_scope().client is replacement + assert replacement.transport is replacement_transport + sentry_sdk.capture_message("replacement still works") + assert replacement_transport.mock_envelopes + assert not sentry_mock.mock_envelopes + finally: + owned.close() + replacement.close() + sentry_sdk.get_global_scope().set_client(None) + + +async def test_sentry_async_transport_can_be_closed_before_teardown(minimal_sentry_config: SentryConfig) -> None: + config = dataclasses.replace(minimal_sentry_config, sentry_additional_params={"transport": AsyncHttpTransport}) + instrument = SentryInstrument(bootstrap_config=config) + instrument.bootstrap() + client = sentry_sdk.get_client() + try: + assert isinstance(client.transport, AsyncHttpTransport) + await client.close_async(timeout=2) + instrument.teardown() + assert client.transport is None + assert not sentry_sdk.get_client().is_active() + finally: + await client.close_async(timeout=2) + + class TestSentryEnrichEventFromStructlog: """enrich_* owns the Sentry-event-shape guards and the orchestration branches. @@ -146,23 +214,31 @@ def test_modify_lifts_message_and_attaches_extra( assert enrich_sentry_event_from_structlog_log(event_before, {}) == event_after -def test_sentry_teardown_disables_sdk_when_flush_raises( - minimal_sentry_config: SentryConfig, sentry_mock: SentryTestTransport, monkeypatch: pytest.MonkeyPatch +@pytest.mark.parametrize("operation", ["flush", "kill"]) +def test_sentry_teardown_disables_sdk_when_cleanup_raises( + minimal_sentry_config: SentryConfig, + sentry_mock: SentryTestTransport, + monkeypatch: pytest.MonkeyPatch, + operation: str, ) -> None: monkeypatch.setenv("SENTRY_DSN", "https://synthetic@example.invalid/1") monkeypatch.setattr("sentry_sdk.client.make_transport", lambda options: sentry_mock if options["dsn"] else None) instrument = SentryInstrument(bootstrap_config=minimal_sentry_config) instrument.bootstrap() + client = sentry_sdk.get_client() - with ( - patch("sentry_sdk.flush", side_effect=RuntimeError("flush boom")), - pytest.raises(RuntimeError, match="flush boom"), - ): - instrument.teardown() - - assert not sentry_sdk.get_client().is_active() - assert sentry_sdk.capture_message("after teardown") is None - assert sentry_mock.mock_envelopes == [] + try: + with ( + patch.object(sentry_mock, operation, side_effect=RuntimeError("cleanup boom")), + pytest.raises(RuntimeError, match="cleanup boom"), + ): + instrument.teardown() + + assert not sentry_sdk.get_client().is_active() + assert sentry_sdk.capture_message("after teardown") is None + assert sentry_mock.mock_envelopes == [] + finally: + client.close() def installed_logging_integration() -> LoggingIntegration: