diff --git a/src/app.rs b/src/app.rs index 3496e6b..00bca5d 100644 --- a/src/app.rs +++ b/src/app.rs @@ -341,6 +341,9 @@ impl App { WorkerEventKind::Segment(s) => self.on_segment(s), WorkerEventKind::Done => self.on_done(), WorkerEventKind::Cancelled => self.on_cancelled(), + WorkerEventKind::CancelledWithWarning(message) => { + self.on_cancelled_with_warning(message) + } WorkerEventKind::Error(e) => self.on_error(e), } true @@ -467,6 +470,12 @@ impl App { )); } + pub fn on_cancelled_with_warning(&mut self, message: String) { + self.on_cancelled(); + self.set_message(format!("cancelled, but cleanup failed: {message}")); + self.overlay = Overlay::Message; + } + pub fn on_error(&mut self, message: String) { self.settle_pause(); self.status = Status::Error; diff --git a/src/doctor.rs b/src/doctor.rs index 0ddeb82..2ee330b 100644 --- a/src/doctor.rs +++ b/src/doctor.rs @@ -26,18 +26,36 @@ struct Row { } fn cache_status(cache: &std::path::Path) -> (Verdict, &'static str) { - if cache.is_dir() { - (Verdict::Ok, "directory exists; write access not tested") - } else if cache.exists() { - (Verdict::Fail, "path exists but is not a directory") - } else if cache.parent().is_some_and(std::path::Path::is_dir) { - ( - Verdict::Warn, - "will be created on first download; write access not tested", - ) + let cache = if cache.is_absolute() { + cache.to_path_buf() } else { - (Verdict::Fail, "parent directory is missing") + match std::env::current_dir() { + Ok(current) => current.join(cache), + Err(_) => return (Verdict::Fail, "cannot resolve relative cache path"), + } + }; + if cache.is_dir() { + return (Verdict::Ok, "directory exists; write access not tested"); + } + match std::fs::symlink_metadata(&cache) { + Ok(_) => return (Verdict::Fail, "path exists but is not a usable directory"), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return (Verdict::Fail, "cannot inspect cache path"), } + for ancestor in cache.ancestors().skip(1) { + match std::fs::symlink_metadata(ancestor) { + Ok(metadata) if metadata.is_dir() || ancestor.is_dir() => { + return ( + Verdict::Warn, + "will be created on first download; write access not tested", + ); + } + Ok(_) => return (Verdict::Fail, "an ancestor is not a directory"), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(_) => return (Verdict::Fail, "cannot inspect cache path"), + } + } + (Verdict::Fail, "no existing parent directory") } fn version(binary: &std::path::Path, args: &[&str]) -> Option { @@ -313,11 +331,95 @@ mod tests { std::fs::write(&cache, b"not a directory").unwrap(); assert_eq!( cache_status(&cache), - (Verdict::Fail, "path exists but is not a directory") + (Verdict::Fail, "path exists but is not a usable directory") + ); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn cache_status_rejects_uninspectable_cache_paths() { + let dir = std::env::temp_dir().join(format!( + "scribe-doctor-uninspectable-{}", + std::process::id() + )); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let parent = dir.join("not-a-directory"); + std::fs::write(&parent, b"x").unwrap(); + let cache = parent.join("models"); + assert_eq!( + cache_status(&cache), + (Verdict::Fail, "cannot inspect cache path") + ); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn cache_status_rejects_dangling_symlinks() { + use std::os::unix::fs::symlink; + let dir = std::env::temp_dir().join(format!("scribe-doctor-link-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let cache = dir.join("models"); + symlink(dir.join("missing"), &cache).unwrap(); + assert_eq!( + cache_status(&cache), + (Verdict::Fail, "path exists but is not a usable directory") + ); + std::fs::remove_file(&cache).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn cache_status_accepts_relative_missing_paths() { + let cache = std::path::PathBuf::from(format!( + "scribe-doctor-relative-{}/nested/models", + std::process::id() + )); + assert_eq!( + cache_status(&cache), + ( + Verdict::Warn, + "will be created on first download; write access not tested" + ) + ); + } + + #[cfg(unix)] + #[test] + fn cache_status_accepts_symlinked_directory_ancestors() { + use std::os::unix::fs::symlink; + let dir = + std::env::temp_dir().join(format!("scribe-doctor-symlink-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(dir.join("target")).unwrap(); + symlink(dir.join("target"), dir.join("linked")).unwrap(); + let cache = dir.join("linked").join("nested").join("models"); + assert_eq!( + cache_status(&cache), + ( + Verdict::Warn, + "will be created on first download; write access not tested" + ) ); std::fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn cache_status_accepts_missing_parent_trees() { + let dir = std::env::temp_dir().join(format!("scribe-doctor-nested-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + assert!(!dir.exists()); + let cache = dir.join("one").join("two").join("models"); + assert_eq!( + cache_status(&cache), + ( + Verdict::Warn, + "will be created on first download; write access not tested" + ) + ); + } + #[test] fn verdict_labels_are_short() { assert_eq!(Verdict::Ok.label(), "ok"); diff --git a/src/fetch.rs b/src/fetch.rs index 744f9ca..b07ff23 100644 --- a/src/fetch.rs +++ b/src/fetch.rs @@ -154,8 +154,8 @@ async fn fetch_async(url: &str, cancel: &Arc) -> Result None, }; let Some(crate_result) = crate_result else { - let _ = std::fs::remove_file(&direct); - return Err("cancelled".into()); + let cleanup = cleanup_paths(&[&direct]); + return Err(format!("cancelled{}", cleanup_suffix(cleanup))); }; let path = match crate_result { Ok(p) if p.is_absolute() => p, @@ -187,8 +187,11 @@ async fn fetch_async(url: &str, cancel: &Arc) -> Result child, Err(e) => { - cleanup_fallback(&fallback, &direct); - return Err(format!("could not download audio: {e}")); + let cleanup = cleanup_fallback(&fallback, &direct); + return Err(format!( + "could not download audio: {e}{}", + cleanup_suffix(cleanup) + )); } }; let status = tokio::select! { @@ -196,20 +199,21 @@ async fn fetch_async(url: &str, cancel: &Arc) -> Result status, Err(e) => { stop_child(&mut child).await; - cleanup_fallback(&fallback, &direct); - return Err(format!("could not download audio: {e}")); + let cleanup = cleanup_fallback(&fallback, &direct); + return Err(format!("could not download audio: {e}{}", cleanup_suffix(cleanup))); } }, _ = cancelled(cancel) => { stop_child(&mut child).await; - cleanup_fallback(&fallback, &direct); - return Err("cancelled".into()); + let cleanup = cleanup_fallback(&fallback, &direct); + return Err(format!("cancelled{}", cleanup_suffix(cleanup))); } }; if !status.success() || !fallback.is_file() { - cleanup_fallback(&fallback, &direct); + let cleanup = cleanup_fallback(&fallback, &direct); return Err(format!( - "no audio came out. the http path said: {crate_err}" + "no audio came out. the http path said: {crate_err}{}", + cleanup_suffix(cleanup) )); } fallback @@ -217,14 +221,24 @@ async fn fetch_async(url: &str, cancel: &Arc) -> Result error, + Err(returned_error) => { + format!("{error}; returned audio cleanup also failed: {returned_error}") + } + }; + return Err(format!( + "audio was downloaded but temporary-file cleanup failed: {detail}" + )); } Ok(FetchedAudio { @@ -272,9 +286,34 @@ pub fn ffmpeg_path() -> Option { p.is_file().then_some(p) } -fn cleanup_fallback(fallback: &Path, direct: &Path) { - let _ = std::fs::remove_file(fallback); - let _ = std::fs::remove_file(direct); +fn cleanup_paths(paths: &[&Path]) -> Result<(), String> { + let mut failures = Vec::new(); + for path in paths { + match std::fs::remove_file(path) { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} + Err(error) => failures.push(format!("{}: {error}", path.display())), + } + } + if failures.is_empty() { + Ok(()) + } else { + Err(format!( + "could not remove partial download(s): {}", + failures.join("; ") + )) + } +} + +fn cleanup_fallback(fallback: &Path, direct: &Path) -> Result<(), String> { + cleanup_paths(&[fallback, direct]) +} + +fn cleanup_suffix(result: Result<(), String>) -> String { + result + .err() + .map(|error| format!("; {error}")) + .unwrap_or_default() } /// remove a partial audio file left behind by a cancelled/interrupted fetch. @@ -330,13 +369,31 @@ mod tests { std::fs::write(&fallback, b"partial").unwrap(); std::fs::write(&direct, b"partial").unwrap(); - cleanup_fallback(&fallback, &direct); + cleanup_fallback(&fallback, &direct).unwrap(); assert!(!fallback.exists()); assert!(!direct.exists()); std::fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn fallback_cleanup_reports_filesystem_failures() { + let dir = + std::env::temp_dir().join(format!("scribe-fallback-error-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let fallback = dir.join("fallback.webm"); + let direct = dir.join("direct.m4a"); + std::fs::create_dir_all(&fallback).unwrap(); + std::fs::write(&direct, b"partial").unwrap(); + + let error = cleanup_fallback(&fallback, &direct).unwrap_err(); + + assert!(error.contains("fallback.webm")); + assert!(!direct.exists()); + std::fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn cleanup_removes_partial_audio() { let dir = std::env::temp_dir().join(format!("scribe-fetch-{}", std::process::id())); diff --git a/src/main.rs b/src/main.rs index 74c7d07..637681a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -209,6 +209,9 @@ fn collect_plain_segments( WorkerEventKind::Segment(segment) => segments.push(segment), WorkerEventKind::Done => return Ok(segments), WorkerEventKind::Cancelled => return Err("transcription cancelled".into()), + WorkerEventKind::CancelledWithWarning(message) => { + return Err(format!("transcription cancelled; {message}")); + } WorkerEventKind::Error(error) => return Err(error), _ => {} } @@ -336,7 +339,10 @@ fn run_tui(args: &Args) -> Result<(), String> { } let terminal = matches!( ev.kind, - WorkerEventKind::Done | WorkerEventKind::Cancelled | WorkerEventKind::Error(_) + WorkerEventKind::Done + | WorkerEventKind::Cancelled + | WorkerEventKind::CancelledWithWarning(_) + | WorkerEventKind::Error(_) ); needs_redraw = true; app.accept_event(ev); @@ -886,16 +892,95 @@ fn change_setting(app: &mut App, forward: bool) { } } +fn retry_cache_removal(mut remove: impl FnMut() -> Result<(), String>) -> Result<(), String> { + let mut last_error = String::new(); + for attempt in 0..20 { + match remove() { + Ok(()) => return Ok(()), + Err(error) + if error.contains("another scribe is using the model cache") && attempt < 19 => + { + last_error = error; + std::thread::sleep(std::time::Duration::from_millis(100)); + } + Err(error) => return Err(error), + } + } + Err(last_error) +} + +fn remove_discarded_model(info: &model::ModelInfo) -> Result<(), String> { + retry_cache_removal(|| model::remove_model(info)) +} + +fn remove_discarded_partial(info: &model::ModelInfo) -> Result<(), String> { + retry_cache_removal(|| model::remove_partial(info)) +} + +fn normalized_path(path: &std::path::Path) -> std::path::PathBuf { + let absolute = if path.is_absolute() { + path.to_path_buf() + } else { + std::env::current_dir() + .unwrap_or_else(|_| std::path::PathBuf::from(".")) + .join(path) + }; + let mut normalized = std::path::PathBuf::new(); + for component in absolute.components() { + match component { + std::path::Component::CurDir => {} + std::path::Component::ParentDir => { + normalized.pop(); + } + other => normalized.push(other.as_os_str()), + } + } + normalized +} + +fn paths_equal(left: &std::path::Path, right: &std::path::Path) -> bool { + #[cfg(windows)] + { + left.to_string_lossy().to_lowercase() == right.to_string_lossy().to_lowercase() + } + #[cfg(not(windows))] + { + left == right + } +} + +fn selected_model_matches_managed(app: &App, file: &str) -> bool { + let managed = model::cache_dir().join(file); + let selected = std::path::Path::new(&app.model_name); + if selected.as_os_str().is_empty() { + return false; + } + let selected = std::fs::canonicalize(selected).unwrap_or_else(|_| normalized_path(selected)); + let managed = std::fs::canonicalize(&managed).unwrap_or_else(|_| normalized_path(&managed)); + paths_equal(&selected, &managed) +} + +fn clear_discarded_model_selection(app: &mut App, file: &str, selected_managed: bool) { + let path = model::cache_dir().join(file); + if selected_managed && !path.exists() { + app.model_name.clear(); + app.model_label = "-".into(); + } +} + fn finish_model_download(app: &mut App, outcome: DownloadOutcome) { match outcome { DownloadOutcome::Ready => { if app.download_discard { + let discarded_file = app.download_file.clone(); + let selected_managed = selected_model_matches_managed(app, &discarded_file); let result = app .download_models .iter() .find(|model| model.file == app.download_file) .ok_or_else(|| "downloaded model is no longer in the catalog".to_string()) - .and_then(model::remove_model); + .and_then(remove_discarded_model); + clear_discarded_model_selection(app, &discarded_file, selected_managed); app.download_discard = false; app.download_paused = false; match result { @@ -935,7 +1020,7 @@ fn finish_model_download(app: &mut App, outcome: DownloadOutcome) { .iter() .find(|info| info.file == app.download_file) { - if let Err(err) = model::remove_partial(info) { + if let Err(err) = remove_discarded_partial(info) { app.download_info = err.clone(); app.set_message(err); } else { @@ -970,6 +1055,10 @@ fn start_download( let Some(info) = app.download_models.get(app.download_index).cloned() else { return; }; + if downloader.is_some() && info.file == app.download_file { + app.set_message("download in progress (press c or esc to pause)"); + return; + } let cached = model::cache_dir().join(info.file); if cached.is_file() { if let Err(e) = model::validate_cached(&info, &cached) { @@ -987,7 +1076,7 @@ fn start_download( let what = if app.download_paused { "previous download is still stopping; press enter again in a moment" } else { - "download in progress (press c or esc to pause)" + "another download is in progress" }; app.set_message(what); return; @@ -1077,6 +1166,8 @@ use util::{duration_short, human_bytes, timestamp_short}; mod tests { use super::*; + static TEST_CACHE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + #[test] fn plain_transcription_requires_worker_completion() { let segment = || export::Segment::new(0, 100, "hello".into()); @@ -1105,8 +1196,39 @@ mod tests { assert_eq!(failed.unwrap_err(), "decoder failed"); } + #[test] + fn cache_removal_retries_contention_beyond_the_old_window() { + let mut attempts = 0; + let result = retry_cache_removal(|| { + attempts += 1; + if attempts < 7 { + Err("another scribe is using the model cache".into()) + } else { + Ok(()) + } + }); + assert!(result.is_ok()); + assert_eq!(attempts, 7); + } + + #[test] + fn cache_removal_retries_transient_lock_contention() { + let mut attempts = 0; + let result = retry_cache_removal(|| { + attempts += 1; + if attempts < 3 { + Err("another scribe is using the model cache".into()) + } else { + Ok(()) + } + }); + assert!(result.is_ok()); + assert_eq!(attempts, 3); + } + #[test] fn cancel_after_download_commit_removes_the_completed_model() { + let _guard = TEST_CACHE_LOCK.lock().unwrap(); let dir = std::env::temp_dir().join(format!("scribe-discard-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); @@ -1119,12 +1241,16 @@ mod tests { let mut app = App::new(&crate::cli::Args::default()); app.download_models = crate::model::CATALOG.to_vec(); app.download_file = info.file.to_string(); + app.model_name = path.to_string_lossy().to_string(); + app.model_label = info.label.to_string(); app.download_discard = true; app.download_paused = true; finish_model_download(&mut app, DownloadOutcome::Ready); assert!(!path.exists()); + assert!(app.model_name.is_empty()); + assert_eq!(app.model_label, "-"); assert!(!app.download_discard); assert!(!app.download_paused); assert_eq!(app.download, app::DownloadState::Idle); @@ -1132,6 +1258,109 @@ mod tests { std::fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn discard_clears_equivalent_managed_model_selection() { + let _guard = TEST_CACHE_LOCK.lock().unwrap(); + let info = crate::model::find("tiny").unwrap(); + let dir = + std::env::temp_dir().join(format!("scribe-relative-discard-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + crate::model::set_test_cache_dir(Some(dir.clone())); + let path = dir.join(info.file); + std::fs::write(&path, b"model").unwrap(); + let alias = dir + .join("..") + .join(dir.file_name().unwrap()) + .join(info.file); + let mut app = App::new(&crate::cli::Args::default()); + app.model_name = alias.to_string_lossy().into_owned(); + app.model_label = info.label.to_string(); + let selected_managed = selected_model_matches_managed(&app, info.file); + assert!(selected_managed); + std::fs::remove_file(&path).unwrap(); + + clear_discarded_model_selection(&mut app, info.file, selected_managed); + + assert!(app.model_name.is_empty()); + assert_eq!(app.model_label, "-"); + crate::model::set_test_cache_dir(None); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[cfg(windows)] + #[test] + fn discard_clears_case_insensitive_managed_model_selection() { + let _guard = TEST_CACHE_LOCK.lock().unwrap(); + let info = crate::model::find("tiny").unwrap(); + let dir = std::env::temp_dir().join(format!("scribe-case-discard-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + crate::model::set_test_cache_dir(Some(dir.clone())); + let path = dir.join(info.file); + std::fs::write(&path, b"model").unwrap(); + + let mut app = App::new(&crate::cli::Args::default()); + app.model_name = path.to_string_lossy().to_uppercase(); + app.model_label = info.label.to_string(); + let selected_managed = selected_model_matches_managed(&app, info.file); + assert!(selected_managed); + std::fs::remove_file(&path).unwrap(); + + clear_discarded_model_selection(&mut app, info.file, selected_managed); + + assert!(app.model_name.is_empty()); + assert_eq!(app.model_label, "-"); + crate::model::set_test_cache_dir(None); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[cfg(unix)] + #[test] + fn discard_clears_symlinked_managed_model_selection() { + let _guard = TEST_CACHE_LOCK.lock().unwrap(); + use std::os::unix::fs::symlink; + let info = crate::model::find("tiny").unwrap(); + let dir = + std::env::temp_dir().join(format!("scribe-symlink-discard-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + crate::model::set_test_cache_dir(Some(dir.clone())); + let path = dir.join(info.file); + let alias = dir.join("selected-model.bin"); + std::fs::write(&path, b"model").unwrap(); + symlink(&path, &alias).unwrap(); + + let mut app = App::new(&crate::cli::Args::default()); + app.model_name = alias.to_string_lossy().into_owned(); + app.model_label = info.label.to_string(); + let selected_managed = selected_model_matches_managed(&app, info.file); + assert!(selected_managed); + std::fs::remove_file(&path).unwrap(); + + clear_discarded_model_selection(&mut app, info.file, selected_managed); + + assert!(app.model_name.is_empty()); + assert_eq!(app.model_label, "-"); + crate::model::set_test_cache_dir(None); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn discard_does_not_clear_custom_model_with_matching_filename() { + let info = crate::model::find("tiny").unwrap(); + let custom = std::env::temp_dir().join("custom").join(info.file); + let mut app = App::new(&crate::cli::Args::default()); + app.model_name = custom.to_string_lossy().to_string(); + app.model_label = "custom".into(); + + let selected_managed = selected_model_matches_managed(&app, info.file); + clear_discarded_model_selection(&mut app, info.file, selected_managed); + + assert_eq!(app.model_name, custom.to_string_lossy().into_owned()); + assert_eq!(app.model_label, "custom"); + } + #[test] fn terminal_cleanup_continues_after_a_failed_step() { use std::cell::RefCell; diff --git a/src/model.rs b/src/model.rs index 293c78d..d5da162 100644 --- a/src/model.rs +++ b/src/model.rs @@ -1388,13 +1388,21 @@ mod tests { fs::remove_dir_all(&dir).unwrap(); } + #[cfg(unix)] #[test] - fn custom_model_header_read_errors_are_rejected() { + fn validate_custom_rejects_unreadable_model_headers() { let dir = std::env::temp_dir().join(format!("scribe-header-{}", std::process::id())); fs::create_dir_all(&dir).unwrap(); - let path = dir.join("truncated.bin"); - fs::write(&path, b"gg").unwrap(); - assert!(read_model_header(&path).is_err()); + for index in 0..512 { + fs::write(dir.join(format!("entry-{index}")), b"x").unwrap(); + if fs::metadata(&dir).unwrap().len() >= 1024 { + break; + } + } + assert!(fs::metadata(&dir).unwrap().len() >= 1024); + assert!(read_model_header(&dir).is_err()); + let error = validate_custom(&dir).unwrap_err(); + assert!(error.contains("cannot read model header")); fs::remove_dir_all(&dir).unwrap(); } diff --git a/src/util.rs b/src/util.rs index f7d567c..516dcd0 100644 --- a/src/util.rs +++ b/src/util.rs @@ -65,6 +65,55 @@ pub fn is_url(s: &str) -> bool { /// just enough url parsing to reject junk without pulling in a url crate. we /// care about scheme + host, not about the entire rfc. a filename with a colon /// or a dot is still a filename. +fn valid_zone_id(zone: &str) -> bool { + let bytes = zone.as_bytes(); + let mut index = 0; + while index < bytes.len() { + let byte = bytes[index]; + if byte.is_ascii_alphanumeric() || b"-._~".contains(&byte) { + index += 1; + } else if byte == b'%' { + if index + 2 >= bytes.len() + || !bytes[index + 1].is_ascii_hexdigit() + || !bytes[index + 2].is_ascii_hexdigit() + { + return false; + } + index += 3; + } else { + return false; + } + } + !bytes.is_empty() +} + +fn valid_ipvfuture(host: &str) -> bool { + let versioned = host.strip_prefix('v').or_else(|| host.strip_prefix('V')); + let Some(versioned) = versioned else { + return false; + }; + let Some((version, address)) = versioned.split_once('.') else { + return false; + }; + !version.is_empty() + && version.bytes().all(|byte| byte.is_ascii_hexdigit()) + && !address.is_empty() + && address + .bytes() + .all(|byte| byte.is_ascii_alphanumeric() || b"-._~!$&'()*+,;=:".contains(&byte)) +} + +fn valid_bracketed_host(host: &str) -> bool { + if valid_ipvfuture(host) { + return true; + } + if let Some((address, zone)) = host.split_once("%25") { + address.parse::().is_ok() && valid_zone_id(zone) + } else { + host.parse::().is_ok() + } +} + pub fn parse_http_url(s: &str) -> Option<(String, String)> { let s = s.trim(); let (scheme, rest) = s.split_once("://")?; @@ -75,7 +124,9 @@ pub fn parse_http_url(s: &str) -> Option<(String, String)> { let host_port = authority.rsplit('@').next()?; let host = if let Some(bracketed) = host_port.strip_prefix('[') { let (host, suffix) = bracketed.split_once(']')?; - host.parse::().ok()?; + if !valid_bracketed_host(host) { + return None; + } if !suffix.is_empty() { let port = suffix.strip_prefix(':')?; if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) { @@ -100,7 +151,12 @@ pub fn parse_http_url(s: &str) -> Option<(String, String)> { if host.is_empty() || host.chars().any(|c| c.is_whitespace()) { return None; } - Some((scheme.to_ascii_lowercase(), host.to_ascii_lowercase())) + let normalized_host = if let Some((address, zone)) = host.split_once("%25") { + format!("{}%25{zone}", address.to_ascii_lowercase()) + } else { + host.to_ascii_lowercase() + }; + Some((scheme.to_ascii_lowercase(), normalized_host)) } fn host_matches(url: &str, hosts: &[&str]) -> bool { @@ -451,20 +507,45 @@ fn split_completion_path(input: &str, windows: bool) -> (&str, &str) { }; match separator { Some(i) => (&input[..=i], &input[i + 1..]), + None if windows + && input.as_bytes().get(1) == Some(&b':') + && input.as_bytes()[0].is_ascii_alphabetic() => + { + (&input[..2], &input[2..]) + } None => ("", input), } } +fn is_windows_unc_path(input: &str, windows: bool) -> bool { + windows + && input + .as_bytes() + .first() + .is_some_and(|byte| *byte == b'/' || *byte == b'\\') + && input + .as_bytes() + .get(1) + .is_some_and(|byte| *byte == b'/' || *byte == b'\\') +} + pub fn complete_path(input: &str) -> Vec { + complete_path_with(input, cfg!(windows)) +} + +fn complete_path_with(input: &str, windows: bool) -> Vec { let raw = if input.starts_with('~') { - expand_tilde(input) + expand_tilde_from(input, home_dir(), windows) } else { PathBuf::from(input) }; let text = raw.to_string_lossy().to_string(); - let (dir, prefix) = split_completion_path(&text, cfg!(windows)); + if is_windows_unc_path(&text, windows) { + return Vec::new(); + } + let (dir, prefix) = split_completion_path(&text, windows); let scan = if dir.is_empty() { "." } else { dir }; - let scan = expand_tilde(scan); + let scan = expand_tilde_from(scan, home_dir(), windows); let mut out: Vec = Vec::new(); if let Ok(entries) = std::fs::read_dir(&scan) { let mut found: Vec = entries @@ -739,7 +820,6 @@ mod tests { assert!(is_url("HTTP://EXAMPLE.COM")); assert!(!is_url("/tmp/a.wav")); assert!(!is_url(r"c:\audio\file.wav")); - // schemes that look like urls but are not http(s) are paths assert!(!is_url("ftp://example.com/a")); assert!(!is_url("file:///tmp/a.wav")); assert!(!is_url("not a url")); @@ -749,7 +829,23 @@ mod tests { assert!(is_url("http://user:pass@example.com:8080/a")); assert!(is_url("http://[::1]/audio.wav")); assert!(is_url("https://[2001:db8::1]:8443/audio.wav")); + assert!(is_url("http://[fe80::1%25eth0]/audio.wav")); + assert!(is_url("http://[fe80::1%25eth0]:8080/audio.wav")); + assert_eq!( + parse_http_url("http://[fe80::1%25Eth0]/audio.wav") + .unwrap() + .1, + "fe80::1%25Eth0" + ); + assert!(is_url("http://[v1.example]/audio.wav")); + assert!(is_url("http://[Vf.a:b!$&'()*+,;=]/audio.wav")); assert!(!is_url("http://[not-ip]/audio.wav")); + assert!(!is_url("http://[fe80::1%25]/audio.wav")); + assert!(!is_url("http://[fe80::1%25bad%xx]/audio.wav")); + assert!(!is_url("http://[fe80::1%25eth0%zz]/audio.wav")); + assert!(!is_url("http://[fe80::1%25eth0]:99999/audio.wav")); + assert!(!is_url("http://[v.example]/audio.wav")); + assert!(!is_url("http://[v1.]/audio.wav")); assert!(!is_url("http://example.com:bad/audio.wav")); assert!(!is_url("http://example.com:/audio.wav")); } @@ -917,6 +1013,51 @@ mod tests { split_completion_path("C:/Users/user/rec", true), ("C:/Users/user/", "rec") ); + assert_eq!(split_completion_path("C:rec", true), ("C:", "rec")); + assert_eq!(split_completion_path("C:", true), ("C:", "")); + assert!(is_windows_unc_path("\\\\server\\share", true)); + assert!(is_windows_unc_path("//server/share", true)); + assert!(is_windows_unc_path(r"/\\server/share", true)); + assert!(is_windows_unc_path(r"\/server/share", true)); + assert!(is_windows_unc_path(r"\//server/share", true)); + assert!(!is_windows_unc_path("C:\\Users\\person", true)); + assert!(!is_windows_unc_path("\\\\server\\share", false)); + } + + #[cfg(windows)] + #[test] + fn complete_path_uses_windows_separators_end_to_end() { + let dir = std::env::temp_dir().join(format!("scribe-win-cmpl-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("recording.wav"), b"x").unwrap(); + let input = format!("{}\\record", dir.display()); + let candidates = complete_path(&input); + assert!( + candidates + .iter() + .any(|candidate| candidate.value.ends_with("recording.wav")) + ); + std::fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn complete_path_uses_windows_separator_mode_end_to_end() { + let dir = std::env::temp_dir().join(format!("scribe-cmpl-win-mode-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("recording.wav"), b"x").unwrap(); + + let input = format!("{}/record", dir.display()); + let candidates = complete_path_with(&input, true); + + assert!( + candidates + .iter() + .any(|candidate| candidate.value.ends_with("recording.wav")) + ); + assert!(complete_path_with(r"\\\\server\\share", true).is_empty()); + assert!(complete_path_with(r"/\\server/share", true).is_empty()); + std::fs::remove_dir_all(&dir).unwrap(); } #[test] diff --git a/src/worker.rs b/src/worker.rs index 8de4b50..a2a2104 100644 --- a/src/worker.rs +++ b/src/worker.rs @@ -65,6 +65,7 @@ pub enum EventKind { Segment(Segment), Done, Cancelled, + CancelledWithWarning(String), Error(String), } @@ -221,9 +222,13 @@ fn run( reap(children); let last = match result { Err(_) => EventKind::Error("the worker panicked. the job was abandoned; try again".into()), - Ok(_) if cancel.load(Ordering::Relaxed) => EventKind::Cancelled, - Ok(Ok(())) => EventKind::Done, + Ok(Err(e)) if cancel.load(Ordering::Relaxed) && e.starts_with("cancelled; ") => { + EventKind::CancelledWithWarning(e["cancelled; ".len()..].to_string()) + } + Ok(Err(e)) if cancel.load(Ordering::Relaxed) && e == "cancelled" => EventKind::Cancelled, Ok(Err(e)) => EventKind::Error(e), + Ok(Ok(())) if cancel.load(Ordering::Relaxed) => EventKind::Cancelled, + Ok(Ok(())) => EventKind::Done, }; let _ = tx.send(Event::new(job_id, last)); } @@ -431,6 +436,8 @@ struct Ingest { reader: Option>, diagnostics: Option>>, children: Children, + cancel: Arc, + finished: bool, } impl Ingest { @@ -443,6 +450,7 @@ impl Ingest { .take() .and_then(|h| h.join().ok()) .unwrap_or_default(); + self.finished = true; (total, first_line(&tail)) } } @@ -452,7 +460,10 @@ impl Drop for Ingest { // a cancelled job can return before the readers see eof. kill the // decoder so their blocking reads end, then join them: no detached // reader may outlive the job it was reading for. - kill_all(&self.children); + if !self.finished { + self.cancel.store(true, Ordering::Relaxed); + kill_all(&self.children); + } if let Some(h) = self.reader.take() { let _ = h.join(); } @@ -462,7 +473,16 @@ impl Drop for Ingest { } } -fn send_chunk(tx: &SyncSender, mut chunk: Chunk, cancel: &AtomicBool) -> bool { +fn send_chunk(tx: &SyncSender, chunk: Chunk, cancel: &AtomicBool) -> bool { + send_chunk_with(tx, chunk, cancel, || {}) +} + +fn send_chunk_with( + tx: &SyncSender, + mut chunk: Chunk, + cancel: &AtomicBool, + mut on_full: impl FnMut(), +) -> bool { loop { if cancel.load(Ordering::Relaxed) { return false; @@ -471,6 +491,7 @@ fn send_chunk(tx: &SyncSender, mut chunk: Chunk, cancel: &AtomicBool) -> Ok(()) => return true, Err(std::sync::mpsc::TrySendError::Full(returned)) => { chunk = returned; + on_full(); thread::sleep(Duration::from_millis(10)); } Err(std::sync::mpsc::TrySendError::Disconnected(_)) => return false, @@ -495,21 +516,22 @@ fn spawn_ingest( return Err(format!("cannot start decoder stderr reader: {e}")); } }; + let reader_cancel = cancel.clone(); let reader = match thread::Builder::new() .name("scribe-ingest".into()) .spawn(move || { let mut bytes = vec![0u8; CHUNK * 4]; let mut total = 0usize; - while !cancel.load(Ordering::Relaxed) { + while !reader_cancel.load(Ordering::Relaxed) { let n = match read_full(&mut out, &mut bytes) { Ok(0) => break, Ok(n) => n, Err(e) => { - if !cancel.load(Ordering::Relaxed) { + if !reader_cancel.load(Ordering::Relaxed) { let _ = send_chunk( &tx, Chunk::Failed(format!("could not read decoded audio: {e}")), - &cancel, + &reader_cancel, ); } return total; @@ -517,7 +539,7 @@ fn spawn_ingest( }; let samples = bytes_to_f32(&bytes[..n - n % 4]); total += samples.len(); - if !send_chunk(&tx, Chunk::Samples(samples), &cancel) { + if !send_chunk(&tx, Chunk::Samples(samples), &reader_cancel) { return total; } if n < bytes.len() { @@ -537,6 +559,8 @@ fn spawn_ingest( reader: Some(reader), diagnostics: Some(diagnostics), children, + cancel, + finished: false, }) } @@ -972,7 +996,11 @@ mod tests { match rx.recv_timeout(Duration::from_millis(100)) { Ok(Event { job_id: 7, - kind: EventKind::Error(_) | EventKind::Cancelled | EventKind::Done, + kind: + EventKind::Error(_) + | EventKind::Cancelled + | EventKind::CancelledWithWarning(_) + | EventKind::Done, }) => { terminal = true; break; @@ -1008,20 +1036,54 @@ mod tests { assert!(tx.try_send(Chunk::Samples(vec![0.0])).is_ok()); let cancel = Arc::new(AtomicBool::new(false)); let worker_cancel = cancel.clone(); + let (full_tx, full_rx) = mpsc::channel(); let (done_tx, done_rx) = mpsc::channel(); let worker = thread::spawn(move || { - let sent = send_chunk(&tx, Chunk::Samples(vec![1.0]), &worker_cancel); + let sent = send_chunk_with(&tx, Chunk::Samples(vec![1.0]), &worker_cancel, || { + let _ = full_tx.send(()); + }); done_tx.send(sent).unwrap(); }); - thread::sleep(Duration::from_millis(30)); + full_rx.recv_timeout(Duration::from_secs(1)).unwrap(); + assert!(done_rx.recv_timeout(Duration::from_millis(50)).is_err()); cancel.store(true, Ordering::Relaxed); assert!(!done_rx.recv_timeout(Duration::from_secs(1)).unwrap()); worker.join().unwrap(); assert!(matches!(rx.try_recv(), Ok(Chunk::Samples(_)))); } + #[test] + fn dropping_ingest_unblocks_a_reader_waiting_on_backpressure() { + let (tx, _rx) = mpsc::sync_channel(1); + tx.try_send(Chunk::Samples(vec![0.0])).unwrap(); + let cancel = Arc::new(AtomicBool::new(false)); + let reader_cancel = cancel.clone(); + let (full_tx, full_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + let reader = thread::spawn(move || { + let sent = send_chunk_with(&tx, Chunk::Samples(vec![1.0]), &reader_cancel, || { + let _ = full_tx.send(()); + }); + done_tx.send(sent).unwrap(); + 0 + }); + let ingest = Ingest { + reader: Some(reader), + diagnostics: None, + children: Arc::new(Mutex::new(Vec::new())), + cancel, + finished: false, + }; + + full_rx.recv_timeout(Duration::from_secs(1)).unwrap(); + assert!(done_rx.recv_timeout(Duration::from_millis(50)).is_err()); + let dropper = thread::spawn(move || drop(ingest)); + dropper.join().unwrap(); + assert!(!done_rx.recv_timeout(Duration::from_secs(1)).unwrap()); + } + #[cfg(unix)] fn fake_decoder(script: &str) -> Command { let mut command = Command::new("sh");