Skip to content

Commit

Permalink
ee
Browse files Browse the repository at this point in the history
  • Loading branch information
marcoacierno committed Nov 24, 2024
1 parent 1c3bfc7 commit 4b5170e
Showing 1 changed file with 31 additions and 31 deletions.
62 changes: 31 additions & 31 deletions backend/notifications/tasks.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.db import transaction

from celery.exceptions import MaxRetriesExceededError
import logging
from uuid import uuid4
from notifications.models import SentEmail
Expand All @@ -11,53 +10,54 @@
logger = logging.getLogger(__name__)


def send_pending_email_failed(self, task_id, args, kwargs, einfo):
sent_email_id = args[0]

sent_email = SentEmail.objects.get(id=sent_email_id)
sent_email.mark_as_failed()
logger.error(
"Failed to send email sent_email_id=%s",
sent_email.id,
)


@app.task(
bind=True,
autoretry_for=(Exception,),
retry_backoff=5,
max_retries=5,
default_retry_delay=2,
on_failure=send_pending_email_failed,
)
@transaction.atomic()
def send_pending_email(self, sent_email_id: int):
logger.info(
"Sending sent_email=%s (retry=%s of %s)",
"Sending sent_email=%s (attempt=%s of %s)",
sent_email_id,
self.request.retries,
self.max_retries,
)

try:
with transaction.atomic():
sent_email = (
SentEmail.objects.select_for_update(skip_locked=True)
.pending()
.filter(id=sent_email_id)
.first()
)
sent_email = (
SentEmail.objects.select_for_update(skip_locked=True)
.pending()
.filter(id=sent_email_id)
.first()
)

if not sent_email:
return
if not sent_email:
return

email_backend_connection = get_connection()
email_backend_connection = get_connection()

message_id = send_email(sent_email, email_backend_connection)
sent_email.mark_as_sent(message_id)
message_id = send_email(sent_email, email_backend_connection)
sent_email.mark_as_sent(message_id)

logger.info(
"Email sent_email_id=%s sent with message_id=%s",
sent_email.id,
message_id,
)
except Exception as e:
try:
raise self.retry(exc=e)
except MaxRetriesExceededError:
sent_email = SentEmail.objects.get(id=sent_email_id)
sent_email.mark_as_failed()
logger.error(
"Failed to send email sent_email_id=%s",
sent_email.id,
)
return
logger.info(
"Email sent_email_id=%s sent with message_id=%s",
sent_email.id,
message_id,
)


def send_email(sent_email, email_backend_connection):
Expand Down

0 comments on commit 4b5170e

Please sign in to comment.