Coverage for polar/sentry.py: 88%

22 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2025-12-05 16:17 +0000

1import os 1a

2 

3import sentry_sdk 1a

4from dramatiq import get_broker 1a

5from sentry_sdk.integrations.dramatiq import DramatiqIntegration as _DramatiqIntegration 1a

6from sentry_sdk.integrations.dramatiq import SentryMiddleware 1a

7from sentry_sdk.integrations.fastapi import FastApiIntegration 1a

8 

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

10from polar.config import settings 1a

11 

12POSTHOG_ID_TAG = "posthog_distinct_id" 1a

13 

14 

15class DramatiqIntegration(_DramatiqIntegration): 1a

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 1a

24 def setup_once() -> None: 1a

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: 1a

31 sentry_sdk.init( 1a

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: 1a

46 if is_user(auth_subject): 1bc

47 user = auth_subject.subject 1b

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

49 sentry_sdk.set_tag(POSTHOG_ID_TAG, user.posthog_distinct_id) 1b