1use anyhow::Result;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7#[non_exhaustive]
8pub enum Service {
9 NativeEnvelope,
11 QrLogin,
13 LoginPoll,
15 SavedDeviceLogin,
17 AccountAuthentication,
19 AutomaticAuthentication,
21 Heartbeat,
23 Sync,
25 Contact,
27 ContactSync,
29 ContactBootstrap,
31 Room,
33 GroupMetadata,
35 Avatar,
37 Voice,
39 FileUploadReservation,
41 CdnBootstrap,
43 CdnDownload,
45 CdnUpload,
47 LargeFileUpload,
49 ChannelsAuthorization,
51 ChannelsPage,
53 Channels,
55 ChannelsDetail,
57}
58
59impl Service {
60 pub fn label(self) -> &'static str {
62 match self {
63 Self::NativeEnvelope => "Native envelope",
64 Self::QrLogin => "QR service",
65 Self::LoginPoll => "Login poll",
66 Self::SavedDeviceLogin => "Saved-device login",
67 Self::AccountAuthentication => "Account authentication",
68 Self::AutomaticAuthentication => "Automatic authentication",
69 Self::Heartbeat => "Heartbeat",
70 Self::Sync => "Sync service",
71 Self::Contact => "Contact service",
72 Self::ContactSync => "Contact sync service",
73 Self::ContactBootstrap => "Contact bootstrap",
74 Self::Room => "Room service",
75 Self::GroupMetadata => "Group metadata service",
76 Self::Avatar => "Avatar service",
77 Self::Voice => "Voice service",
78 Self::FileUploadReservation => "File upload reservation",
79 Self::CdnBootstrap => "CDN bootstrap",
80 Self::CdnDownload => "CDN download",
81 Self::CdnUpload => "CDN upload",
82 Self::LargeFileUpload => "Large-file upload",
83 Self::ChannelsAuthorization => "Channels authorization",
84 Self::ChannelsPage => "Channels page",
85 Self::Channels => "Channels service",
86 Self::ChannelsDetail => "Channels detail",
87 }
88 }
89}
90
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct ServiceRejected {
95 pub service: Service,
97 pub code: i32,
99}
100
101impl ServiceRejected {
102 pub const SESSION_REJECTED: i32 = -13;
105
106 pub fn new(service: Service, code: i32) -> Self {
108 Self { service, code }
109 }
110
111 pub(crate) fn check(service: Service, code: i32) -> Result<()> {
113 if code == 0 {
114 Ok(())
115 } else {
116 Err(Self { service, code }.into())
117 }
118 }
119
120 pub(crate) fn check_wide(service: Service, code: i64) -> Result<()> {
123 match i32::try_from(code) {
124 Ok(code) => Self::check(service, code),
125 Err(_) => Err(anyhow::anyhow!("{} returned {code}", service.label())),
126 }
127 }
128
129 pub fn find(error: &anyhow::Error) -> Option<&Self> {
131 find(error)
132 }
133
134 pub fn is_session_rejected(&self) -> bool {
138 self.code == Self::SESSION_REJECTED
139 && matches!(
140 self.service,
141 Service::NativeEnvelope
142 | Service::Heartbeat
143 | Service::Sync
144 | Service::Contact
145 | Service::ContactSync
146 | Service::SavedDeviceLogin
147 | Service::AccountAuthentication
148 | Service::AutomaticAuthentication
149 )
150 }
151}
152
153impl std::fmt::Display for ServiceRejected {
154 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155 write!(f, "{} returned {}", self.service.label(), self.code)
156 }
157}
158
159impl std::error::Error for ServiceRejected {}
160
161pub fn is_session_rejected(error: &anyhow::Error) -> bool {
166 ServiceRejected::find(error).is_some_and(ServiceRejected::is_session_rejected)
167 || find::<crate::OpenImServiceError>(error)
168 .is_some_and(|failure| failure.service_code == ServiceRejected::SESSION_REJECTED)
169}
170
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175#[non_exhaustive]
176pub enum AccountInterrupted {
177 Stopped,
180 Transferred,
183 CredentialsSuperseded,
186}
187
188impl AccountInterrupted {
189 pub fn find(error: &anyhow::Error) -> Option<Self> {
191 find(error).copied()
192 }
193
194 pub(crate) fn because(self, message: &'static str) -> anyhow::Error {
196 anyhow::Error::new(self).context(message)
197 }
198}
199
200impl std::fmt::Display for AccountInterrupted {
201 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202 f.write_str(match self {
203 Self::Stopped => "Account stopped",
204 Self::Transferred => "Account state transferred",
205 Self::CredentialsSuperseded => "Account credentials superseded",
206 })
207 }
208}
209
210impl std::error::Error for AccountInterrupted {}
211
212fn find<T: std::error::Error + Send + Sync + 'static>(error: &anyhow::Error) -> Option<&T> {
213 error
214 .downcast_ref::<T>()
215 .or_else(|| error.chain().find_map(|cause| cause.downcast_ref::<T>()))
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 #[test]
223 fn service_rejection_keeps_its_message_and_is_found_under_context() {
224 let error = ServiceRejected::check(Service::Heartbeat, -13)
225 .unwrap_err()
226 .context("request failed")
227 .context(crate::NativeRequestNotSubmitted);
228 assert_eq!(
229 ServiceRejected::find(&error),
230 Some(&ServiceRejected::new(Service::Heartbeat, -13))
231 );
232 assert_eq!(
233 error.root_cause().to_string(),
234 "Heartbeat returned -13",
235 "the message matches the earlier untyped error"
236 );
237 assert!(ServiceRejected::check(Service::Heartbeat, 0).is_ok());
238 }
239
240 #[test]
241 fn session_rejection_depends_on_the_boundary_and_the_exact_code() {
242 for service in [
243 Service::NativeEnvelope,
244 Service::Heartbeat,
245 Service::Sync,
246 Service::Contact,
247 Service::ContactSync,
248 Service::SavedDeviceLogin,
249 Service::AccountAuthentication,
250 Service::AutomaticAuthentication,
251 ] {
252 assert!(is_session_rejected(
253 &ServiceRejected::new(service, -13).into()
254 ));
255 assert!(!is_session_rejected(
256 &ServiceRejected::new(service, -130).into()
257 ));
258 }
259 for service in [Service::CdnBootstrap, Service::Voice, Service::LoginPoll] {
260 assert!(!is_session_rejected(
261 &ServiceRejected::new(service, -13).into()
262 ));
263 }
264 assert!(is_session_rejected(
265 &anyhow::Error::new(crate::OpenImServiceError { service_code: -13 }).context("lookup")
266 ));
267 assert!(!is_session_rejected(&anyhow::anyhow!(
268 "Heartbeat returned -13"
269 )));
270 }
271
272 #[test]
273 fn interruption_reason_is_found_behind_its_message() {
274 let error = AccountInterrupted::Stopped
275 .because("Account stopped during request")
276 .context(crate::NativeRequestNotSubmitted);
277 assert_eq!(
278 AccountInterrupted::find(&error),
279 Some(AccountInterrupted::Stopped)
280 );
281 assert!(error.is::<crate::NativeRequestNotSubmitted>());
282 assert_eq!(AccountInterrupted::find(&anyhow::anyhow!("other")), None);
283 }
284}