118 lines
3.6 KiB
Python
118 lines
3.6 KiB
Python
import logging
|
|
import random
|
|
|
|
from celery import shared_task
|
|
from celery.schedules import crontab
|
|
from django.db import transaction
|
|
from django.db.models import F
|
|
from django.utils import timezone
|
|
|
|
from notify.delivery.exceptions import PermanentDeliveryError
|
|
from notify.delivery.registry import get_provider_or_raise
|
|
from notify.models import DeliveryStatus, Notification, NotificationRecipient, VerificationCode
|
|
|
|
__all__ = [
|
|
"BEAT_SCHEDULE",
|
|
"deliver_notification",
|
|
"delete_expired_codes",
|
|
"delete_expired_notifications",
|
|
"retry_countdown",
|
|
]
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
RETRY_BASE_DELAY = 60
|
|
|
|
BEAT_SCHEDULE = {
|
|
"notify-delete-expired-notifications": {
|
|
"task": "notify.tasks.delete_expired_notifications",
|
|
"schedule": crontab(minute=0),
|
|
},
|
|
"notify-delete-expired-codes": {
|
|
"task": "notify.tasks.delete_expired_codes",
|
|
"schedule": crontab(minute=30),
|
|
},
|
|
}
|
|
|
|
|
|
def _mark_failed(notification_recipient_id: str, error: str) -> None:
|
|
NotificationRecipient.objects.filter(
|
|
id=notification_recipient_id,
|
|
delivery_status=DeliveryStatus.UNSENT,
|
|
).update(
|
|
delivery_status=DeliveryStatus.FAILED,
|
|
last_error=error[:2000],
|
|
)
|
|
|
|
|
|
def _deliver_notification(notification_recipient_id: str) -> None:
|
|
error = None
|
|
with transaction.atomic():
|
|
recipient = (
|
|
NotificationRecipient.objects.select_for_update(of=("self",))
|
|
.select_related("notification__type", "user")
|
|
.filter(id=notification_recipient_id)
|
|
.first()
|
|
)
|
|
if recipient is None or recipient.delivery_status != DeliveryStatus.UNSENT:
|
|
return
|
|
NotificationRecipient.objects.filter(pk=recipient.pk).update(
|
|
attempts=F("attempts") + 1,
|
|
)
|
|
recipient.refresh_from_db(fields=["attempts"])
|
|
try:
|
|
provider = get_provider_or_raise(recipient.delivery_channel)
|
|
provider.send(recipient)
|
|
except Exception as exc:
|
|
if isinstance(exc, KeyError):
|
|
exc = PermanentDeliveryError(str(exc))
|
|
NotificationRecipient.objects.filter(pk=recipient.pk).update(
|
|
last_error=str(exc)[:2000],
|
|
)
|
|
error = exc
|
|
if error is not None:
|
|
raise error
|
|
|
|
|
|
def retry_countdown(retries: int) -> int:
|
|
delay = RETRY_BASE_DELAY * 2 ** retries
|
|
return delay + random.randint(0, delay // 10)
|
|
|
|
|
|
@shared_task(
|
|
bind=True,
|
|
max_retries=5,
|
|
)
|
|
def deliver_notification(self, notification_recipient_id: str):
|
|
try:
|
|
_deliver_notification(notification_recipient_id)
|
|
except PermanentDeliveryError as exc:
|
|
logger.error(
|
|
"Permanent delivery failure for recipient %s: %s",
|
|
notification_recipient_id,
|
|
exc,
|
|
)
|
|
_mark_failed(notification_recipient_id, str(exc))
|
|
except Exception as exc:
|
|
if self.request.retries >= self.max_retries:
|
|
logger.error(
|
|
"Delivery failed after retries for recipient %s: %s",
|
|
notification_recipient_id,
|
|
exc,
|
|
)
|
|
_mark_failed(notification_recipient_id, str(exc))
|
|
raise
|
|
raise self.retry(exc=exc, countdown=retry_countdown(self.request.retries)) from exc
|
|
|
|
|
|
@shared_task
|
|
def delete_expired_notifications():
|
|
deleted_count, _ = Notification.objects.filter(expires_at__lt=timezone.now()).delete()
|
|
return deleted_count
|
|
|
|
|
|
@shared_task
|
|
def delete_expired_codes():
|
|
deleted_count, _ = VerificationCode.objects.filter(expires_at__lt=timezone.now()).delete()
|
|
return deleted_count
|