Coverage for polar/sentry.py: 88%

22 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-07 12:42 +0000

1import os 

2 

3import sentry_sdk 

4from dramatiq import get_broker 

5from sentry_sdk.integrations.dramatiq import DramatiqIntegration as _DramatiqIntegration 

6from sentry_sdk.integrations.dramatiq import SentryMiddleware 

7from sentry_sdk.integrations.fastapi import FastApiIntegration 

8 

9from polar.auth.models import AuthSubject, Subject, is_user 

10from polar.config import settings 

11 

12POSTHOG_ID_TAG = "posthog_distinct_id" 

13 

14 

15class DramatiqIntegration(_DramatiqIntegration): 

16 """ 

17 Custom Dramatiq integration to set up Sentry middleware. 

18 

19 The built-in one expects us to init Sentry before our broker, which is not 

20 practical in our case. 

21 """ 

22 

23 @staticmethod 

24 def setup_once() -> None: 

25 broker = get_broker() 

26 first_middleware = type(broker.middleware[0]) 

27 broker.add_middleware(SentryMiddleware(), before=first_middleware) 

28 

29 

30def configure_sentry() -> None: 

31 sentry_sdk.init( 

32 dsn=settings.SENTRY_DSN, 

33 traces_sample_rate=0, 

34 profiles_sample_rate=0, 

35 release=os.environ.get("RELEASE_VERSION", "development"), 

36 server_name=os.environ.get("RENDER_INSTANCE_ID", "localhost"), 

37 environment=settings.ENV, 

38 integrations=[ 

39 FastApiIntegration(transaction_style="endpoint"), 

40 # DramatiqIntegration(), 

41 ], 

42 ) 

43 

44 

45def set_sentry_user(auth_subject: AuthSubject[Subject]) -> None: 

46 if is_user(auth_subject): 

47 user = auth_subject.subject 

48 sentry_sdk.set_user({"id": str(user.id), "email": user.email}) 

49 sentry_sdk.set_tag(POSTHOG_ID_TAG, user.posthog_distinct_id)