Medlar/crates/core/src/error.rs
2026-11-25 13:55:19 -06:00

398 lines
15 KiB
Rust

//! What each way to fail means: how bad it is, when it is tried again, what the user reads and can do.
//!
//! Texts are in the catalogue: `error.<name>` is what failed, `error.<name>.why` is why, `fix.<name>` is the button.
use crate::model::{ErrorKind, TaskError};
use crate::{disk, http, strings, tr};
use std::io;
use std::path::Path;
use std::time::Duration;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Severity {
/// Passes by itself.
Passing,
/// The download goes on when the user has done something.
Blocked,
/// Something is broken.
Serious,
}
/// When a failed download is tried again without being asked to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Retry {
/// After `first`, twice as long each time, at most `max`.
Later { first: Duration, max: Duration },
/// When the network is there.
Network,
/// When the folder can be written to.
Disk,
/// When the computer is awake.
Wake,
Never,
}
/// What the user can do about it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Fix {
TryAgain,
SignIn,
/// Open the network's own page.
OpenPortal,
/// From the page the link came from.
NewLink,
/// Start over, keep both or continue from a new link.
Choose,
FreeSpace,
ChangeFolder,
Restart,
Resume,
EditLink,
CheckNetwork,
}
impl Fix {
pub fn name(self) -> &'static str {
match self {
Fix::TryAgain => "try_again",
Fix::SignIn => "sign_in",
Fix::OpenPortal => "open_portal",
Fix::NewLink => "new_link",
Fix::Choose => "choose",
Fix::FreeSpace => "free_space",
Fix::ChangeFolder => "change_folder",
Fix::Restart => "restart",
Fix::Resume => "resume",
Fix::EditLink => "edit_link",
Fix::CheckNetwork => "check_network",
}
}
pub fn label(self) -> String {
strings::text(&format!("fix.{}", self.name()), &[])
}
}
const fn later(first: u64, max: u64) -> Retry {
Retry::Later { first: Duration::from_secs(first), max: Duration::from_secs(max) }
}
impl ErrorKind {
fn rules(self) -> (Severity, Retry, Fix) {
use ErrorKind::*;
use Severity::*;
match self {
Dns | Unreachable | Proxy => (Passing, later(5, 300), Fix::CheckNetwork),
Refused | Timeout | Cut => (Passing, later(5, 300), Fix::TryAgain),
Busy => (Passing, later(30, 600), Fix::TryAgain),
Server => (Passing, later(15, 600), Fix::TryAgain),
BadReply => (Passing, later(30, 600), Fix::TryAgain),
FileBusy => (Passing, later(10, 120), Fix::TryAgain),
Offline => (Passing, Retry::Network, Fix::CheckNetwork),
Portal => (Blocked, Retry::Network, Fix::OpenPortal),
Sleep => (Passing, Retry::Wake, Fix::Resume),
DiskFull => (Blocked, Retry::Disk, Fix::FreeSpace),
ReadOnly | FolderGone | DriveGone | Denied => (Blocked, Retry::Disk, Fix::ChangeFolder),
FileGone => (Blocked, Retry::Disk, Fix::Restart),
Login => (Blocked, Retry::Never, Fix::SignIn),
Forbidden | Expired | WrongContent | Link => (Blocked, Retry::Never, Fix::NewLink),
NotFound | Rejected | BadLink => (Blocked, Retry::Never, Fix::EditLink),
Changed | NoResume | Checksum => (Blocked, Retry::Never, Fix::Choose),
Killed => (Passing, Retry::Never, Fix::Resume),
Tls => (Serious, Retry::Never, Fix::TryAgain),
Disk => (Serious, later(30, 600), Fix::ChangeFolder),
List => (Serious, later(30, 600), Fix::TryAgain),
Drm => (Blocked, Retry::Never, Fix::EditLink),
Tool => (Blocked, Retry::Never, Fix::TryAgain),
Media => (Serious, Retry::Never, Fix::TryAgain),
Crashed => (Serious, Retry::Never, Fix::TryAgain),
}
}
pub fn severity(self) -> Severity {
self.rules().0
}
pub fn retry(self) -> Retry {
self.rules().1
}
pub fn fix(self) -> Fix {
self.rules().2
}
/// What failed, in a few words.
pub fn title(self) -> String {
strings::text(&format!("error.{}", self.name()), &[])
}
/// Between this computer and the server: what a network change can cure.
pub fn of_network(self) -> bool {
use ErrorKind::*;
matches!(self, Proxy | Dns | Refused | Unreachable | Timeout | Cut)
}
/// Others on the same server would fail the same way.
pub fn of_host(self) -> bool {
self.of_network() || matches!(self, ErrorKind::Busy | ErrorKind::Server)
}
}
/// Where it happened.
#[derive(Debug, Clone, Copy)]
pub struct Place<'a> {
/// Name and port.
pub server: &'a str,
pub folder: &'a Path,
/// Bytes of the file are here already.
pub begun: bool,
}
/// One failure, understood.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
pub kind: ErrorKind,
/// What failed, then why. Made of catalogue texts only, never of what the system or the server says.
pub text: String,
/// The server asked to wait.
pub retry_after: Option<Duration>,
}
impl Failure {
pub fn new(kind: ErrorKind, place: Place) -> Failure {
Failure::with_code(kind, place, 0)
}
/// With another reason than the usual one.
fn because(kind: ErrorKind, key: Option<&str>, place: Place) -> Failure {
let usual = Failure::new(kind, place);
let Some(key) = key else { return usual };
let why = strings::text(key, &[("server", &place.server)]);
Failure { text: tr!("error.full", what = kind.title(), why = why), ..usual }
}
fn with_code(kind: ErrorKind, place: Place, code: u16) -> Failure {
let server = if place.server.is_empty() { tr!("error.no_server") } else { place.server.to_string() };
let args: strings::Args = &[("server", &server), ("folder", &place.folder.display()), ("code", &code)];
let why = strings::text(&format!("error.{}.why", kind.name()), args);
Failure { kind, text: tr!("error.full", what = kind.title(), why = why), retry_after: None }
}
pub fn of(e: &http::Error, place: Place) -> Failure {
use http::Error as E;
let kind = match e {
E::Status { code: 407, .. } => return Failure::because(ErrorKind::Login, Some("error.login.proxy"), place),
E::Status { code, retry_after } => {
let failure = Failure::with_code(of_status(*code, place.begun), place, *code);
return Failure { retry_after: *retry_after, ..failure };
}
E::Link => ErrorKind::BadLink,
E::Net(e) if tls_error(e).is_some() => return Failure::because(ErrorKind::Tls, tls_why(tls_error(e)), place),
E::Net(e) => of_net(e),
E::Idle => ErrorKind::Timeout,
E::Tls(_) => ErrorKind::Tls,
E::Conn { kind, why } => return Failure::because(*kind, *why, place),
E::Proxy(None) => return Failure::because(ErrorKind::Proxy, Some("error.proxy.setting"), place),
E::Proxy(Some(e)) if proxy_login(e) => return Failure::because(ErrorKind::Login, Some("error.login.proxy"), place),
E::Proxy(Some(_)) => ErrorKind::Proxy,
E::Changed => ErrorKind::Changed,
E::Page => ErrorKind::WrongContent,
E::RangeIgnored | E::NoResume => ErrorKind::NoResume,
E::Encoded(_) | E::BadReply(_) => ErrorKind::BadReply,
// Stopped is no failure.
E::Cut { .. } | E::Stopped => ErrorKind::Cut,
E::Checksum => ErrorKind::Checksum,
E::Missing => ErrorKind::FileGone,
E::Disk(e) => of_disk(e, place.folder),
E::Store(_) => ErrorKind::List,
};
// One that is gone takes the file along.
let kind = if kind == ErrorKind::FileGone && !place.folder.is_dir() { gone(place.folder) } else { kind };
Failure::new(kind, place)
}
pub fn error(&self) -> TaskError {
TaskError { kind: Some(self.kind), detail: self.text.clone() }
}
}
fn of_status(code: u16, begun: bool) -> ErrorKind {
match code {
401 | 407 => ErrorKind::Login,
511 => ErrorKind::Portal,
403 | 410 if begun => ErrorKind::Expired,
403 => ErrorKind::Forbidden,
404 | 410 => ErrorKind::NotFound,
408 | 425 => ErrorKind::Timeout,
429 | 503 => ErrorKind::Busy,
500..=599 => ErrorKind::Server,
_ => ErrorKind::Rejected,
}
}
/// What went wrong with TLS, if that is it.
pub(crate) fn tls_error(e: &reqwest::Error) -> Option<&rustls::Error> {
causes(e).find_map(|e| e.downcast_ref())
}
/// The plain reason a certificate was refused.
pub(crate) fn tls_why(e: Option<&rustls::Error>) -> Option<&'static str> {
use rustls::CertificateError::*;
let Some(rustls::Error::InvalidCertificate(e)) = e else { return None };
Some(match e {
Expired | ExpiredContext { .. } => "error.tls.expired",
NotValidYet | NotValidYetContext { .. } => "error.tls.not_yet",
UnknownIssuer => "error.tls.unknown",
NotValidForName | NotValidForNameContext { .. } => "error.tls.name",
Revoked => "error.tls.revoked",
// Self-signed ones, mostly.
Other(e) if e.to_string().contains("CaUsedAsEndEntity") => "error.tls.unknown",
_ => return None,
})
}
/// hyper's types for it are private.
fn proxy_login(e: &reqwest::Error) -> bool {
causes(e).any(|e| proxy_wants_login(&e.to_string()))
}
pub(crate) fn proxy_wants_login(text: &str) -> bool {
let known = ["proxy authorization required", "credentials not accepted", "does not support user/pass", "implements authentication incorrectly"];
known.iter().any(|k| text.contains(k))
}
/// The error and all that led to it.
fn causes(e: &reqwest::Error) -> impl Iterator<Item = &(dyn std::error::Error + 'static)> {
std::iter::successors(Some(e as &(dyn std::error::Error + 'static)), |e| {
// An io::Error's source skips what it wraps.
let wrapped = e.downcast_ref::<io::Error>().and_then(|e| e.get_ref());
wrapped.map(|e| e as &(dyn std::error::Error + 'static)).or_else(|| e.source())
})
}
fn of_net(e: &reqwest::Error) -> ErrorKind {
if e.is_redirect() || e.is_builder() {
return ErrorKind::BadLink;
}
for e in causes(e) {
if let Some(io) = e.downcast_ref::<io::Error>() {
match io.kind() {
io::ErrorKind::ConnectionRefused => return ErrorKind::Refused,
io::ErrorKind::HostUnreachable | io::ErrorKind::NetworkUnreachable | io::ErrorKind::NetworkDown => return ErrorKind::Unreachable,
io::ErrorKind::TimedOut => return ErrorKind::Timeout,
_ => {}
}
}
// hyper's type for it is private.
if e.to_string().starts_with("dns error") {
return ErrorKind::Dns;
}
}
if e.is_timeout() { ErrorKind::Timeout } else { ErrorKind::Cut }
}
fn of_disk(e: &disk::Error, folder: &Path) -> ErrorKind {
let io = match e {
disk::Error::NoSpace { .. } => return ErrorKind::DiskFull,
disk::Error::Busy => return ErrorKind::FileBusy,
disk::Error::Io(e) => e,
};
match io.kind() {
io::ErrorKind::StorageFull | io::ErrorKind::QuotaExceeded => ErrorKind::DiskFull,
io::ErrorKind::ReadOnlyFilesystem => ErrorKind::ReadOnly,
_ if !folder.is_dir() && (io.kind() != io::ErrorKind::PermissionDenied || removable(folder)) => gone(folder),
io::ErrorKind::PermissionDenied => ErrorKind::Denied,
io::ErrorKind::NotFound => ErrorKind::FileGone,
_ => ErrorKind::Disk,
}
}
fn gone(folder: &Path) -> ErrorKind {
if removable(folder) { ErrorKind::DriveGone } else { ErrorKind::FolderGone }
}
fn removable(folder: &Path) -> bool {
["/run/media", "/media", "/mnt"].iter().any(|p| folder.starts_with(p))
}
#[cfg(test)]
mod tests {
use super::*;
fn here() -> Place<'static> {
Place { server: "files.example", folder: Path::new("/"), begun: false }
}
#[test]
fn every_kind_has_a_rule_words_and_a_fix() {
for &kind in ErrorKind::ALL {
let (severity, retry, fix) = (kind.severity(), kind.retry(), kind.fix());
// What passes is tried again by itself, except what the user turned off.
assert!(severity != Severity::Passing || retry != Retry::Never || kind == ErrorKind::Killed, "{kind:?}");
let failure = Failure::new(kind, here());
let why = strings::text(&format!("error.{}.why", kind.name()), &[]);
for text in [kind.title(), why, fix.label(), failure.text.clone()] {
assert!(text.len() > 3 && !text.starts_with("error.") && !text.starts_with("fix."), "{kind:?}: {text}");
}
assert!(failure.text.starts_with(&kind.title()) && !failure.text.contains(['{', '}']), "{}", failure.text);
}
}
#[test]
fn no_raw_text_gets_through() {
let raw = "raw (os error 99) Some(\"x\")";
let io = |kind| http::Error::Disk(disk::Error::Io(io::Error::new(kind, raw)));
let all = [
(io(io::ErrorKind::StorageFull), ErrorKind::DiskFull),
(io(io::ErrorKind::ReadOnlyFilesystem), ErrorKind::ReadOnly),
(io(io::ErrorKind::PermissionDenied), ErrorKind::Denied),
(io(io::ErrorKind::NotFound), ErrorKind::FileGone),
(io(io::ErrorKind::Other), ErrorKind::Disk),
(http::Error::Disk(disk::Error::Busy), ErrorKind::FileBusy),
(http::Error::Disk(disk::Error::NoSpace { need: 2, free: 1 }), ErrorKind::DiskFull),
(http::Error::Encoded(raw.into()), ErrorKind::BadReply),
(http::Error::BadReply(raw.into()), ErrorKind::BadReply),
(http::Error::Store(crate::store::Error::BadValue(raw.into())), ErrorKind::List),
(http::Error::Cut { got: 1, expected: None }, ErrorKind::Cut),
(http::Error::Changed, ErrorKind::Changed),
(http::Error::Page, ErrorKind::WrongContent),
(http::Error::NoResume, ErrorKind::NoResume),
(http::Error::Link, ErrorKind::BadLink),
(http::Error::Idle, ErrorKind::Timeout),
];
for (e, kind) in all {
let failure = Failure::of(&e, here());
assert_eq!(failure.kind, kind);
assert!(!failure.text.contains("raw") && !failure.text.contains("os error"), "{}", failure.text);
}
}
#[test]
fn statuses() {
use ErrorKind::*;
for (code, fresh, begun) in [
(401, Login, Login),
(403, Forbidden, Expired),
(404, NotFound, NotFound),
(410, NotFound, Expired),
(418, Rejected, Rejected),
(429, Busy, Busy),
(500, Server, Server),
(503, Busy, Busy),
] {
assert_eq!((of_status(code, false), of_status(code, true)), (fresh, begun), "{code}");
}
// Asking again would change nothing.
for kind in [NotFound, Expired, Forbidden, Login, Changed] {
assert_eq!(kind.retry(), Retry::Never);
}
}
#[test]
fn a_gone_folder_is_told_from_a_gone_drive() {
let gone = |folder: &str| Failure::of(&http::Error::Missing, Place { folder: Path::new(folder), ..here() }).kind;
assert_eq!(gone("/"), ErrorKind::FileGone);
assert_eq!(gone("/no/such/folder"), ErrorKind::FolderGone);
assert_eq!(gone("/run/media/nobody/stick/no"), ErrorKind::DriveGone);
}
}