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}
50
51impl Service {
52 pub fn label(self) -> &'static str {
54 match self {
55 Self::NativeEnvelope => "Native envelope",
56 Self::QrLogin => "QR service",
57 Self::LoginPoll => "Login poll",
58 Self::SavedDeviceLogin => "Saved-device login",
59 Self::AccountAuthentication => "Account authentication",
60 Self::AutomaticAuthentication => "Automatic authentication",
61 Self::Heartbeat => "Heartbeat",
62 Self::Sync => "Sync service",
63 Self::Contact => "Contact service",
64 Self::ContactSync => "Contact sync service",
65 Self::ContactBootstrap => "Contact bootstrap",
66 Self::Room => "Room service",
67 Self::GroupMetadata => "Group metadata service",
68 Self::Avatar => "Avatar service",
69 Self::Voice => "Voice service",
70 Self::FileUploadReservation => "File upload reservation",
71 Self::CdnBootstrap => "CDN bootstrap",
72 Self::CdnDownload => "CDN download",
73 Self::CdnUpload => "CDN upload",
74 Self::LargeFileUpload => "Large-file upload",
75 }
76 }
77}
78
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct ServiceRejected {
83 pub service: Service,
85 pub code: i32,
87}
88
89impl ServiceRejected {
90 pub const SESSION_REJECTED: i32 = -13;
93
94 pub fn new(service: Service, code: i32) -> Self {
96 Self { service, code }
97 }
98
99 pub(crate) fn check(service: Service, code: i32) -> Result<()> {
101 if code == 0 {
102 Ok(())
103 } else {
104 Err(Self { service, code }.into())
105 }
106 }
107
108 pub(crate) fn check_wide(service: Service, code: i64) -> Result<()> {
111 match i32::try_from(code) {
112 Ok(code) => Self::check(service, code),
113 Err(_) => Err(anyhow::anyhow!("{} returned {code}", service.label())),
114 }
115 }
116
117 pub fn find(error: &anyhow::Error) -> Option<&Self> {
119 find(error)
120 }
121
122 pub fn is_session_rejected(&self) -> bool {
126 self.code == Self::SESSION_REJECTED
127 && matches!(
128 self.service,
129 Service::NativeEnvelope
130 | Service::Heartbeat
131 | Service::Sync
132 | Service::Contact
133 | Service::ContactSync
134 | Service::SavedDeviceLogin
135 | Service::AccountAuthentication
136 | Service::AutomaticAuthentication
137 )
138 }
139}
140
141impl std::fmt::Display for ServiceRejected {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 write!(f, "{} returned {}", self.service.label(), self.code)
144 }
145}
146
147impl std::error::Error for ServiceRejected {}
148
149pub fn is_session_rejected(error: &anyhow::Error) -> bool {
154 ServiceRejected::find(error).is_some_and(ServiceRejected::is_session_rejected)
155 || find::<crate::OpenImServiceError>(error)
156 .is_some_and(|failure| failure.service_code == ServiceRejected::SESSION_REJECTED)
157}
158
159#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
163#[non_exhaustive]
164pub enum AccountInterrupted {
165 Stopped,
168 Transferred,
171 CredentialsSuperseded,
174}
175
176impl AccountInterrupted {
177 pub fn find(error: &anyhow::Error) -> Option<Self> {
179 find(error).copied()
180 }
181
182 pub(crate) fn because(self, message: &'static str) -> anyhow::Error {
184 anyhow::Error::new(self).context(message)
185 }
186}
187
188impl std::fmt::Display for AccountInterrupted {
189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190 f.write_str(match self {
191 Self::Stopped => "Account stopped",
192 Self::Transferred => "Account state transferred",
193 Self::CredentialsSuperseded => "Account credentials superseded",
194 })
195 }
196}
197
198impl std::error::Error for AccountInterrupted {}
199
200fn find<T: std::error::Error + Send + Sync + 'static>(error: &anyhow::Error) -> Option<&T> {
201 error
202 .downcast_ref::<T>()
203 .or_else(|| error.chain().find_map(|cause| cause.downcast_ref::<T>()))
204}
205
206#[cfg(test)]
207mod tests {
208 use super::*;
209
210 #[test]
211 fn service_rejection_keeps_its_message_and_is_found_under_context() {
212 let error = ServiceRejected::check(Service::Heartbeat, -13)
213 .unwrap_err()
214 .context("request failed")
215 .context(crate::NativeRequestNotSubmitted);
216 assert_eq!(
217 ServiceRejected::find(&error),
218 Some(&ServiceRejected::new(Service::Heartbeat, -13))
219 );
220 assert_eq!(
221 error.root_cause().to_string(),
222 "Heartbeat returned -13",
223 "the message matches the earlier untyped error"
224 );
225 assert!(ServiceRejected::check(Service::Heartbeat, 0).is_ok());
226 }
227
228 #[test]
229 fn session_rejection_depends_on_the_boundary_and_the_exact_code() {
230 for service in [
231 Service::NativeEnvelope,
232 Service::Heartbeat,
233 Service::Sync,
234 Service::Contact,
235 Service::ContactSync,
236 Service::SavedDeviceLogin,
237 Service::AccountAuthentication,
238 Service::AutomaticAuthentication,
239 ] {
240 assert!(is_session_rejected(
241 &ServiceRejected::new(service, -13).into()
242 ));
243 assert!(!is_session_rejected(
244 &ServiceRejected::new(service, -130).into()
245 ));
246 }
247 for service in [Service::CdnBootstrap, Service::Voice, Service::LoginPoll] {
248 assert!(!is_session_rejected(
249 &ServiceRejected::new(service, -13).into()
250 ));
251 }
252 assert!(is_session_rejected(
253 &anyhow::Error::new(crate::OpenImServiceError { service_code: -13 }).context("lookup")
254 ));
255 assert!(!is_session_rejected(&anyhow::anyhow!(
256 "Heartbeat returned -13"
257 )));
258 }
259
260 #[test]
261 fn interruption_reason_is_found_behind_its_message() {
262 let error = AccountInterrupted::Stopped
263 .because("Account stopped during request")
264 .context(crate::NativeRequestNotSubmitted);
265 assert_eq!(
266 AccountInterrupted::find(&error),
267 Some(AccountInterrupted::Stopped)
268 );
269 assert!(error.is::<crate::NativeRequestNotSubmitted>());
270 assert_eq!(AccountInterrupted::find(&anyhow::anyhow!("other")), None);
271 }
272}