use anyhow::Result;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Service {
NativeEnvelope,
QrLogin,
LoginPoll,
SavedDeviceLogin,
AccountAuthentication,
AutomaticAuthentication,
Heartbeat,
Sync,
Contact,
ContactSync,
ContactBootstrap,
Room,
GroupMetadata,
Avatar,
Voice,
FileUploadReservation,
CdnBootstrap,
CdnDownload,
CdnUpload,
LargeFileUpload,
}
impl Service {
pub fn label(self) -> &'static str {
match self {
Self::NativeEnvelope => "Native envelope",
Self::QrLogin => "QR service",
Self::LoginPoll => "Login poll",
Self::SavedDeviceLogin => "Saved-device login",
Self::AccountAuthentication => "Account authentication",
Self::AutomaticAuthentication => "Automatic authentication",
Self::Heartbeat => "Heartbeat",
Self::Sync => "Sync service",
Self::Contact => "Contact service",
Self::ContactSync => "Contact sync service",
Self::ContactBootstrap => "Contact bootstrap",
Self::Room => "Room service",
Self::GroupMetadata => "Group metadata service",
Self::Avatar => "Avatar service",
Self::Voice => "Voice service",
Self::FileUploadReservation => "File upload reservation",
Self::CdnBootstrap => "CDN bootstrap",
Self::CdnDownload => "CDN download",
Self::CdnUpload => "CDN upload",
Self::LargeFileUpload => "Large-file upload",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ServiceRejected {
pub service: Service,
pub code: i32,
}
impl ServiceRejected {
pub const SESSION_REJECTED: i32 = -13;
pub fn new(service: Service, code: i32) -> Self {
Self { service, code }
}
pub(crate) fn check(service: Service, code: i32) -> Result<()> {
if code == 0 {
Ok(())
} else {
Err(Self { service, code }.into())
}
}
pub(crate) fn check_wide(service: Service, code: i64) -> Result<()> {
match i32::try_from(code) {
Ok(code) => Self::check(service, code),
Err(_) => Err(anyhow::anyhow!("{} returned {code}", service.label())),
}
}
pub fn find(error: &anyhow::Error) -> Option<&Self> {
find(error)
}
pub fn is_session_rejected(&self) -> bool {
self.code == Self::SESSION_REJECTED
&& matches!(
self.service,
Service::NativeEnvelope
| Service::Heartbeat
| Service::Sync
| Service::Contact
| Service::ContactSync
| Service::SavedDeviceLogin
| Service::AccountAuthentication
| Service::AutomaticAuthentication
)
}
}
impl std::fmt::Display for ServiceRejected {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} returned {}", self.service.label(), self.code)
}
}
impl std::error::Error for ServiceRejected {}
pub fn is_session_rejected(error: &anyhow::Error) -> bool {
ServiceRejected::find(error).is_some_and(ServiceRejected::is_session_rejected)
|| find::<crate::OpenImServiceError>(error)
.is_some_and(|failure| failure.service_code == ServiceRejected::SESSION_REJECTED)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AccountInterrupted {
Stopped,
Transferred,
CredentialsSuperseded,
}
impl AccountInterrupted {
pub fn find(error: &anyhow::Error) -> Option<Self> {
find(error).copied()
}
pub(crate) fn because(self, message: &'static str) -> anyhow::Error {
anyhow::Error::new(self).context(message)
}
}
impl std::fmt::Display for AccountInterrupted {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Stopped => "Account stopped",
Self::Transferred => "Account state transferred",
Self::CredentialsSuperseded => "Account credentials superseded",
})
}
}
impl std::error::Error for AccountInterrupted {}
fn find<T: std::error::Error + Send + Sync + 'static>(error: &anyhow::Error) -> Option<&T> {
error
.downcast_ref::<T>()
.or_else(|| error.chain().find_map(|cause| cause.downcast_ref::<T>()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn service_rejection_keeps_its_message_and_is_found_under_context() {
let error = ServiceRejected::check(Service::Heartbeat, -13)
.unwrap_err()
.context("request failed")
.context(crate::NativeRequestNotSubmitted);
assert_eq!(
ServiceRejected::find(&error),
Some(&ServiceRejected::new(Service::Heartbeat, -13))
);
assert_eq!(
error.root_cause().to_string(),
"Heartbeat returned -13",
"the message matches the earlier untyped error"
);
assert!(ServiceRejected::check(Service::Heartbeat, 0).is_ok());
}
#[test]
fn session_rejection_depends_on_the_boundary_and_the_exact_code() {
for service in [
Service::NativeEnvelope,
Service::Heartbeat,
Service::Sync,
Service::Contact,
Service::ContactSync,
Service::SavedDeviceLogin,
Service::AccountAuthentication,
Service::AutomaticAuthentication,
] {
assert!(is_session_rejected(
&ServiceRejected::new(service, -13).into()
));
assert!(!is_session_rejected(
&ServiceRejected::new(service, -130).into()
));
}
for service in [Service::CdnBootstrap, Service::Voice, Service::LoginPoll] {
assert!(!is_session_rejected(
&ServiceRejected::new(service, -13).into()
));
}
assert!(is_session_rejected(
&anyhow::Error::new(crate::OpenImServiceError { service_code: -13 }).context("lookup")
));
assert!(!is_session_rejected(&anyhow::anyhow!(
"Heartbeat returned -13"
)));
}
#[test]
fn interruption_reason_is_found_behind_its_message() {
let error = AccountInterrupted::Stopped
.because("Account stopped during request")
.context(crate::NativeRequestNotSubmitted);
assert_eq!(
AccountInterrupted::find(&error),
Some(AccountInterrupted::Stopped)
);
assert!(error.is::<crate::NativeRequestNotSubmitted>());
assert_eq!(AccountInterrupted::find(&anyhow::anyhow!("other")), None);
}
}