-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkafka_config.py
More file actions
82 lines (70 loc) · 2.99 KB
/
Copy pathkafka_config.py
File metadata and controls
82 lines (70 loc) · 2.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from kafka import KafkaConsumer
from utils import SETTINGS, send_email
from datetime import datetime
import json
import time
def make_consumer(topic, bootstrap_servers, group_id="mail_service-group"):
"""Create and return a Kafka consumer with exponential backoff on connection failure."""
backoff = 1
while True:
try:
c = KafkaConsumer(
topic,
bootstrap_servers=bootstrap_servers,
auto_offset_reset="earliest",
enable_auto_commit=True,
group_id=group_id,
)
print("Connected to Kafka")
return c
except Exception as e:
print(f"Kafka connection failed: {e}. retrying in {backoff}s")
time.sleep(backoff)
backoff = min(backoff * 2, 30)
def consume_messages():
"""Consume messages from a specified Kafka topic."""
if not SETTINGS.USE_KAFKA:
print(
"Kafka integration is disabled. Setting USE_KAFKA to True to enable it and restart the service."
)
return
print("Waiting for the producer to start...")
consumer = make_consumer(
topic=SETTINGS.KAFKA_CONSUMER_TOPIC,
bootstrap_servers=SETTINGS.KAFKA_BOOTSTRAP_SERVERS.split(","),
)
print("Consumer is ready and listening for messages...")
try:
while True:
for message in consumer:
ts = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S UTC")
key = message.key.decode("utf-8") if message.key else "None"
data = message.value.decode("utf-8")
if key == "email_topic":
# Get email details from the message
email_data = json.loads(data)
receiver_email = email_data.get("receiver_email")
email_object = email_data.get("email_object")
message_text = email_data.get("message_text")
if not all([receiver_email, email_object, message_text]):
print(f"[{ts}] Incomplete email data received: {email_data}")
print("The correct format is:")
print(
'{"receiver_email": "email@example.com", "email_object": "Subject", "message_text": "Body"} or {"receiver_email": ["email@example.com"], "email_object": "Subject", "message_text": "Body"}'
)
print("Skipping this message.")
continue
print(
f"[{ts}] Sending email to {receiver_email} with subject '{email_object}'"
)
# Send the email
send_email(
receiver_email=receiver_email,
message_text=message_text,
email_object=email_object,
)
except KeyboardInterrupt:
pass
finally:
consumer.close()
time.sleep(3)