Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions docs/introduction/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
20 changes: 12 additions & 8 deletions lite_bootstrap/instruments/sentry_instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
98 changes: 87 additions & 11 deletions tests/instruments/test_sentry_instrument.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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:
Expand Down
Loading