Skip to main content

wechat_protocol/
errors.rs

1//! Typed failure reasons carried inside `anyhow::Error`. Messages stay the same
2//! as before these types existed; the types let callers branch without parsing.
3use anyhow::Result;
4
5/// The response boundary that reported a non-zero service code.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7#[non_exhaustive]
8pub enum Service {
9    /// Outer response envelope of an authenticated or prelogin request.
10    NativeEnvelope,
11    /// QR challenge creation.
12    QrLogin,
13    /// Polling an issued login challenge.
14    LoginPoll,
15    /// Confirmation push for a saved device.
16    SavedDeviceLogin,
17    /// Credential exchange that completes a login.
18    AccountAuthentication,
19    /// Session renewal with saved credentials.
20    AutomaticAuthentication,
21    /// Persistent-connection heartbeat.
22    Heartbeat,
23    /// Message sync.
24    Sync,
25    /// Contact lookup.
26    Contact,
27    /// Contact catalog sync.
28    ContactSync,
29    /// Initial contact catalog.
30    ContactBootstrap,
31    /// Group member roster.
32    Room,
33    /// Group catalog page.
34    GroupMetadata,
35    /// Avatar lookup.
36    Avatar,
37    /// Voice chunk download.
38    Voice,
39    /// File upload reservation.
40    FileUploadReservation,
41    /// CDN credential bootstrap.
42    CdnBootstrap,
43    /// CDN download.
44    CdnDownload,
45    /// CDN upload.
46    CdnUpload,
47    /// Large-file upload.
48    LargeFileUpload,
49}
50
51impl Service {
52    /// Label used at the start of the error message.
53    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/// A verified response carried a non-zero service code. The request reached the
80/// service, so this error never shows that an operation was not submitted.
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
82pub struct ServiceRejected {
83    /// Response boundary that reported the code.
84    pub service: Service,
85    /// Signed code returned by that boundary.
86    pub code: i32,
87}
88
89impl ServiceRejected {
90    /// Code the session boundaries return when they no longer accept the
91    /// account's credentials.
92    pub const SESSION_REJECTED: i32 = -13;
93
94    /// Build the error for one boundary and code.
95    pub fn new(service: Service, code: i32) -> Self {
96        Self { service, code }
97    }
98
99    /// Accept code zero and reject every other code.
100    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    /// As [`Self::check`] for codes parsed as 64-bit text. A code outside the
109    /// 32-bit range keeps the same message without the type.
110    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    /// Find this error anywhere in an error and its causes.
118    pub fn find(error: &anyhow::Error) -> Option<&Self> {
119        find(error)
120    }
121
122    /// True when a session boundary returned [`Self::SESSION_REJECTED`]. The
123    /// account needs a new login or renewal; repeating the request cannot help.
124    /// The same code from another boundary, such as the CDN, is not included.
125    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
149/// True when the error shows that the service no longer accepts the account's
150/// session: a [`ServiceRejected`] for which
151/// [`ServiceRejected::is_session_rejected`] holds, or an
152/// [`OpenImServiceError`](crate::OpenImServiceError) with the same code.
153pub 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/// Why the account owner ended a request or a notification wait. This says
160/// nothing about whether bytes were sent; check
161/// [`NativeRequestNotSubmitted`](crate::NativeRequestNotSubmitted) for that.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
163#[non_exhaustive]
164pub enum AccountInterrupted {
165    /// The account was stopped, shut down or reserved for logout. A background
166    /// loop should end quietly.
167    Stopped,
168    /// The credentials were moved out with `quiesce_and_export`. This client
169    /// can no longer be used.
170    Transferred,
171    /// A renewal accepted newer credentials. Open a new notification
172    /// connection, or repeat a request that was not submitted.
173    CredentialsSuperseded,
174}
175
176impl AccountInterrupted {
177    /// Find this reason anywhere in an error and its causes.
178    pub fn find(error: &anyhow::Error) -> Option<Self> {
179        find(error).copied()
180    }
181
182    /// The typed reason with the given message shown in front of it.
183    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}