Coverage for notifications/retry_worker.py: 65.74%

94 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 14:44 +0000

1"""Deliver pending chat posts the live path could not finish (SB-1604). 

2 

3The live path (Notifier._post_to_channel) sends each post once. A post that hit 

4a rate limit, a server error or a network failure is left `pending` in the 

5delivery ledger with a `next_attempt_at`; a post whose pod died mid-send is left 

6`pending` with none. This worker picks both up: 

7 

8- `claim_due_notification_deliveries` hands out due rows atomically, counts the 

9 attempt and leases the row, so two pods never send the same post and a worker 

10 that dies mid-send leaves it to be retried. 

11- Sends run concurrently and each finishes on its own (a done-callback records 

12 it), so one slow destination cannot hold up the others. 

13- Backoff and the attempt limit come from retry_policy; after the last attempt 

14 the row is `failed` for good, which "Last post" shows to managers and admins. 

15- A channel removed or paused since the first try is not posted to. 

16 

17It runs in a background thread of the backend process, never on a request, and 

18only when NOTIFICATION_RETRY_WORKER is on, so tests and local runs stay quiet. 

19""" 

20 

21from __future__ import annotations 

22 

23import os 

24import threading 

25from concurrent.futures import Future, ThreadPoolExecutor 

26from contextlib import asynccontextmanager 

27from datetime import UTC, datetime 

28from typing import TYPE_CHECKING 

29 

30import structlog 

31 

32from notifications.retry_policy import next_attempt 

33from notifications.threads import send as thread_send 

34 

35if TYPE_CHECKING: 

36 from collections.abc import Callable 

37 

38logger = structlog.get_logger(__name__) 

39 

40BATCH_SIZE = 25 

41LEASE_SECONDS = 120 # longer than any one send can take 

42STALE_SECONDS = 120 # a first send this old never finished 

43INTERVAL_SECONDS = 15 

44MAX_CONCURRENT_SENDS = 8 

45 

46 

47def _safe_error(exc: BaseException) -> str: 

48 from notifications.dispatcher import _safe_error as safe 

49 

50 return safe(exc) # type: ignore[arg-type] 

51 

52 

53def _record(deliveries, row: dict, future: Future, now_fn: Callable[[], datetime]) -> None: 

54 """Write the outcome of one send. Called when its future completes.""" 

55 delivery_id = row["id"] 

56 exc = future.exception() 

57 if exc is None: 

58 result = future.result() 

59 deliveries.mark_sent(delivery_id, getattr(result, "message_ref", None)) 

60 logger.info("notifications.retry_sent", delivery_id=delivery_id, attempt=row.get("attempts")) 

61 return 

62 error = _safe_error(exc) 

63 retry_at = next_attempt( 

64 int(row.get("attempts") or 1), 

65 bool(getattr(exc, "retryable", False)), 

66 getattr(exc, "retry_after", None), 

67 now_fn(), 

68 ) 

69 if retry_at is None: 

70 deliveries.mark_failed(delivery_id, error) 

71 logger.warning("notifications.retry_gave_up", delivery_id=delivery_id, attempt=row.get("attempts"), error=error) 

72 else: 

73 deliveries.mark_retry(delivery_id, error, retry_at.isoformat()) 

74 logger.info("notifications.retry_scheduled", delivery_id=delivery_id, attempt=row.get("attempts")) 

75 

76 

77def _recorder(deliveries, row: dict, now_fn: Callable[[], datetime]) -> Callable[[Future], None]: 

78 def done(future: Future) -> None: 

79 _record(deliveries, row, future, now_fn) 

80 

81 return done 

82 

83 

84def process_due( 

85 deliveries, 

86 channels, 

87 send_fn: Callable, 

88 executor: ThreadPoolExecutor, 

89 now_fn: Callable[[], datetime] = lambda: datetime.now(UTC), 

90 threads=None, 

91) -> int: 

92 """Claim due posts and start sending them. Returns how many were started. 

93 

94 Does not wait for the sends: each records its own outcome when it finishes. 

95 """ 

96 rows = deliveries.claim_due(BATCH_SIZE, LEASE_SECONDS, STALE_SECONDS) 

97 started = 0 

98 for row in rows: 

99 channel = channels.get_by_id(row["channel_id"]) 

100 if channel is None or not channel.get("enabled"): 

101 deliveries.mark_failed(row["id"], "Channel removed or paused before it could be sent") 

102 continue 

103 future = executor.submit( 

104 thread_send, 

105 send_fn, 

106 channel["platform"], 

107 channel["destination"], 

108 row["content"], 

109 post_as_threads=bool(channel.get("post_as_threads")), 

110 channel_id=row["channel_id"], 

111 match_id=row.get("match_id"), 

112 thread_name=None, # the thread row keeps its name; see notifications/threads.py 

113 threads=threads, 

114 ) 

115 future.add_done_callback(_recorder(deliveries, row, now_fn)) 

116 started += 1 

117 return started 

118 

119 

120def enabled() -> bool: 

121 return os.getenv("NOTIFICATION_RETRY_WORKER", "off").lower() in {"1", "true", "on", "yes"} 

122 

123 

124class RetryWorker: 

125 """A daemon thread that calls process_due every INTERVAL_SECONDS.""" 

126 

127 def __init__(self, deliveries, channels, send_fn: Callable, interval: float = INTERVAL_SECONDS, threads=None): 

128 self._deliveries = deliveries 

129 self._channels = channels 

130 self._threads = threads 

131 self._send_fn = send_fn 

132 self._interval = interval 

133 self._stop = threading.Event() 

134 self._executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT_SENDS, thread_name_prefix="notify-retry") 

135 self._thread = threading.Thread(target=self._run, name="notify-retry-worker", daemon=True) 

136 

137 def start(self) -> None: 

138 self._thread.start() 

139 logger.info("notifications.retry_worker_started", interval=self._interval) 

140 

141 def stop(self) -> None: 

142 self._stop.set() 

143 self._thread.join(timeout=5) 

144 self._executor.shutdown(wait=False, cancel_futures=True) 

145 

146 def _run(self) -> None: 

147 from api.club_notifications import is_notifications_enabled 

148 

149 while not self._stop.wait(self._interval): 

150 if not is_notifications_enabled(): 

151 continue 

152 try: 

153 process_due(self._deliveries, self._channels, self._send_fn, self._executor, threads=self._threads) 

154 except Exception as exc: # never let the loop die 

155 logger.warning("notifications.retry_worker_error", error_type=type(exc).__name__) 

156 

157 

158@asynccontextmanager 

159async def retry_worker_lifespan(): 

160 """Start the worker with the app when NOTIFICATION_RETRY_WORKER is on.""" 

161 if not enabled(): 161 ↛ 164line 161 didn't jump to line 164 because the condition on line 161 was always true

162 yield 

163 return 

164 from dao.match_dao import SupabaseConnection 

165 from dao.notification_channels_dao import NotificationChannelsDAO 

166 from dao.notification_deliveries_dao import NotificationDeliveriesDAO 

167 from dao.notification_threads_dao import NotificationThreadsDAO 

168 from notifications.senders import send_to 

169 

170 conn = SupabaseConnection() 

171 worker = RetryWorker( 

172 NotificationDeliveriesDAO(conn), NotificationChannelsDAO(conn), send_to, threads=NotificationThreadsDAO(conn) 

173 ) 

174 worker.start() 

175 try: 

176 yield 

177 finally: 

178 worker.stop()