1- import json
2- import logging
31from typing import Any , Dict , Optional , Type
42
5- from django .conf import settings
63from django .db .models .signals import post_save
74from django .dispatch import receiver
8- from google .cloud import pubsub_v1
95
106from codecov_auth .models import OrganizationLevelToken , Owner , OwnerProfile
11-
12- log = logging .getLogger (__name__ )
7+ from utils .shelter import ShelterPubsub
138
149
1510@receiver (post_save , sender = Owner )
@@ -20,42 +15,6 @@ def create_owner_profile_when_owner_is_created(
2015 return OwnerProfile .objects .create (owner_id = instance .ownerid )
2116
2217
23- class ShelterPubsub :
24- pubsub_publisher = None
25- _instance = None
26-
27- @classmethod
28- def get_instance (cls ) -> "ShelterPubsub" :
29- """
30- This class needs the Django settings to be fully loaded before it can be instantiated,
31- therefore use this method to get an instance rather than instantiating directly.
32- """
33- if cls ._instance is None :
34- cls ._instance = cls ()
35- return cls ._instance
36-
37- def __init__ (self ) -> None :
38- if not self .pubsub_publisher :
39- self .pubsub_publisher = pubsub_v1 .PublisherClient ()
40- pubsub_project_id : str = settings .SHELTER_PUBSUB_PROJECT_ID
41-
42- # topic_id has REPO in the name but it is used for all types of objects
43- topic_id : str = settings .SHELTER_PUBSUB_SYNC_REPO_TOPIC_ID
44- self .topic_path = self .pubsub_publisher .topic_path (pubsub_project_id , topic_id )
45-
46- def publish (self , data : Dict [str , Any ]) -> None :
47- try :
48- self .pubsub_publisher .publish (
49- self .topic_path ,
50- json .dumps (data ).encode ("utf-8" ),
51- )
52- except Exception as e :
53- log .warning (
54- "Failed to publish a message" ,
55- extra = dict (data_to_publish = data , error = e ),
56- )
57-
58-
5918@receiver (
6019 post_save , sender = OrganizationLevelToken , dispatch_uid = "shelter_sync_org_token"
6120)
0 commit comments