2024-05-23 11:32:45 +02:00
|
|
|
import requests
|
2024-09-02 16:28:55 +02:00
|
|
|
import newrelic.agent
|
2024-05-23 11:32:45 +02:00
|
|
|
|
2024-05-23 10:27:08 +02:00
|
|
|
from abc import ABC, abstractmethod
|
2024-05-23 11:32:45 +02:00
|
|
|
from app.config import EVENT_WEBHOOK, EVENT_WEBHOOK_SKIP_VERIFY_SSL
|
2024-05-23 10:27:08 +02:00
|
|
|
from app.log import LOG
|
|
|
|
from app.models import SyncEvent
|
|
|
|
|
|
|
|
|
|
|
|
class EventSink(ABC):
|
|
|
|
@abstractmethod
|
2024-05-23 15:05:47 +02:00
|
|
|
def process(self, event: SyncEvent) -> bool:
|
2024-05-23 10:27:08 +02:00
|
|
|
pass
|
|
|
|
|
2024-10-23 17:01:32 +02:00
|
|
|
@abstractmethod
|
|
|
|
def send_data_to_webhook(self, data: bytes) -> bool:
|
|
|
|
pass
|
|
|
|
|
2024-05-23 10:27:08 +02:00
|
|
|
|
|
|
|
class HttpEventSink(EventSink):
|
2024-05-23 15:05:47 +02:00
|
|
|
def process(self, event: SyncEvent) -> bool:
|
2024-05-23 11:32:45 +02:00
|
|
|
if not EVENT_WEBHOOK:
|
|
|
|
LOG.warning("Skipping sending event because there is no webhook configured")
|
2024-05-23 15:05:47 +02:00
|
|
|
return False
|
|
|
|
|
2024-05-23 11:32:45 +02:00
|
|
|
LOG.info(f"Sending event {event.id} to {EVENT_WEBHOOK}")
|
|
|
|
|
2024-10-23 17:01:32 +02:00
|
|
|
if self.send_data_to_webhook(event.content):
|
|
|
|
LOG.info(f"Event {event.id} sent successfully to webhook")
|
|
|
|
return True
|
|
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
def send_data_to_webhook(self, data: bytes) -> bool:
|
2024-05-23 11:32:45 +02:00
|
|
|
res = requests.post(
|
|
|
|
url=EVENT_WEBHOOK,
|
2024-10-23 17:01:32 +02:00
|
|
|
data=data,
|
2024-05-23 11:32:45 +02:00
|
|
|
headers={"Content-Type": "application/x-protobuf"},
|
|
|
|
verify=not EVENT_WEBHOOK_SKIP_VERIFY_SSL,
|
|
|
|
)
|
2024-09-19 16:20:56 +02:00
|
|
|
newrelic.agent.record_custom_event(
|
|
|
|
"EventSentToPartner", {"http_code": res.status_code}
|
|
|
|
)
|
2024-05-23 11:32:45 +02:00
|
|
|
if res.status_code != 200:
|
|
|
|
LOG.warning(
|
|
|
|
f"Failed to send event to webhook: {res.status_code} {res.text}"
|
|
|
|
)
|
2024-05-23 15:05:47 +02:00
|
|
|
return False
|
2024-05-23 11:32:45 +02:00
|
|
|
else:
|
2024-05-23 15:05:47 +02:00
|
|
|
return True
|
2024-05-23 10:27:08 +02:00
|
|
|
|
|
|
|
|
|
|
|
class ConsoleEventSink(EventSink):
|
2024-05-23 15:05:47 +02:00
|
|
|
def process(self, event: SyncEvent) -> bool:
|
2024-05-23 10:27:08 +02:00
|
|
|
LOG.info(f"Handling event {event.id}")
|
2024-05-23 15:05:47 +02:00
|
|
|
return True
|
2024-10-23 17:01:32 +02:00
|
|
|
|
|
|
|
def send_data_to_webhook(self, data: bytes) -> bool:
|
|
|
|
LOG.info(f"Sending {len(data)} bytes to webhook")
|
|
|
|
return True
|