Skip to content

Terminal interface to find, download, and stream movies, TV shows, and live TV using local media players.

fix(download): optimize stream buffer io and harden range segmentation

Samir Hossainsdb58b5918abc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 319b5e5..a5dad7d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -21,6 +21,12 @@
- **In-App Updater Streaming Timeout & Chunk Retry Recovery**:
- Removed the static 30-second total request deadline from the release binary download client in `src/updater/check.rs`, preventing mid-transfer decode aborts (`download chunk stream error: error decoding response body`) on slow or high-latency network connections.
- Added mid-stream chunk failure recovery in `src/updater/download.rs` with automatic temporary file cleanup, exponential backoff, and retry loop up to 3 attempts.
+- **Download Engine Streaming Timeout & Segment Range Resilience**:
+ - Removed the global 60-second total request deadline from the media download HTTP client in `src/net.rs` and `src/tui/app/download.rs` via `streaming_client_builder()`, preventing transfer aborts on long video downloads while maintaining a 15-second connect timeout and 30-second chunk stall detection.
+ - Relaxed range segmentation validation in `src/download.rs` to allow parallel segmented downloads on servers and CDNs that support `Range` requests without explicitly advertising `Accept-Ranges: bytes`.
+ - Added fast-fail handling in `src/download.rs` when segment workers receive `200 OK`, avoiding wasteful retries and falling back immediately to single-stream downloading.
+ - Buffered single-connection file writes in `src/download.rs` with a 256KB `tokio::io::BufWriter`, reducing syscall overhead during single-stream downloads.
+ - Sanitized download failure notices via `DownloadError::user_message()` in `src/download.rs` and `src/tui/app/download.rs`, replacing raw error dumps and URL tokens with clean, actionable status messages.
## [0.1.23] - 2026-09-21
### Fixed
diff --git a/docs/downloads.md b/docs/downloads.md
index 7afc5a2..8793864 100644
--- a/docs/downloads.md
+++ b/docs/downloads.md
@@ -11,7 +11,8 @@ and optional segmentation. Orchestration lives in `app/download.rs`.
continues from there using `Range` requests.
- **Segmentation**: files above a size threshold can be downloaded in parallel
segments (up to a capped count), then stitched.
-- **I/O Aggregation**: Download segment writers are buffered with a 256KB `tokio::io::BufWriter`, aggregating incoming 8KB–16KB HTTP response chunks into sequential disk writes and reducing filesystem syscalls by up to 96.8%.
+- **I/O Aggregation**: Download workers (both multi-segment workers and single-connection fallback) are buffered with a 256KB `tokio::io::BufWriter`, aggregating incoming HTTP response chunks into sequential disk writes and minimizing filesystem syscall overhead.
+- **Client Deadlines**: The media download client uses `streaming_client_builder()` without a global request timeout, allowing multi-gigabyte files to transfer continuously while enforcing a 15-second connect timeout and 30-second per-chunk stall detection.
- **Retries**: a failed attempt is retried a limited number of times; 30s idle
- **Cancel**: an `AtomicBool` cancel flag pauses/resumes cleanly, preserving the
partial file for a later resume.
diff --git a/src/download.rs b/src/download.rs
index ee6f52a..6b2c672 100644
--- a/src/download.rs
+++ b/src/download.rs
@@ -85,6 +85,48 @@ pub enum DownloadError {
Paused,
}
+impl DownloadError {
+ pub fn user_message(&self) -> String {
+ match self {
+ Self::Http(status) => match *status {
+ StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => {
+ format!("Server refused download (HTTP {}).", status.as_u16())
+ }
+ StatusCode::NOT_FOUND | StatusCode::GONE => {
+ "File is no longer available on server.".to_string()
+ }
+ StatusCode::TOO_MANY_REQUESTS => {
+ "Server rate limit exceeded. Try again later.".to_string()
+ }
+ other if other.is_server_error() => {
+ format!("Server error (HTTP {}). Try again later.", other.as_u16())
+ }
+ other => format!("Server returned HTTP {}.", other.as_u16()),
+ },
+ Self::Network(error) => {
+ if error.is_timeout() {
+ "Connection timed out.".to_string()
+ } else if error.is_connect() {
+ "Cannot reach download server.".to_string()
+ } else {
+ "Connection to server was lost.".to_string()
+ }
+ }
+ Self::File(error) => format!("File write error: {}.", error.kind()),
+ Self::InvalidRange(_) => "Server returned invalid partial response.".to_string(),
+ Self::Incomplete {
+ downloaded,
+ expected,
+ } => format!(
+ "Download stopped at {:.1} of {:.1} MB.",
+ *downloaded as f64 / 1_048_576.0,
+ *expected as f64 / 1_048_576.0
+ ),
+ Self::Paused => "Download paused.".to_string(),
+ }
+ }
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
struct ResumeMetadata {
etag: Option<String>,
@@ -154,7 +196,7 @@ where
.headers()
.get(ACCEPT_RANGES)
.and_then(|value| value.to_str().ok())
- .is_some_and(|value| value.eq_ignore_ascii_case("bytes"))
+ .is_none_or(|value| !value.eq_ignore_ascii_case("none"))
&& response
.content_length()
.is_some_and(|total| total >= SEGMENT_THRESHOLD)
@@ -235,11 +277,12 @@ where
metadata.segments = None;
write_metadata(&metadata_path, &metadata).await?;
- let mut file = tokio::fs::OpenOptions::new()
+ let raw_file = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&partial)
.await?;
+ let mut file = tokio::io::BufWriter::with_capacity(256 * 1024, raw_file);
let mut response = response;
let mut downloaded = offset;
let transfer_started = Instant::now();
@@ -272,7 +315,7 @@ where
}
Ok(Ok(None)) => {
file.flush().await?;
- file.sync_data().await?;
+ file.get_mut().sync_data().await?;
if let Some(expected) = metadata.total
&& downloaded != expected
{
@@ -526,10 +569,14 @@ async fn download_segment(
}
};
if response.status() != StatusCode::PARTIAL_CONTENT {
- last_error = Some(DownloadError::InvalidRange(format!(
+ let error = DownloadError::InvalidRange(format!(
"worker expected HTTP 206, received {}",
response.status()
- )));
+ ));
+ if response.status() == StatusCode::OK {
+ return Err(error);
+ }
+ last_error = Some(error);
retry_delay(attempt).await;
continue;
}
@@ -862,4 +909,42 @@ mod tests {
);
let _ = tokio::fs::remove_dir_all(&dir).await;
}
+ #[test]
+ fn test_download_error_user_message() {
+ let err_403 = DownloadError::Http(StatusCode::FORBIDDEN);
+ assert_eq!(
+ err_403.user_message(),
+ "Server refused download (HTTP 403)."
+ );
+
+ let err_404 = DownloadError::Http(StatusCode::NOT_FOUND);
+ assert_eq!(
+ err_404.user_message(),
+ "File is no longer available on server."
+ );
+
+ let err_429 = DownloadError::Http(StatusCode::TOO_MANY_REQUESTS);
+ assert_eq!(
+ err_429.user_message(),
+ "Server rate limit exceeded. Try again later."
+ );
+
+ let err_503 = DownloadError::Http(StatusCode::SERVICE_UNAVAILABLE);
+ assert_eq!(
+ err_503.user_message(),
+ "Server error (HTTP 503). Try again later."
+ );
+
+ let err_incomplete = DownloadError::Incomplete {
+ downloaded: 10 * 1024 * 1024,
+ expected: 20 * 1024 * 1024,
+ };
+ assert_eq!(
+ err_incomplete.user_message(),
+ "Download stopped at 10.0 of 20.0 MB."
+ );
+
+ let err_paused = DownloadError::Paused;
+ assert_eq!(err_paused.user_message(), "Download paused.");
+ }
}
diff --git a/src/net.rs b/src/net.rs
index c483c40..50c24a7 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -72,7 +72,7 @@ impl Resolve for FallbackResolver {
}
}
-pub fn http_client_builder() -> reqwest::ClientBuilder {
+pub fn http_client_builder_base() -> reqwest::ClientBuilder {
reqwest::Client::builder()
.dns_resolver(Arc::new(FallbackResolver::new()))
.tcp_nodelay(true)
@@ -80,7 +80,14 @@ pub fn http_client_builder() -> reqwest::ClientBuilder {
.pool_idle_timeout(Some(std::time::Duration::from_secs(90)))
.pool_max_idle_per_host(8)
.connect_timeout(std::time::Duration::from_secs(15))
- .timeout(std::time::Duration::from_secs(60))
+}
+
+pub fn http_client_builder() -> reqwest::ClientBuilder {
+ http_client_builder_base().timeout(std::time::Duration::from_secs(60))
+}
+
+pub fn streaming_client_builder() -> reqwest::ClientBuilder {
+ http_client_builder_base()
}
pub async fn probe_url(url: &str, timeout: std::time::Duration) -> bool {
diff --git a/src/tui/app/download.rs b/src/tui/app/download.rs
index 1544c9a..c9b2b93 100644
--- a/src/tui/app/download.rs
+++ b/src/tui/app/download.rs
@@ -137,7 +137,7 @@ impl App {
let sender = self.action_sender.clone();
let user_agent = self.service.client.user_agent().to_string();
- let mut client_builder = crate::net::http_client_builder()
+ let mut client_builder = crate::net::streaming_client_builder()
.connect_timeout(std::time::Duration::from_secs(15))
.tcp_keepalive(std::time::Duration::from_secs(30));
@@ -476,7 +476,13 @@ impl App {
.ok();
}
Err(error) => {
- sender.send(Action::DownloadFailed(error.to_string())).ok();
+ log::error!(
+ "download of {} failed: {error}",
+ crate::logging::sanitize_url(&link)
+ );
+ sender
+ .send(Action::DownloadFailed(error.user_message()))
+ .ok();
}
}
}