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    /// H5 ticket request for Channels post lookups.
50    ChannelsAuthorization,
51    /// Authenticated page address for a Channels post.
52    ChannelsPage,
53    /// The H5 transfer proxy that carries Channels requests.
54    Channels,
55    /// The Channels post detail request carried by the proxy.
56    ChannelsDetail,
57}
58
59impl Service {
60    /// Label used at the start of the error message.
61    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/// A verified response carried a non-zero service code. The request reached the
92/// service, so this error never shows that an operation was not submitted.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub struct ServiceRejected {
95    /// Response boundary that reported the code.
96    pub service: Service,
97    /// Signed code returned by that boundary.
98    pub code: i32,
99}
100
101impl ServiceRejected {
102    /// Code the session boundaries return when they no longer accept the
103    /// account's credentials.
104    pub const SESSION_REJECTED: i32 = -13;
105
106    /// Build the error for one boundary and code.
107    pub fn new(service: Service, code: i32) -> Self {
108        Self { service, code }
109    }
110
111    /// Accept code zero and reject every other code.
112    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    /// As [`Self::check`] for codes parsed as 64-bit text. A code outside the
121    /// 32-bit range keeps the same message without the type.
122    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    /// Find this error anywhere in an error and its causes.
130    pub fn find(error: &anyhow::Error) -> Option<&Self> {
131        find(error)
132    }
133
134    /// True when a session boundary returned [`Self::SESSION_REJECTED`]. The
135    /// account needs a new login or renewal; repeating the request cannot help.
136    /// The same code from another boundary, such as the CDN, is not included.
137    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
161/// True when the error shows that the service no longer accepts the account's
162/// session: a [`ServiceRejected`] for which
163/// [`ServiceRejected::is_session_rejected`] holds, or an
164/// [`OpenImServiceError`](crate::OpenImServiceError) with the same code.
165pub 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/// Why the account owner ended a request or a notification wait. This says
172/// nothing about whether bytes were sent; check
173/// [`NativeRequestNotSubmitted`](crate::NativeRequestNotSubmitted) for that.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
175#[non_exhaustive]
176pub enum AccountInterrupted {
177    /// The account was stopped, shut down or reserved for logout. A background
178    /// loop should end quietly.
179    Stopped,
180    /// The credentials were moved out with `quiesce_and_export`. This client
181    /// can no longer be used.
182    Transferred,
183    /// A renewal accepted newer credentials. Open a new notification
184    /// connection, or repeat a request that was not submitted.
185    CredentialsSuperseded,
186}
187
188impl AccountInterrupted {
189    /// Find this reason anywhere in an error and its causes.
190    pub fn find(error: &anyhow::Error) -> Option<Self> {
191        find(error).copied()
192    }
193
194    /// The typed reason with the given message shown in front of it.
195    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}