diff --git a/Cargo.lock b/Cargo.lock index bc8390d..25627a2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2577,6 +2577,7 @@ version = "0.3.0" dependencies = [ "crossterm", "ratatui", + "rustix", "sha2 0.11.1", "tokio", "unicode-width", diff --git a/Cargo.toml b/Cargo.toml index 5452c70..075e939 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,6 +48,9 @@ sha2 = "0.11.1" # locate ffprobe on path; used by the duration detector in worker.rs. which = "8" +[target.'cfg(unix)'.dependencies] +rustix = { version = "1.1", features = ["fs"] } + [profile.release] lto = "fat" codegen-units = 1 diff --git a/src/main.rs b/src/main.rs index 1e2fa6e..6559125 100644 --- a/src/main.rs +++ b/src/main.rs @@ -252,6 +252,12 @@ fn run_plain(args: &Args) -> Result { } } +enum DownloadOutcome { + Ready, + Paused, + Failed(String), +} + fn run_tui(args: &Args) -> Result<(), String> { let mut guard = TerminalGuard::enter().map_err(|e| format!("could not start the terminal ui: {e}"))?; @@ -283,7 +289,7 @@ fn run_tui(args: &Args) -> Result<(), String> { // cancelled workers keep running until they notice the flag. park their // handles here and reap them in the loop instead of freezing the ui. let mut retiring: Vec = Vec::new(); - let mut downloader: Option> = None; + let mut downloader: Option> = None; let mut download_rx: Option> = None; let mut download_cancel: Option> = None; @@ -298,80 +304,27 @@ fn run_tui(args: &Args) -> Result<(), String> { if let Some(drx) = &download_rx { while let Ok(p) = drx.try_recv() { needs_redraw = true; - if p.bytes_per_sec < 0.0 { - if p.bytes_per_sec == -2.0 { - app.download = app::DownloadState::Idle; - if app.download_discard { - if let Some(info) = app - .download_models - .iter() - .find(|info| info.file == app.download_file) - { - if let Err(e) = model::remove_partial(info) { - app.download_info = e.clone(); - app.set_message(e); - } else { - app.download_info = - "download canceled · partial file removed".into(); - app.toast("download canceled", ToastKind::Warn); - } - } - app.download_discard = false; - app.download_paused = false; - } else { - app.download = app::DownloadState::Idle; - app.download_paused = true; - app.download_info = "paused · enter resumes from saved data".into(); - app.toast("download paused · enter resumes", ToastKind::Info); - } - } else { - let err_path = - model::cache_dir().join(format!(".{}.error", app.download_file)); - let msg = std::fs::read_to_string(&err_path).unwrap_or_else(|_| { - "download failed, and the error note vanished".into() - }); - let _ = std::fs::remove_file(&err_path); - app.download = app::DownloadState::Failed; - app.download_paused = false; - app.download_info = msg.clone(); - app.toast(format!("download failed: {msg}"), ToastKind::Error); - app.set_message(msg); - } - } else { - app.download_frac = p.fraction(); - if p.bytes_per_sec > 0.0 { - app.download_info = format!( - "{}/s eta {}", - human_bytes(p.bytes_per_sec as u64), - p.eta_s() - .map(duration_short) - .unwrap_or_else(|| "--:--".into()) - ); - } + app.download_frac = p.fraction(); + if p.bytes_per_sec > 0.0 { + app.download_info = format!( + "{}/s eta {}", + human_bytes(p.bytes_per_sec as u64), + p.eta_s() + .map(duration_short) + .unwrap_or_else(|| "--:--".into()) + ); } } } if downloader.as_ref().is_some_and(|h| h.is_finished()) { if let Some(h) = downloader.take() { - let _ = h.join(); + let outcome = h.join().unwrap_or_else(|_| { + DownloadOutcome::Failed("download worker stopped unexpectedly".into()) + }); + finish_model_download(&mut app, outcome); } download_rx = None; - if app.download == app::DownloadState::Downloading { - app.download = app::DownloadState::Done; - app.download_paused = false; - app.download_frac = 1.0; - let label = app - .download_models - .iter() - .find(|model| model.file == app.download_file) - .map(|model| model.label) - .unwrap_or("model"); - app.toast( - format!("{label} downloaded and verified"), - ToastKind::Success, - ); - app.set_message(format!("{label} is ready. press enter to select it")); - } + download_cancel = None; needs_redraw = true; } @@ -516,7 +469,7 @@ fn process_key( tx: &mpsc::Sender, handle: &mut Option, retiring: &mut Vec, - downloader: &mut Option>, + downloader: &mut Option>, download_rx: &mut Option>, download_cancel: &mut Option>, picker_rows: usize, @@ -600,10 +553,10 @@ fn process_key( if let Some(c) = download_cancel.take() { c.store(true, std::sync::atomic::Ordering::Relaxed); } - app.download_info = "pausing · saved data will resume on enter".into(); + app.download_info = "pausing · saved data will resume on enter".into(); app.download_paused = true; app.toast( - "download paused · enter resumes from saved data", + "download paused · enter resumes from saved data", ToastKind::Info, ); // Closing the picker should not require waiting for the @@ -619,7 +572,7 @@ fn process_key( if let Some(c) = download_cancel.take() { c.store(true, std::sync::atomic::Ordering::Relaxed); } - app.download_info = "pausing · saved data will resume on enter".into(); + app.download_info = "pausing · saved data will resume on enter".into(); app.download_paused = true; } KeyCode::Char('c') if app.download == app::DownloadState::Downloading => { @@ -628,7 +581,7 @@ fn process_key( if let Some(c) = download_cancel.take() { c.store(true, std::sync::atomic::Ordering::Relaxed); } - app.download_info = "canceling · removing partial download".into(); + app.download_info = "canceling · removing partial download".into(); } KeyCode::Char('x') => { let info = &app.download_models[app.download_index]; @@ -932,9 +885,61 @@ fn change_setting(app: &mut App, forward: bool) { } } +fn finish_model_download(app: &mut App, outcome: DownloadOutcome) { + match outcome { + DownloadOutcome::Ready => { + app.download = app::DownloadState::Done; + app.download_paused = false; + app.download_frac = 1.0; + let label = app + .download_models + .iter() + .find(|model| model.file == app.download_file) + .map(|model| model.label) + .unwrap_or("model"); + app.toast( + format!("{label} downloaded and verified"), + ToastKind::Success, + ); + app.set_message(format!("{label} is ready. press enter to select it")); + } + DownloadOutcome::Paused => { + app.download = app::DownloadState::Idle; + if app.download_discard { + if let Some(info) = app + .download_models + .iter() + .find(|info| info.file == app.download_file) + { + if let Err(err) = model::remove_partial(info) { + app.download_info = err.clone(); + app.set_message(err); + } else { + app.download_info = "download canceled · partial file removed".into(); + app.toast("download canceled", ToastKind::Warn); + } + } + app.download_discard = false; + app.download_paused = false; + } else { + app.download_paused = true; + app.download_info = "paused · enter resumes from saved data".into(); + app.toast("download paused · enter resumes", ToastKind::Info); + } + } + DownloadOutcome::Failed(err) => { + app.download = app::DownloadState::Failed; + app.download_paused = false; + app.download_info = err.clone(); + app.toast(format!("download failed: {err}"), ToastKind::Error); + app.set_message(err); + } + } +} + fn start_download( app: &mut App, - downloader: &mut Option>, + downloader: &mut Option>, download_rx: &mut Option>, download_cancel: &mut Option>, ) { @@ -954,17 +959,6 @@ fn start_download( } return; } - // a finished thread still holding its slot must be reaped before a new - // download starts; otherwise the old join handle can look "live" for a - // frame and enter gets ignored right after a pause. - if let Some(h) = downloader.as_ref() - && h.is_finished() - { - if let Some(h) = downloader.take() { - let _ = h.join(); - } - *download_rx = None; - } if downloader.is_some() { let what = if app.download_paused { "previous download is still stopping; press enter again in a moment" @@ -996,22 +990,12 @@ fn start_download( let result = model::download(&info, &cancel_thread, |p| { let _ = p_tx.send(p); }); - if let Err(e) = result { - if cancel_thread.load(std::sync::atomic::Ordering::Relaxed) { - let _ = p_tx.send(model::DownloadProgress { - downloaded: 0, - total: None, - bytes_per_sec: -2.0, - }); - } else { - let _ = - std::fs::write(model::cache_dir().join(format!(".{}.error", info.file)), &e); - let _ = p_tx.send(model::DownloadProgress { - downloaded: 0, - total: None, - bytes_per_sec: -1.0, - }); + match result { + Ok(_) => DownloadOutcome::Ready, + Err(_) if cancel_thread.load(std::sync::atomic::Ordering::Relaxed) => { + DownloadOutcome::Paused } + Err(err) => DownloadOutcome::Failed(err), } }); *download_cancel = Some(cancel); diff --git a/src/model.rs b/src/model.rs index e61fa59..d58954a 100644 --- a/src/model.rs +++ b/src/model.rs @@ -412,9 +412,18 @@ pub fn find(key: &str) -> Option<&'static ModelInfo> { /// where models live. xdg if you have it, ~/.cache if you do not. i am not /// going to guess three more conventions and make a mess of your home dir. pub fn cache_dir() -> PathBuf { + #[cfg(test)] + if let Some(dir) = TEST_CACHE_DIR.with(|dir| dir.borrow().clone()) { + return dir; + } crate::util::cache_home().join("scribe").join("models") } +#[cfg(test)] +thread_local! { + static TEST_CACHE_DIR: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + /// What a `--model`/saved value can refer to. Keeping the three forms distinct /// is what makes resolution unambiguous: a catalog name is never also treated /// as a path just because a file with that name happens to exist in `$PWD`. @@ -665,24 +674,30 @@ pub fn partial_size(info: &ModelInfo) -> Option { } pub fn remove_partial(info: &ModelInfo) -> Result<(), String> { - let path = cache_dir().join(format!("{}.part", info.file)); - match fs::remove_file(&path) { - Ok(()) => Ok(()), - Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()), - Err(e) => Err(format!( - "cannot remove partial model {}: {e}", - path.display() - )), - } + let dir = cache_dir(); + remove_cached_files(&dir, info.file, [dir.join(format!("{}.part", info.file))]) } pub fn remove_model(info: &ModelInfo) -> Result<(), String> { let dir = cache_dir(); - for path in [ - dir.join(info.file), - dir.join(format!("{}.part", info.file)), - dir.join(format!(".{}.error", info.file)), - ] { + remove_cached_files( + &dir, + info.file, + [ + dir.join(info.file), + dir.join(format!("{}.part", info.file)), + dir.join(format!(".{}.error", info.file)), + ], + ) +} + +fn remove_cached_files( + dir: &Path, + file: &str, + paths: impl IntoIterator, +) -> Result<(), String> { + let _lock = DownloadLock::acquire(dir, file)?; + for path in paths { match fs::remove_file(&path) { Ok(()) => {} Err(e) if e.kind() == std::io::ErrorKind::NotFound => {} @@ -692,52 +707,89 @@ pub fn remove_model(info: &ModelInfo) -> Result<(), String> { Ok(()) } -/// one process at a time may touch a given partial file. without this, two -/// scribes can append to the same `.part` and each verify the other's debris. +/// The persistent file serializes current processes. The legacy path uses a +/// directory so older downloaders cannot unlink it as a stale lock file. #[derive(Debug)] -struct DownloadLock(PathBuf); +struct DownloadLock { + legacy_marker: PathBuf, + _file: fs::File, +} impl DownloadLock { fn acquire(dir: &Path, file: &str) -> Result { - let path = dir.join(format!(".{file}.lock")); - match fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) + fs::create_dir_all(dir).map_err(|e| format!("cannot create model directory: {e}"))?; + let lock = open_cache_lock(&dir.join(format!(".{file}.cache.lock"))) + .map_err(|e| format!("cannot open model cache lock: {e}"))?; + if !lock + .metadata() + .map_err(|e| format!("cannot inspect model cache lock: {e}"))? + .is_file() { - Ok(_) => Ok(Self(path)), + return Err("model cache lock is not a regular file".into()); + } + match lock.try_lock() { + Ok(()) => {} + Err(fs::TryLockError::WouldBlock) => { + return Err(format!( + "another scribe is using the model cache for {file}" + )); + } + Err(fs::TryLockError::Error(e)) => return Err(format!("cannot lock model cache: {e}")), + } + + let legacy_marker = dir.join(format!(".{file}.lock")); + match fs::create_dir(&legacy_marker) { + Ok(()) => {} Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => { - let stale = fs::metadata(&path) - .and_then(|m| m.modified()) - .map(|t| t.elapsed().unwrap_or_default() > std::time::Duration::from_secs(600)) - .unwrap_or(true); - if stale { - let _ = fs::remove_file(&path); - if fs::OpenOptions::new() - .write(true) - .create_new(true) - .open(&path) - .is_ok() - { - return Ok(Self(path)); - } + // Only versions that take the OS lock create this directory. + // If it survived a crash, the OS lock lets us adopt it safely. + let is_directory = + fs::symlink_metadata(&legacy_marker).is_ok_and(|metadata| metadata.is_dir()); + if !is_directory { + return Err(format!( + "another scribe is using the model cache for {file} (legacy lock at {})", + legacy_marker.display() + )); } - Err(format!( - "another scribe is downloading {file}. wait for it to finish (or remove the stale lock at {})", - path.display() - )) } - Err(e) => Err(format!("cannot create download lock: {e}")), + Err(e) => return Err(format!("cannot create legacy model cache marker: {e}")), } + Ok(Self { + legacy_marker, + _file: lock, + }) } } impl Drop for DownloadLock { fn drop(&mut self) { - let _ = fs::remove_file(&self.0); + let _ = fs::remove_dir(&self.legacy_marker); } } +#[cfg(unix)] +fn open_cache_lock(path: &Path) -> std::io::Result { + use rustix::fs::{Mode, OFlags, open}; + + let flags = + OFlags::RDWR | OFlags::CREATE | OFlags::NONBLOCK | OFlags::NOFOLLOW | OFlags::CLOEXEC; + Ok(open(path, flags, Mode::RUSR | Mode::WUSR).map(File::from)?) +} + +#[cfg(windows)] +fn open_cache_lock(path: &Path) -> std::io::Result { + use std::os::windows::fs::OpenOptionsExt; + + const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x00200000; + fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .truncate(false) + .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT) + .open(path) +} + /// download to a .part file, verify size and sha256, then rename. the rename is /// the commit point: until then, nothing in the cache claims to be a model. pub fn download( @@ -757,7 +809,6 @@ fn download_from( cancel: &std::sync::Arc, on_progress: impl Fn(DownloadProgress), ) -> Result { - fs::create_dir_all(&dir).map_err(|e| format!("cannot create model directory: {e}"))?; let _lock = DownloadLock::acquire(&dir, info.file)?; let final_path = dir.join(info.file); let part = dir.join(format!("{}.part", info.file)); @@ -1249,6 +1300,84 @@ mod tests { fs::remove_dir_all(&dir).unwrap(); } + #[test] + fn public_cache_removals_respect_the_download_lock() { + let dir = std::env::temp_dir().join(format!("scribe-lock-removal-{}", std::process::id())); + let info = tiny_info("unused"); + let model = dir.join(info.file); + let partial = dir.join(format!("{}.part", info.file)); + let error = dir.join(format!(".{}.error", info.file)); + TEST_CACHE_DIR.with(|cache| *cache.borrow_mut() = Some(dir.clone())); + + assert!(!dir.exists()); + remove_partial(&info).unwrap(); + assert!(dir.join(format!(".{}.cache.lock", info.file)).is_file()); + + fs::write(&model, b"model").unwrap(); + fs::write(&partial, b"partial").unwrap(); + fs::write(&error, b"old note").unwrap(); + let lock = DownloadLock::acquire(&dir, info.file).unwrap(); + + assert!( + remove_partial(&info) + .unwrap_err() + .contains("another scribe") + ); + assert!(remove_model(&info).unwrap_err().contains("another scribe")); + assert_eq!(fs::read(&model).unwrap(), b"model"); + assert_eq!(fs::read(&partial).unwrap(), b"partial"); + assert_eq!(fs::read(&error).unwrap(), b"old note"); + + drop(lock); + remove_partial(&info).unwrap(); + assert!(!partial.exists()); + assert!(model.exists()); + assert!(error.exists()); + remove_model(&info).unwrap(); + assert!(!model.exists()); + assert!(!error.exists()); + TEST_CACHE_DIR.with(|cache| *cache.borrow_mut() = None); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn legacy_downloads_contend_and_cannot_remove_the_marker() { + let dir = std::env::temp_dir().join(format!("scribe-legacy-lock-{}", std::process::id())); + fs::create_dir(&dir).unwrap(); + let file = "ggml-test.bin"; + let legacy = dir.join(format!(".{file}.lock")); + File::create_new(&legacy).unwrap(); + assert!( + DownloadLock::acquire(&dir, file) + .unwrap_err() + .contains("legacy lock") + ); + fs::remove_file(&legacy).unwrap(); + + // A previous new-version process could have exited before dropping the marker. + fs::create_dir(&legacy).unwrap(); + let lock = DownloadLock::acquire(&dir, file).unwrap(); + assert!(File::create_new(&legacy).is_err()); + assert!(fs::remove_file(&legacy).is_err()); + assert!(legacy.is_dir()); + drop(lock); + + File::create_new(&legacy).unwrap(); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn cache_lock_rejects_a_directory() { + let dir = std::env::temp_dir().join(format!("scribe-nonfile-lock-{}", std::process::id())); + let file = "ggml-test.bin"; + let lock_path = dir.join(format!(".{file}.cache.lock")); + fs::create_dir_all(&lock_path).unwrap(); + assert!(DownloadLock::acquire(&dir, file).is_err()); + assert!(lock_path.is_dir()); + assert!(!dir.join(format!(".{file}.lock")).exists()); + fs::remove_dir_all(&dir).unwrap(); + } + #[test] fn validate_custom_rejects_stubs_and_wrong_headers() { let dir = std::env::temp_dir().join(format!("scribe-custom-{}", std::process::id())); diff --git a/src/util.rs b/src/util.rs index 67d64cd..4dd1a0a 100644 --- a/src/util.rs +++ b/src/util.rs @@ -691,7 +691,7 @@ mod tests { assert!(!is_youtube_url( "https://notyoutube.com.evil.test/watch?v=x" )); - assert!(!youtube_id("https://notyoutube.com.evil.test/watch?v=x").is_some()); + assert!(youtube_id("https://notyoutube.com.evil.test/watch?v=x").is_none()); assert!(is_youtube_url("https://www.youtube.com/watch?v=abc")); assert_eq!( youtube_id("https://www.youtube.com/watch?v=abc"),