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