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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
use std::fmt::{Debug, Formatter};
use std::time::Duration;
use std::{error, fmt};
/// Every way a Telegram send can fail.
///
/// Note that [`TelegramError::Http`] always holds a [`reqwest::Error`] which has
/// had its URL stripped via [`reqwest::Error::without_url`]. The bot token is a
/// path segment of every request URL, and `reqwest`'s own `Debug` includes the
/// URL, so an un-stripped error would leak the credential into any log line.
#[derive(Debug)]
pub enum TelegramError {
/// The bot token was empty or malformed.
InvalidToken(String),
/// The message was too large to even attempt to send.
///
/// This is a guard against an upstream bug producing a multi-megabyte
/// string; it is checked before chunking, so it is never the result of
/// merely exceeding Telegram's per-message limit.
MessageTooLarge {
/// Size of the offending message, in bytes.
bytes: usize,
/// The maximum permitted size, in bytes.
max: usize,
},
/// The HTTP request itself failed (connection refused, TLS failure, timeout).
Http(reqwest::Error),
/// Telegram accepted the request but rejected its contents.
Api {
/// Telegram's `error_code` (an HTTP status code).
error_code: i32,
/// Telegram's human-readable `description`.
description: String,
},
/// Telegram returned `429` along with how long to wait.
///
/// This is distinct from a plain [`TelegramError::Api`] `429` because it
/// carries an actionable delay: Telegram is telling us precisely when the
/// request may be repeated.
RateLimited {
/// How long Telegram asked us to wait.
retry_after: Duration,
},
/// The response body could not be deserialized.
Serialization(serde_json::Error),
/// An invariant inside this library was violated.
Internal(String),
}
impl TelegramError {
/// Whether this error is permanent, meaning a retry can never succeed.
///
/// A permanent error almost always means the notifier is misconfigured
/// rather than that this particular message was bad: a wrong token, a chat
/// the bot was removed from, a chat id that does not exist. Every
/// subsequent send will fail the same way.
#[must_use]
pub const fn is_permanent(&self) -> bool {
match self {
Self::InvalidToken(_) | Self::MessageTooLarge { .. } | Self::Internal(_) => true,
Self::Api { error_code, .. } => {
// 429 is handled separately (it carries `retry_after`), and 5xx
// is transient. Everything else in the 4xx range is permanent.
*error_code >= 400 && *error_code < 500 && *error_code != 429
}
Self::Http(_) | Self::Serialization(_) | Self::RateLimited { .. } => false,
}
}
/// Whether this error indicates the notifier as a whole is misconfigured.
///
/// These deserve a louder log than an ordinary send failure, because they
/// mean every future send is also doomed:
/// - `401` — the bot token is wrong.
/// - `403` — the bot was blocked, or removed from the chat.
/// - `400` with a chat-related description — the chat id is wrong.
#[must_use]
pub fn is_misconfiguration(&self) -> bool {
match self {
Self::InvalidToken(_) => true,
Self::Api {
error_code,
description,
} => {
*error_code == 401
|| *error_code == 403
|| (*error_code == 400 && description.to_lowercase().contains("chat not found"))
}
_ => false,
}
}
}
impl error::Error for TelegramError {}
impl fmt::Display for TelegramError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidToken(reason) => write!(f, "invalid telegram bot token: {reason}"),
Self::MessageTooLarge { bytes, max } => {
write!(
f,
"message is {bytes} bytes, which exceeds the {max} byte maximum"
)
}
Self::Http(error) => write!(f, "telegram http request failed: {error}"),
Self::Api {
error_code,
description,
} => write!(
f,
"telegram rejected the request ({error_code}): {description}"
),
Self::RateLimited { retry_after } => {
write!(f, "telegram rate limited us; retry after {retry_after:?}")
}
Self::Serialization(error) => {
write!(f, "could not deserialize telegram's response: {error}")
}
Self::Internal(reason) => write!(f, "internal telegram client error: {reason}"),
}
}
}
impl From<reqwest::Error> for TelegramError {
fn from(error: reqwest::Error) -> Self {
// Strip the URL unconditionally: it contains the bot token.
Self::Http(error.without_url())
}
}
impl From<serde_json::Error> for TelegramError {
fn from(error: serde_json::Error) -> Self {
Self::Serialization(error)
}
}
#[cfg(test)]
mod tests {
use super::TelegramError;
#[test]
fn client_errors_are_permanent() {
let error: TelegramError = TelegramError::Api {
error_code: 400,
description: String::from("Bad Request: message text is empty"),
};
assert!(error.is_permanent());
}
#[test]
fn rate_limit_errors_are_not_permanent() {
let error: TelegramError = TelegramError::Api {
error_code: 429,
description: String::from("Too Many Requests: retry after 5"),
};
assert!(!error.is_permanent());
}
#[test]
fn server_errors_are_not_permanent() {
let error: TelegramError = TelegramError::Api {
error_code: 502,
description: String::from("Bad Gateway"),
};
assert!(!error.is_permanent());
}
#[test]
fn unauthorized_is_a_misconfiguration() {
let error: TelegramError = TelegramError::Api {
error_code: 401,
description: String::from("Unauthorized"),
};
assert!(error.is_misconfiguration());
}
#[test]
fn forbidden_is_a_misconfiguration() {
let error: TelegramError = TelegramError::Api {
error_code: 403,
description: String::from("Forbidden: bot was blocked by the user"),
};
assert!(error.is_misconfiguration());
}
#[test]
fn chat_not_found_is_a_misconfiguration() {
let error: TelegramError = TelegramError::Api {
error_code: 400,
description: String::from("Bad Request: chat not found"),
};
assert!(error.is_misconfiguration());
}
#[test]
fn an_ordinary_bad_request_is_not_a_misconfiguration() {
let error: TelegramError = TelegramError::Api {
error_code: 400,
description: String::from("Bad Request: message is too long"),
};
assert!(!error.is_misconfiguration());
}
#[test]
fn display_includes_the_error_code_and_description() {
let error: TelegramError = TelegramError::Api {
error_code: 400,
description: String::from("Bad Request: chat not found"),
};
let expected: String =
String::from("telegram rejected the request (400): Bad Request: chat not found");
let actual: String = format!("{error}");
assert_eq!(expected, actual);
}
}