S007: error kinds with rules, words and fixes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
parent
e0ee812160
commit
44b0ff9105
9 changed files with 515 additions and 6 deletions
|
|
@ -11,7 +11,7 @@ Every failure is understood, explained, retried sensibly, and never costs finish
|
|||
- crates/core/src/{manager,http,segment,disk}*
|
||||
|
||||
## Steps
|
||||
- [ ] Error kinds from 1.17, each with severity, retry rule, plain message (what failed, then why) and fix action; a test asserts every kind has all four and no raw OS text leaks
|
||||
- [x] Error kinds from 1.17, each with severity, retry rule, plain message (what failed, then why) and fix action; a test asserts every kind has all four and no raw OS text leaks
|
||||
- [ ] Retry engine: backoff per kind, per-host circuit breaker, limits per task and "retry forever" option, time until next try in the snapshot
|
||||
- [ ] Network state through NetworkManager D-Bus with a fallback: offline waits instead of failing, resumes on return; captive portal (HTML in place of a file) detected
|
||||
- [ ] Sleep and wake through logind `PrepareForSleep`: pause cleanly, resume after
|
||||
|
|
|
|||
|
|
@ -69,6 +69,87 @@
|
|||
"log.moved": "Moved to {folder}",
|
||||
"log.renamed": "Renamed to {name}",
|
||||
|
||||
"error.dns": "Server not found",
|
||||
"error.dns.why": "The name {server} could not be looked up. It may be misspelled, or the name service is not answering.",
|
||||
"error.tls": "Secure connection failed",
|
||||
"error.tls.why": "{server} could not prove who it is, so nothing was downloaded from it. Its certificate may be expired, or this computer's clock wrong.",
|
||||
"error.refused": "Connection refused",
|
||||
"error.refused.why": "{server} did not accept the connection. It may be down, or blocked by a firewall.",
|
||||
"error.unreachable": "Server out of reach",
|
||||
"error.unreachable.why": "There is no way to {server} through this network.",
|
||||
"error.timeout": "Server does not answer",
|
||||
"error.timeout.why": "{server} took too long to answer.",
|
||||
"error.cut": "Connection lost",
|
||||
"error.cut.why": "The connection to {server} ended before the file was complete.",
|
||||
"error.offline": "No network",
|
||||
"error.offline.why": "This computer is not connected. The download goes on when the network is back.",
|
||||
"error.portal": "Network needs a sign-in",
|
||||
"error.portal.why": "This network wants you to sign in on its web page first. The download goes on after that.",
|
||||
"error.login": "Login needed",
|
||||
"error.login.why": "{server} wants a user name and password.",
|
||||
"error.forbidden": "Access denied",
|
||||
"error.forbidden.why": "{server} refused to give out the file (status {code}). The link may need the page it came from.",
|
||||
"error.expired": "Link expired",
|
||||
"error.expired.why": "{server} gave out the file before but refuses now (status {code}). A new link for the same file continues the download.",
|
||||
"error.not_found": "File not found",
|
||||
"error.not_found.why": "{server} has no file at this link (status {code}).",
|
||||
"error.rejected": "Request rejected",
|
||||
"error.rejected.why": "{server} did not accept the request (status {code}).",
|
||||
"error.busy": "Server is busy",
|
||||
"error.busy.why": "{server} has too many requests right now (status {code}).",
|
||||
"error.server": "Server error",
|
||||
"error.server.why": "{server} had a problem of its own (status {code}).",
|
||||
"error.bad_reply": "Wrong answer from the server",
|
||||
"error.bad_reply.why": "{server} contradicted itself about the file, so nothing from that answer was used.",
|
||||
"error.bad_link": "Link can't be used",
|
||||
"error.bad_link.why": "The link is not a web address Medlar can open, or it leads back to itself.",
|
||||
"error.changed": "File changed on the server",
|
||||
"error.changed.why": "{server} now has another version of the file. What is here was kept; the two are never mixed.",
|
||||
"error.wrong_content": "Not the file",
|
||||
"error.wrong_content.why": "{server} sent a web page instead of the file. The link may be old, or need a login.",
|
||||
"error.no_resume": "Can't be continued",
|
||||
"error.no_resume.why": "{server} no longer sends the rest of a file, only all of it. What is here was kept.",
|
||||
"error.disk_full": "Disk is full",
|
||||
"error.disk_full.why": "There is not enough space in {folder}. The download goes on when there is.",
|
||||
"error.read_only": "Disk is read-only",
|
||||
"error.read_only.why": "Nothing can be written to {folder}. The download goes on when it can.",
|
||||
"error.folder_gone": "Folder is gone",
|
||||
"error.folder_gone.why": "{folder} does not exist any more. The download goes on when it is back.",
|
||||
"error.drive_gone": "Drive is gone",
|
||||
"error.drive_gone.why": "The drive with {folder} is not connected. The download goes on when it is back.",
|
||||
"error.file_gone": "Unfinished file is gone",
|
||||
"error.file_gone.why": "The started file is no longer in {folder}. The download goes on if it comes back, or can start over.",
|
||||
"error.denied": "No permission",
|
||||
"error.denied.why": "You are not allowed to write to {folder}. The download goes on when you are.",
|
||||
"error.file_busy": "File in use",
|
||||
"error.file_busy.why": "Another program is writing this file in {folder}.",
|
||||
"error.disk": "Disk error",
|
||||
"error.disk.why": "The disk with {folder} reported an error.",
|
||||
"error.list": "Download list not saved",
|
||||
"error.list.why": "The download list could not be written, so the download stopped to stay safe. Its disk may be full.",
|
||||
"error.sleep": "Computer sleeps",
|
||||
"error.sleep.why": "The download goes on when the computer wakes up.",
|
||||
"error.killed": "Interrupted",
|
||||
"error.killed.why": "Medlar ended while this was downloading. What was downloaded is safe.",
|
||||
"error.crashed": "Medlar made a mistake",
|
||||
"error.crashed.why": "This download stopped because of an error inside Medlar. What was downloaded is safe.",
|
||||
|
||||
"fix.try_again": "Try again",
|
||||
"fix.sign_in": "Sign in",
|
||||
"fix.open_portal": "Open sign-in page",
|
||||
"fix.new_link": "Get new link",
|
||||
"fix.choose": "Choose",
|
||||
"fix.free_space": "Free up space",
|
||||
"fix.change_folder": "Change folder",
|
||||
"fix.restart": "Start over",
|
||||
"fix.resume": "Resume",
|
||||
"fix.edit_link": "Edit link",
|
||||
"fix.check_network": "Network settings",
|
||||
|
||||
"error.full": "{what}. {why}",
|
||||
"error.no_server": "The server",
|
||||
"log.retry": {"one": "Next try in {n} second", "other": "Next try in {n} seconds"},
|
||||
|
||||
"dialog.cancel": "Cancel",
|
||||
"dialog.close": "Close",
|
||||
"toast.undo": "Undo",
|
||||
|
|
|
|||
344
crates/core/src/error.rs
Normal file
344
crates/core/src/error.rs
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
//! 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 => (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 => (Blocked, Retry::Never, Fix::NewLink),
|
||||
NotFound | Rejected | BadLink => (Blocked, Retry::Never, Fix::EditLink),
|
||||
Changed | NoResume => (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),
|
||||
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, 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)
|
||||
}
|
||||
|
||||
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, 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) => of_net(e),
|
||||
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::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,
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
fn of_net(e: &reqwest::Error) -> ErrorKind {
|
||||
if e.is_redirect() || e.is_builder() {
|
||||
return ErrorKind::BadLink;
|
||||
}
|
||||
let mut source: Option<&(dyn std::error::Error + 'static)> = Some(e);
|
||||
while let Some(e) = source {
|
||||
if e.is::<rustls::Error>() {
|
||||
return ErrorKind::Tls;
|
||||
}
|
||||
if let Some(io) = e.downcast_ref::<io::Error>() {
|
||||
if io.get_ref().is_some_and(|e| e.is::<rustls::Error>()) {
|
||||
return ErrorKind::Tls;
|
||||
}
|
||||
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;
|
||||
}
|
||||
source = e.source();
|
||||
}
|
||||
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),
|
||||
];
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -81,8 +81,15 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt
|
|||
}
|
||||
}
|
||||
}
|
||||
// Its drive may come back; starting over is the user's to decide.
|
||||
if file.is_none() && parts.iter().any(|p| p.done > 0) {
|
||||
return Err(Error::Missing);
|
||||
}
|
||||
|
||||
let mut probe = probe(client, &source, &mut stop).await?;
|
||||
if is_page(&task, &source, &probe) {
|
||||
return Err(Error::Page);
|
||||
}
|
||||
let body = probe.body.take();
|
||||
let link = Link { client: client.clone(), source: source.at(&probe.url), ranges: probe.ranges, version: probe.version.clone() };
|
||||
let (file, parts) = match file {
|
||||
|
|
@ -113,6 +120,14 @@ pub async fn download(shared: &Shared, id: TaskId, source: Source, options: &Opt
|
|||
job.finish(file, size).await
|
||||
}
|
||||
|
||||
/// The server sent a web page, and the task is for something else.
|
||||
fn is_page(task: &Task, source: &Source, probe: &Probe) -> bool {
|
||||
let mime = probe.mime.as_deref();
|
||||
let names = [Some(task.name.clone()).filter(|n| !n.is_empty()), name::from_url(&source.url)];
|
||||
let was_page = task.mime.as_deref().is_some_and(|m| page(Some(m)));
|
||||
page(mime) && !was_page && (task.mime.is_some() || names.iter().flatten().any(|n| page_instead(mime, n)))
|
||||
}
|
||||
|
||||
fn finished(p: &Part) -> bool {
|
||||
p.end == Some(p.start + p.done)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -128,12 +128,17 @@ async fn send_range(link: &Link, first: u64, end: Option<u64>, stop: &mut Stop)
|
|||
Ok(response)
|
||||
}
|
||||
StatusCode::OK if link.version.same_file(&Validators::of(headers, content_length(headers))) => Err(Error::RangeIgnored),
|
||||
StatusCode::OK if comes_as_page(link, headers) => Err(Error::Page),
|
||||
StatusCode::OK => Err(Error::Changed),
|
||||
StatusCode::RANGE_NOT_SATISFIABLE if unsatisfied_total(headers).is_some_and(|t| link.version.size != Some(t)) => Err(Error::Changed),
|
||||
_ => Err(status_error(&response)),
|
||||
}
|
||||
}
|
||||
|
||||
fn comes_as_page(link: &Link, headers: &HeaderMap) -> bool {
|
||||
name::from_url(&link.source.url).is_some_and(|n| page_instead(name::mime(headers).as_deref(), &n))
|
||||
}
|
||||
|
||||
async fn whole(link: &Link, part: &LivePart, body: Option<Response>, stop: &mut Stop) -> Result<Response> {
|
||||
if part.get() != (crate::model::Part { start: 0, end: None, done: 0 }) {
|
||||
return Err(Error::NoResume);
|
||||
|
|
@ -150,7 +155,7 @@ async fn whole(link: &Link, part: &LivePart, body: Option<Response>, stop: &mut
|
|||
}
|
||||
check_encoding(headers, response.url())?;
|
||||
if !link.version.same_file(&Validators::of(headers, content_length(headers))) {
|
||||
return Err(Error::Changed);
|
||||
return Err(if comes_as_page(link, headers) { Error::Page } else { Error::Changed });
|
||||
}
|
||||
Ok(response)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ use std::time::Duration;
|
|||
use tokio::sync::watch;
|
||||
use url::Url;
|
||||
|
||||
/// Why a download stopped. Plain words for the user come with the error kinds (S007).
|
||||
/// Why a download stopped. `error::Failure` has the words for the user.
|
||||
#[derive(Debug)]
|
||||
pub enum Error {
|
||||
/// Asked to stop.
|
||||
|
|
@ -33,6 +33,8 @@ pub enum Error {
|
|||
Status { code: u16, retry_after: Option<Duration> },
|
||||
/// The file on the server is not the one the parts came from.
|
||||
Changed,
|
||||
/// A web page came in place of the file.
|
||||
Page,
|
||||
/// A range was asked for and the whole file came.
|
||||
RangeIgnored,
|
||||
/// Finished bytes are on disk and the server can't continue from them.
|
||||
|
|
@ -43,6 +45,8 @@ pub enum Error {
|
|||
BadReply(String),
|
||||
/// The connection ended early.
|
||||
Cut { got: u64, expected: Option<u64> },
|
||||
/// Finished bytes are recorded, but their file is gone.
|
||||
Missing,
|
||||
Disk(disk::Error),
|
||||
Store(store::Error),
|
||||
}
|
||||
|
|
@ -237,6 +241,16 @@ fn check_encoding(headers: &HeaderMap, url: &Url) -> Result<()> {
|
|||
}
|
||||
}
|
||||
|
||||
/// A web page, where `name` promises another kind of file.
|
||||
fn page_instead(mime: Option<&str>, name: &str) -> bool {
|
||||
let Some(ext) = name::split(name).1 else { return false };
|
||||
page(mime) && name::is_file_type(ext) && !ext.eq_ignore_ascii_case("html")
|
||||
}
|
||||
|
||||
fn page(mime: Option<&str>) -> bool {
|
||||
matches!(mime, Some("text/html" | "application/xhtml+xml"))
|
||||
}
|
||||
|
||||
/// What tells one version of a file from another.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Validators {
|
||||
|
|
@ -316,6 +330,15 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pages_in_place_of_files() {
|
||||
let html = Some("text/html");
|
||||
assert!(page_instead(html, "a.ZIP") && page_instead(html, "a.tar.gz") && page_instead(html, "x.iso"));
|
||||
for (mime, name) in [(html, "a.html"), (html, "a.php"), (html, "file"), (html, "v1.2"), (Some("application/zip"), "a.zip"), (None, "a.zip")] {
|
||||
assert!(!page_instead(mime, name), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn versions() {
|
||||
let v = |size, etag: Option<&str>, lm: Option<&str>| Validators {
|
||||
|
|
|
|||
|
|
@ -96,7 +96,14 @@ fn extension_of(mime: &str) -> Option<&'static str> {
|
|||
TYPES.iter().find(|(m, _)| *m == mime).map(|(_, e)| *e)
|
||||
}
|
||||
|
||||
fn from_url(url: &Url) -> Option<String> {
|
||||
/// The extension stands for a kind of file that Medlar knows.
|
||||
pub(super) fn is_file_type(ext: &str) -> bool {
|
||||
let ext = ext.to_lowercase();
|
||||
let more = ["appimage", "bin", "dmg", "exe", "img", "jar", "msi", "torrent"];
|
||||
TYPES.iter().any(|(_, e)| *e == ext) || more.contains(&ext.as_str())
|
||||
}
|
||||
|
||||
pub(super) fn from_url(url: &Url) -> Option<String> {
|
||||
let last = url.path_segments()?.rfind(|s| !s.is_empty())?;
|
||||
// Decoded only here, so `%2F` can't become a path: `safe` sees it.
|
||||
safe(&percent_decode_str(last).decode_utf8_lossy())
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
|
||||
pub mod adapt;
|
||||
pub mod disk;
|
||||
pub mod error;
|
||||
pub mod events;
|
||||
pub mod host;
|
||||
pub mod http;
|
||||
|
|
|
|||
|
|
@ -93,8 +93,41 @@ named_enum!(
|
|||
);
|
||||
|
||||
named_enum!(
|
||||
/// Why a task failed. Filled by S007; each kind has a label under `error.<name>`.
|
||||
ErrorKind {}
|
||||
/// Why a task failed or waits. What each means is in `error`; the label is under `error.<name>`.
|
||||
ErrorKind {
|
||||
Dns = "dns",
|
||||
Tls = "tls",
|
||||
Refused = "refused",
|
||||
Unreachable = "unreachable",
|
||||
Timeout = "timeout",
|
||||
Cut = "cut",
|
||||
Offline = "offline",
|
||||
Portal = "portal",
|
||||
Login = "login",
|
||||
Forbidden = "forbidden",
|
||||
Expired = "expired",
|
||||
NotFound = "not_found",
|
||||
Rejected = "rejected",
|
||||
Busy = "busy",
|
||||
Server = "server",
|
||||
BadReply = "bad_reply",
|
||||
BadLink = "bad_link",
|
||||
Changed = "changed",
|
||||
WrongContent = "wrong_content",
|
||||
NoResume = "no_resume",
|
||||
DiskFull = "disk_full",
|
||||
ReadOnly = "read_only",
|
||||
FolderGone = "folder_gone",
|
||||
DriveGone = "drive_gone",
|
||||
FileGone = "file_gone",
|
||||
Denied = "denied",
|
||||
FileBusy = "file_busy",
|
||||
Disk = "disk",
|
||||
List = "list",
|
||||
Sleep = "sleep",
|
||||
Killed = "killed",
|
||||
Crashed = "crashed",
|
||||
}
|
||||
);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
|
|
|
|||
Loading…
Reference in a new issue