Coverage for notifications/adapters/base.py: 85.84%

93 statements  

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

1"""The contract every chat platform implements. 

2 

3An adapter owns everything specific to one platform: what a valid destination 

4looks like, how text is escaped, what configuration it needs, and how a message 

5is sent. Nothing outside `notifications/adapters/` names a platform's rules, so 

6adding one is a new module plus a line in `notifications/registry.py`. 

7 

8Destination values are sensitive and must never appear in logs or in the 

9messages of exceptions raised here. 

10""" 

11 

12from __future__ import annotations 

13 

14import re 

15from abc import ABC, abstractmethod 

16from dataclasses import dataclass 

17from enum import StrEnum 

18from typing import ClassVar 

19 

20import httpx 

21 

22 

23class Capability(StrEnum): 

24 """Optional features a platform supports. Callers degrade when one is absent.""" 

25 

26 THREADS = "threads" 

27 

28 

29class NotificationConfigError(RuntimeError): 

30 """The subsystem is missing required config (e.g. a bot token).""" 

31 

32 

33class UnsupportedPlatformError(ValueError): 

34 """No adapter is registered under this platform id.""" 

35 

36 

37class InvalidDestinationError(ValueError): 

38 """A destination does not match the platform's format.""" 

39 

40 

41class DeliveryError(RuntimeError): 

42 """A send failed. Safe to log. 

43 

44 Provider errors can't be: an httpx error's text carries the request URL, 

45 which holds the Telegram bot token or a webhook's secret path. 

46 

47 `retryable` says whether trying again later could work (rate limit, server 

48 error, network); `retry_after` is the provider's own wait, in seconds, when 

49 it gave one (SB-1604). 

50 """ 

51 

52 def __init__(self, message: str, retryable: bool = False, retry_after: float | None = None): 

53 super().__init__(message) 

54 self.retryable = retryable 

55 self.retry_after = retry_after 

56 

57 

58def _seconds(value) -> float | None: 

59 try: 

60 seconds = float(value) 

61 except (TypeError, ValueError): 

62 return None 

63 return seconds if seconds >= 0 else None 

64 

65 

66def classify_failure(exc: BaseException) -> tuple[bool, float | None]: 

67 """(retryable, retry_after seconds) for a provider failure (SB-1604). Pure. 

68 

69 Retryable: HTTP 429 and 5xx, timeouts and other transport errors, and a 

70 provider error body that names a wait (Discord's and Telegram's rate 

71 limits). Anything else, e.g. a deleted webhook (404) or a bad chat ID 

72 (400), will fail the same way again, so it is final. 

73 """ 

74 if isinstance(exc, httpx.HTTPStatusError): 

75 code = exc.response.status_code 

76 wait = _seconds(exc.response.headers.get("Retry-After")) 

77 if wait is None: 

78 try: 

79 body = exc.response.json() 

80 except Exception: 

81 body = {} 

82 if isinstance(body, dict): 82 ↛ 84line 82 didn't jump to line 84 because the condition on line 82 was always true

83 wait = _seconds(body.get("retry_after") or (body.get("parameters") or {}).get("retry_after")) 

84 return (code == 429 or code >= 500), wait 

85 if isinstance(exc, httpx.TransportError): 

86 return True, None 

87 body = getattr(exc, "response", None) 

88 if isinstance(body, dict): 

89 wait = _seconds(body.get("retry_after") or (body.get("parameters") or {}).get("retry_after")) 

90 if wait is not None: 

91 return True, wait 

92 return False, None 

93 

94 

95@dataclass(frozen=True) 

96class DeliveryResult: 

97 """Outcome of a successful send; failures raise. 

98 

99 `message_ref` is the provider's id for the posted message, or None when the 

100 provider does not return one (e.g. a webhook answering 204). 

101 """ 

102 

103 message_ref: str | None = None 

104 # The thread the message went into, when posted as a match thread (SB-1606). 

105 thread_ref: str | None = None 

106 

107 

108class ChannelAdapter(ABC): 

109 """A chat platform MT can post match updates to.""" 

110 

111 id: ClassVar[str] 

112 label: ClassVar[str] 

113 icon: ClassVar[str] 

114 placeholder: ClassVar[str] 

115 # What the destination is called on a setup form. 

116 destination_label: ClassVar[str] = "Webhook URL" 

117 hint: ClassVar[str] 

118 # Numbered how-to the setup UI shows under "How to set up". Plain text, 

119 # one action per step, ending with what to paste. 

120 setup_steps: ClassVar[tuple[str, ...]] 

121 # Served to the browser and used in `new RegExp(...)`, so keep it to syntax 

122 # Python and JavaScript read the same way. Anchors are required. 

123 destination_pattern: ClassVar[str] 

124 destination_error: ClassVar[str] 

125 # The link people use to join: the platform's invite form, never a public 

126 # page link. The UI never calls a room private: invite links can be forwarded. Same regex rules as above. 

127 invite_pattern: ClassVar[str] 

128 invite_error: ClassVar[str] 

129 capabilities: ClassVar[frozenset[Capability]] = frozenset() 

130 # Youngest U-number this platform may host as a player channel. None means 

131 # fans only. Set from the platform's terms, so a change is a one-line edit. 

132 min_player_age: ClassVar[int | None] = None 

133 # Shown wherever a channel on this platform is offered (SB-1612): the 

134 # platform's own minimum age, from its terms. None: nothing to say. 

135 age_note: ClassVar[str | None] = None 

136 # Extra steps for player channels: club announcements are read-only with 

137 # reactions; a squad channel is the team's chat (SB-1673). 

138 # Empty: the platform has no such setting to describe. 

139 player_setup_steps: ClassVar[tuple[str, ...]] = () 

140 

141 def validate_destination(self, destination: str) -> None: 

142 """Raise InvalidDestinationError unless `destination` fits this platform. 

143 

144 For a webhook platform the pattern is also the SSRF guard, because the 

145 backend POSTs to whatever is saved here. ASCII mode keeps `\\d` and `\\w` 

146 identical to the browser's check. 

147 """ 

148 if not re.fullmatch(self.destination_pattern, destination, flags=re.ASCII): 

149 raise InvalidDestinationError(self.destination_error) 

150 

151 def validate_invite_url(self, invite_url: str) -> None: 

152 """Raise InvalidDestinationError unless `invite_url` is this platform's private join link.""" 

153 if not re.fullmatch(self.invite_pattern, invite_url, flags=re.ASCII): 

154 raise InvalidDestinationError(self.invite_error) 

155 

156 def check_config(self) -> None: # noqa: B027 — optional hook; most platforms need no config 

157 """Raise NotificationConfigError if the platform cannot send right now.""" 

158 

159 def send(self, destination: str, content: str) -> DeliveryResult: 

160 """Deliver plain text. Raises NotificationConfigError or DeliveryError. 

161 

162 `from None` drops the provider exception from the traceback as well, 

163 since `logger.exception` would otherwise print its URL. 

164 """ 

165 try: 

166 return self._deliver(destination, content) 

167 except NotificationConfigError: 

168 raise 

169 except Exception as exc: 

170 detail = type(exc).__name__ 

171 if isinstance(exc, httpx.HTTPStatusError): 171 ↛ 173line 171 didn't jump to line 173 because the condition on line 171 was always true

172 detail = f"HTTP {exc.response.status_code}" 

173 retryable, retry_after = classify_failure(exc) 

174 raise DeliveryError(f"{self.id} send failed: {detail}", retryable, retry_after) from None 

175 

176 def send_in_thread( 

177 self, destination: str, content: str, thread_ref: str | None, thread_name: str | None 

178 ) -> DeliveryResult: 

179 """Post into a match thread (SB-1606): a new one named `thread_name`, or `thread_ref`. 

180 

181 Only for platforms with Capability.THREADS; the result carries the 

182 thread's id. Same error handling as `send`. 

183 """ 

184 try: 

185 return self._deliver_in_thread(destination, content, thread_ref, thread_name) 

186 except NotificationConfigError: 

187 raise 

188 except Exception as exc: 

189 detail = type(exc).__name__ 

190 if isinstance(exc, httpx.HTTPStatusError): 

191 detail = f"HTTP {exc.response.status_code}" 

192 retryable, retry_after = classify_failure(exc) 

193 raise DeliveryError(f"{self.id} send failed: {detail}", retryable, retry_after) from None 

194 

195 def _deliver_in_thread( 

196 self, destination: str, content: str, thread_ref: str | None, thread_name: str | None 

197 ) -> DeliveryResult: 

198 raise NotImplementedError(f"{self.id} has no threads") 

199 

200 @abstractmethod 

201 def _deliver(self, destination: str, content: str) -> DeliveryResult: 

202 """Make the provider call. Exceptions are sanitized by `send`."""