-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscheduler.py
More file actions
97 lines (75 loc) · 2.77 KB
/
scheduler.py
File metadata and controls
97 lines (75 loc) · 2.77 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from __future__ import annotations
import logging
from contextlib import suppress
from datetime import datetime
from typing import TYPE_CHECKING
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from apps.notifications.models import NotificationKind, ScheduledNotification
if TYPE_CHECKING:
from django.db.models import Model
from apps.accounts.models import User
from apps.sections.models import Section
NotificationKindValue = NotificationKind | str
logger = logging.getLogger(__name__)
def enqueue_delayed_notification(
*,
kind: NotificationKindValue,
recipient: User,
section: Section,
related_object: Model,
send_after: datetime,
) -> ScheduledNotification | None:
"""
Create a ScheduledNotification to be sent at send_after.
If an unsent notification of the same kind already exists for this
recipient + object, update its send_after time (upsert / digest logic).
Uses select_for_update to prevent duplicate rows from concurrent requests.
"""
with suppress(AttributeError):
if not recipient.profile.email_notifications_enabled:
logger.info("Skipping scheduled notification for %s: global opt-out", recipient)
return None
ct = ContentType.objects.get_for_model(related_object)
with transaction.atomic():
existing = (
ScheduledNotification.objects.select_for_update()
.filter(
kind=kind,
recipient=recipient,
content_type=ct,
object_id=related_object.pk,
sent_at__isnull=True,
cancelled_at__isnull=True,
)
.first()
)
if existing:
existing.send_after = send_after
existing.save(update_fields=["send_after", "modified"])
return existing
return ScheduledNotification.objects.create(
kind=kind,
recipient=recipient,
section=section,
content_type=ct,
object_id=related_object.pk,
send_after=send_after,
)
def cancel_scheduled_notifications_for(related_object: Model) -> int:
"""
Cancel all pending ScheduledNotifications linked to related_object.
Returns the number of records cancelled.
"""
from django.utils import timezone
ct = ContentType.objects.get_for_model(related_object)
now = timezone.now()
count = ScheduledNotification.objects.filter(
content_type=ct,
object_id=related_object.pk,
sent_at__isnull=True,
cancelled_at__isnull=True,
).update(cancelled_at=now, modified=now)
if count:
logger.info("Cancelled %d scheduled notification(s) for %r", count, related_object)
return count