|
| 1 | +import logging |
| 2 | +from osf.models import NotificationType, NotificationTypeEnum, OSFUser, UserActivityCounter |
| 3 | +from django.db.models import Q |
| 4 | +from django.db.models import OuterRef, Subquery, Exists, F |
| 5 | +from django.db.models.functions import Coalesce |
| 6 | +from framework.celery_tasks import app as celery_app |
| 7 | +from celery import chord |
| 8 | +from django.utils import timezone |
| 9 | +from osf.models.notification_campaign import NotificationCampaign, NotificationCampaignRecipient, NotificationCampaignStatus, NotificationCampaignRecipientStatus |
| 10 | + |
| 11 | +logger = logging.getLogger(__name__) |
| 12 | + |
| 13 | + |
| 14 | +counter_subquery = ( |
| 15 | + UserActivityCounter.objects |
| 16 | + .filter(_id=OuterRef('guids___id')) |
| 17 | + .values('total')[:1] |
| 18 | +) |
| 19 | + |
| 20 | + |
| 21 | +def get_filtered_batches(filters, batch_size=1000, campaign_id=None): |
| 22 | + already_sent_subquery = NotificationCampaignRecipient.objects.filter( |
| 23 | + campaign_id=campaign_id, |
| 24 | + user_id=OuterRef('pk'), |
| 25 | + ) |
| 26 | + |
| 27 | + qs = ( |
| 28 | + OSFUser.objects |
| 29 | + .annotate(already_sent=Exists(already_sent_subquery)) |
| 30 | + .filter(already_sent=False) |
| 31 | + .filter(**filters) |
| 32 | + .annotate(activity_total=Coalesce(Subquery(counter_subquery), 0)) |
| 33 | + .order_by('-activity_total', '-date_registered', '-id') |
| 34 | + ) |
| 35 | + |
| 36 | + last_total = None |
| 37 | + last_date = None |
| 38 | + last_id = None |
| 39 | + |
| 40 | + while True: |
| 41 | + batch_qs = qs |
| 42 | + |
| 43 | + if last_total is not None: |
| 44 | + batch_qs = batch_qs.filter( |
| 45 | + Q(activity_total__lt=last_total) | |
| 46 | + Q(activity_total=last_total, date_registered__lt=last_date) | |
| 47 | + Q(activity_total=last_total, date_registered=last_date, id__lt=last_id) |
| 48 | + ) |
| 49 | + |
| 50 | + batch = batch_qs[:batch_size] |
| 51 | + |
| 52 | + if not batch: |
| 53 | + break |
| 54 | + |
| 55 | + rows = list(batch.values_list('id', 'activity_total', 'date_registered')) |
| 56 | + |
| 57 | + if not rows: |
| 58 | + break |
| 59 | + |
| 60 | + batch_ids = [r[0] for r in rows] |
| 61 | + |
| 62 | + last_id, last_total, last_date = ( |
| 63 | + rows[-1][0], |
| 64 | + rows[-1][1], |
| 65 | + rows[-1][2], |
| 66 | + ) |
| 67 | + |
| 68 | + yield batch_ids |
| 69 | + |
| 70 | + |
| 71 | +FILTER_PRESETS = { |
| 72 | + 'all': {}, |
| 73 | + 'active': {'is_active': True}, |
| 74 | + 'internal': {'is_active': True, 'is_staff': True, 'username__endswith': '@cos.io'}, |
| 75 | +} |
| 76 | + |
| 77 | +@celery_app.task(name='email.process_campaign_retry') |
| 78 | +def process_campaign_retry(*args, **kwargs): |
| 79 | + |
| 80 | + campaign_id = kwargs.get('campaign_id') |
| 81 | + campaign = NotificationCampaign.objects.get(id=campaign_id) |
| 82 | + failed_recipients = NotificationCampaignRecipient.objects.filter(campaign=campaign, status=NotificationCampaignRecipientStatus.FAILED) |
| 83 | + max_retries = campaign.metadata.get('execution', {}).get('max_retries', 3) |
| 84 | + batch_size = campaign.metadata.get('execution', {}).get('batch_size', 1000) |
| 85 | + failed_recipients_count = failed_recipients.count() |
| 86 | + if not failed_recipients_count: |
| 87 | + campaign.status = NotificationCampaignStatus.COMPLETED |
| 88 | + campaign.completed_at = timezone.now() |
| 89 | + campaign.failed_count = 0 |
| 90 | + campaign.save(update_fields=['status', 'completed_at', 'failed_count']) |
| 91 | + return |
| 92 | + |
| 93 | + if campaign.retries < max_retries: |
| 94 | + logger.info(f'Retrying {failed_recipients_count} failed recipients for campaign {campaign_id}') |
| 95 | + filters = {'id__in': failed_recipients.values_list('user_id', flat=True)} |
| 96 | + tasks = [] |
| 97 | + for batch in get_filtered_batches(filters=filters, batch_size=batch_size, campaign_id=campaign_id): |
| 98 | + tasks.append( |
| 99 | + send_campaign_batch.s( |
| 100 | + notification_type_name=campaign.notification_type.name, |
| 101 | + recipients_ids=batch, |
| 102 | + context=campaign.metadata.get('context', {}), |
| 103 | + campaign_id=campaign_id, |
| 104 | + ) |
| 105 | + ) |
| 106 | + chord(tasks)( |
| 107 | + process_campaign_retry.s(campaign_id=campaign_id) |
| 108 | + ) |
| 109 | + campaign.retries += 1 |
| 110 | + campaign.save(update_fields=['retries']) |
| 111 | + else: |
| 112 | + campaign.failed_count = failed_recipients_count |
| 113 | + campaign.status = NotificationCampaignStatus.PARTIALLY_COMPLETED |
| 114 | + campaign.completed_at = timezone.now() |
| 115 | + campaign.save(update_fields=['status', 'completed_at', 'failed_count']) |
| 116 | + |
| 117 | + |
| 118 | +@celery_app.task(name='email.start_notification_campaign') |
| 119 | +def start_notification_campaign(campaign_id): |
| 120 | + campaign = NotificationCampaign.objects.get(id=campaign_id) |
| 121 | + filters = campaign.metadata.get('filters', {}) |
| 122 | + context = campaign.metadata.get('context', {}) |
| 123 | + notification_type_name = campaign.notification_type.name |
| 124 | + |
| 125 | + if hasattr(NotificationTypeEnum, notification_type_name): |
| 126 | + del getattr(NotificationTypeEnum, notification_type_name).instance |
| 127 | + |
| 128 | + if predefined_filter_name := filters.get('predefined'): |
| 129 | + filters = FILTER_PRESETS.get(predefined_filter_name, {}) |
| 130 | + |
| 131 | + tasks = [] |
| 132 | + total_recipients = 0 |
| 133 | + batch_size = campaign.metadata.get('execution', {}).get('batch_size', 1000) |
| 134 | + for batch in get_filtered_batches(filters=filters, batch_size=batch_size): |
| 135 | + tasks.append( |
| 136 | + send_campaign_batch.s( |
| 137 | + notification_type_name=notification_type_name, |
| 138 | + recipients_ids=batch, |
| 139 | + context=context, |
| 140 | + campaign_id=campaign_id, |
| 141 | + ) |
| 142 | + ) |
| 143 | + total_recipients += len(batch) |
| 144 | + |
| 145 | + campaign.recipient_count = total_recipients |
| 146 | + campaign.save(update_fields=['recipient_count']) |
| 147 | + |
| 148 | + chord(tasks)( |
| 149 | + process_campaign_retry.s(campaign_id=campaign_id) |
| 150 | + ) |
| 151 | + |
| 152 | + |
| 153 | +@celery_app.task(name='email.send_campaign_batch', ignore_result=False) |
| 154 | +def send_campaign_batch(context, recipients_ids, notification_type_name='blank', campaign_id=None): |
| 155 | + campaign = NotificationCampaign.objects.get(id=campaign_id) |
| 156 | + if campaign.status == NotificationCampaignStatus.CANCELLED: |
| 157 | + logger.warning(f"Campaign {campaign_id} was cancelled") |
| 158 | + return |
| 159 | + if hasattr(NotificationTypeEnum, notification_type_name): |
| 160 | + notification_type = getattr(NotificationTypeEnum, notification_type_name).instance |
| 161 | + else: |
| 162 | + notification_type = NotificationType.objects.filter( |
| 163 | + name=notification_type_name |
| 164 | + ).first() # TODO cache |
| 165 | + |
| 166 | + if notification_type is None: |
| 167 | + return |
| 168 | + |
| 169 | + recipients_qs = OSFUser.objects.filter(id__in=recipients_ids) |
| 170 | + recipient_records = { |
| 171 | + 'to_create': [], |
| 172 | + 'to_update': [], |
| 173 | + } |
| 174 | + existing = { |
| 175 | + r.user_id: r |
| 176 | + for r in NotificationCampaignRecipient.objects.filter( |
| 177 | + campaign_id=campaign_id, |
| 178 | + user_id__in=recipients_ids, |
| 179 | + ) |
| 180 | + } |
| 181 | + success_count = 0 |
| 182 | + failure_count = 0 |
| 183 | + |
| 184 | + for recipient in recipients_qs: |
| 185 | + recipient_record = existing.get(recipient.id) |
| 186 | + |
| 187 | + if recipient_record is None: |
| 188 | + recipient_record = NotificationCampaignRecipient( |
| 189 | + campaign_id=campaign_id, |
| 190 | + user=recipient, |
| 191 | + ) |
| 192 | + operation = 'to_create' |
| 193 | + else: |
| 194 | + operation = 'to_update' |
| 195 | + |
| 196 | + try: |
| 197 | + notification_type.emit( |
| 198 | + user=recipient, |
| 199 | + event_context=context, |
| 200 | + save=False, # Too many write operations |
| 201 | + ) |
| 202 | + |
| 203 | + recipient_record.status = NotificationCampaignRecipientStatus.SENT |
| 204 | + recipient_record.error_message = None |
| 205 | + recipient_records[operation].append(recipient_record) |
| 206 | + success_count += 1 |
| 207 | + |
| 208 | + except Exception as exc: |
| 209 | + logger.error(exc) # TODO update error |
| 210 | + recipient_record.status = NotificationCampaignRecipientStatus.FAILED |
| 211 | + recipient_record.error_message = str(exc) |
| 212 | + recipient_records[operation].append(recipient_record) |
| 213 | + |
| 214 | + failure_count += 1 |
| 215 | + pass |
| 216 | + |
| 217 | + NotificationCampaignRecipient.objects.bulk_create(recipient_records['to_create']) |
| 218 | + NotificationCampaignRecipient.objects.bulk_update(recipient_records['to_update'], ['status', 'error_message']) |
| 219 | + |
| 220 | + NotificationCampaign.objects.filter(pk=campaign_id).update(sent_count=F('sent_count') + success_count, failed_count=F('failed_count') + failure_count) |
| 221 | + logger.info('Batch finished') # TODO: add/update logs |
0 commit comments