// parallel.rs // Asynchronous package installation with race conditions, atomic updates. #![allow(dead_code)] #![allow(unused_imports)] #![allow(unused_variables)] use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; use std::io::Write; use colored::Colorize; use futures::StreamExt; use sha2::{Digest, Sha256}; use tokio::sync::oneshot; use tokio::task; use tokio::time::timeout; use tempfile::NamedTempFile; use crate::config::Config; use crate::install::{ extract_deb, extract_ror, extract_sror, extract_native, select_binary_for_arch, InstalledDB, InstalledPackage, Package, find_package_with_repo, verify_gpg_signature, }; use crate::resolver; /*global cache for package metadata to avoid repeated yaml parsing. */ static PACKAGE_CACHE: once_cell::sync::Lazy>>> = once_cell::sync::Lazy::new(|| Mutex::new(HashMap::new())); /*flag to detect user interruption. */ static INTERRUPTED: AtomicBool = AtomicBool::new(false); pub fn load_package_cached(name: &str) -> Option> { let mut cache = PACKAGE_CACHE.lock().unwrap(); if let Some(pkg) = cache.get(name) { return Some(Arc::clone(pkg)); } let path = crate::install::find_package_file(name)?; let content = std::fs::read_to_string(path).ok()?; let pkg = serde_yaml::from_str::(&content).ok()?; let arc = Arc::new(pkg); cache.insert(arc.name.clone(), Arc::clone(&arc)); Some(arc) } impl InstalledDB { pub fn save_atomic(&self, path: &Path) -> std::io::Result<()> { let json = serde_json::to_string_pretty(self)?; let dir = path.parent().unwrap(); let mut tmp_file = NamedTempFile::new_in(dir)?; tmp_file.write_all(json.as_bytes())?; tmp_file.persist(path)?; Ok(()) } } struct AtomicInstaller { shadow: tempfile::TempDir, } impl AtomicInstaller { fn new(shadow: tempfile::TempDir) -> Self { Self { shadow } } fn commit( self, files: &[String], src_dir: &Path, target_root: &str, ) -> Result, String> { let prefix = Path::new(target_root); let mut installed = Vec::new(); let mut backup_paths: Vec<(PathBuf, PathBuf)> = Vec::new(); for rel_path in files { let src = src_dir.join(rel_path); let dst = prefix.join(rel_path); if !src.exists() { continue; } let parent = dst.parent().ok_or("Invalid path")?; std::fs::create_dir_all(parent) .map_err(|e| format!("Create parent {}: {}", parent.display(), e))?; let bak_path = dst.with_extension("ror-old"); if dst.exists() && dst.is_file() { if let Err(e) = std::fs::rename(&dst, &bak_path) { return Err(format!("Cannot backup {}: {}", dst.display(), e)); } backup_paths.push((bak_path, dst.clone())); } if let Err(e) = std::fs::rename(&src, &dst) { if let Some((last_bak, orig)) = backup_paths.pop() { let _ = std::fs::rename(&last_bak, &orig); } return Err(format!("Failed to install {}: {}", dst.display(), e)); } installed.push(rel_path.clone()); } for (bak, _) in backup_paths { if bak.exists() { let _ = std::fs::remove_file(&bak); } } Ok(installed) } } async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result { let result = timeout(Duration::from_secs(60), async { let client = reqwest::Client::builder() .timeout(Duration::from_secs(30)) .build() .map_err(|e| format!("HTTP client builder: {}", e))?; let res = client .get(url) .send() .await .map_err(|e| e.to_string())?; if !res.status().is_success() { return Err(format!("HTTP {} for {}", res.status(), url)); } let tmp_dir = Path::new("/tmp/ror-download"); std::fs::create_dir_all(tmp_dir).map_err(|e| e.to_string())?; let file_name = url.rsplit('/').next().unwrap_or("archive.tmp"); let file_path = tmp_dir.join(file_name); let mut file = std::fs::File::create(&file_path).map_err(|e| e.to_string())?; let mut hasher = Sha256::new(); let body = res.bytes().await.map_err(|e| e.to_string())?; hasher.update(&body); file.write_all(&body).map_err(|e| e.to_string())?; drop(file); if !expected_sha.is_empty() { let hash = format!("{:x}", hasher.finalize()); if hash != expected_sha { let _ = std::fs::remove_file(&file_path); return Err(format!( "SHA256 mismatch: expected {}, got {}", expected_sha, hash )); } } Ok(file_path) }) .await .unwrap_or_else(|_| Err("Download timed out".into())); result } /*race-condition download: tries all mirrors and returns the first success. */ async fn race_download( urls: Vec, expected_sha: &str, cfg: Arc, ) -> Result<(PathBuf, String), String> { if urls.len() == 1 { let p = download_one(&urls[0], expected_sha, &cfg).await?; return Ok((p, urls[0].clone())); } let (tx, rx) = oneshot::channel::>(); let tx = Arc::new(Mutex::new(Some(tx))); let mut handles = Vec::new(); for url in urls { let tx_clone = Arc::clone(&tx); let cfg_clone = cfg.clone(); let sha = expected_sha.to_string(); handles.push(task::spawn(async move { match download_one(&url, &sha, &cfg_clone).await { Ok(path) => { let mut guard = tx_clone.lock().unwrap(); if let Some(sender) = guard.take() { let _ = sender.send(Ok((path, url))); } } Err(_) => {} } })); } match rx.await { Ok(Ok((path, win_url))) => { for h in handles { h.abort(); } Ok((path, win_url)) } _ => Err("All mirrors failed".into()), } } async fn install_single_impl( pkg_name: &str, cfg: Arc, ) -> Result { println!("[{}] Resolving {}...", "[ror]".cyan().bold(), pkg_name); let start_time = std::time::Instant::now(); let pkg = load_package_cached(pkg_name) .ok_or_else(|| format!("Package '{}' not found", pkg_name))?; let (_, repo_name) = find_package_with_repo(pkg_name) .ok_or_else(|| format!("Repository info not found for {}", pkg_name))?; let repo_cfg = cfg.repositories.get(&repo_name); let binary = select_binary_for_arch(&pkg, &cfg.global.arch, &cfg.global.libc)?; let mut urls = Vec::new(); if !binary.url.is_empty() { urls.push(binary.url.clone()); } else { for m in &binary.mirrors { let url = m.replace("{filename}", &binary.filename); if url.starts_with("http") { urls.push(url); } } } if urls.is_empty() { return Err("No download URLs provided".to_string()); } println!("[{}] Downloading {}...", "[ror]".blue(), pkg_name); let (archive_path, winning_url) = race_download(urls, &binary.sha256, cfg.clone()).await?; /*gpg verification */ if repo_cfg.map(|r| r.gpg_support).unwrap_or(false) { if let Some(key_file) = repo_cfg.and_then(|r| r.gpg_key.as_deref()) { let asc_url = format!("{}.asc", winning_url); println!("[{}] Verifying GPG...", "[ror]".cyan()); let asc_path = match timeout( Duration::from_secs(30), download_one(&asc_url, "", &cfg), ) .await { Ok(Ok(p)) => p, Ok(Err(e)) => { return Err(format!( "GPG signature download failed {}: {}", asc_url, e )) } Err(_) => { return Err(format!( "GPG signature download timed out: {}", asc_url )) } }; let key_full_path = Path::new("/var/ror/packages").join(key_file); verify_gpg_signature(&archive_path, &asc_path, &key_full_path) .map_err(|e| format!("GPG Verification Failed: {}", e))?; let _ = std::fs::remove_file(&asc_path); } } println!("[{}] Extracting {}...", "[ror]".green(), pkg_name); let shadow = tempfile::tempdir().map_err(|e| e.to_string())?; let work_dir = shadow.path().join("root"); std::fs::create_dir_all(&work_dir).map_err(|e| e.to_string())?; let files_extracted = { let ptype = binary.pkg_type.as_deref().unwrap_or("tar.xz"); if ptype == "deb" { extract_deb(&archive_path, &work_dir)? } else if ptype == "ror" { let dict = binary.dict.as_ref().ok_or("Missing dict URL")?; let dict_path = download_one(dict, "", &cfg).await?; let f = extract_ror(&archive_path, &dict_path, &work_dir)?; let _ = std::fs::remove_file(&dict_path); f } else if ptype == "sror" { extract_sror(&archive_path, &work_dir)? } else { extract_native(&archive_path, &work_dir)? } }; println!("[{}] Installing {}...", "[ror]".yellow(), pkg_name); let installer = AtomicInstaller::new(shadow); let installed_files = installer.commit(&files_extracted, &work_dir, &binary.install_prefix)?; let _ = std::fs::remove_file(&archive_path); let elapsed = start_time.elapsed().as_millis(); println!("[>] Installed {} ({:.2}ms)", pkg_name, elapsed as f64); Ok(InstalledPackage { name: pkg.name.clone(), version: pkg.version.clone(), libc: pkg.libc.clone(), files: installed_files, installed_at: chrono::Local::now().to_rfc3339(), }) } pub async fn install_packages_parallel( packages: &[String], cfg: Arc, ) -> Result<(), String> { println!("[>] Starting package synchronization..."); let ctrl_c_handle = tokio::spawn(async { tokio::signal::ctrl_c().await.ok(); INTERRUPTED.store(true, Ordering::SeqCst); }); let installed_db = InstalledDB::load(); let mut outdated = HashSet::new(); let required = resolver::collect_required_packages(packages, &installed_db, &mut outdated)?; if required.is_empty() { println!("[>] Nothing to install."); ctrl_c_handle.abort(); return Ok(()); } resolver::check_conflicts(&required, &installed_db)?; let graph = resolver::build_graph(&required, &installed_db)?; let levels = graph.compute_levels(); let mut total_installed: Vec = Vec::new(); for (level_idx, level_pkgs) in levels.iter().enumerate() { if INTERRUPTED.load(Ordering::SeqCst) { println!("[!] Interrupted by user."); ctrl_c_handle.abort(); return Err("Installation aborted".to_string()); } println!( "[>] Level {} installing {} packages...", level_idx, level_pkgs.len() ); let mut tasks = Vec::new(); for pkg in level_pkgs { let c = cfg.clone(); let pkg_name = pkg.clone(); tasks.push(tokio::spawn(async move { install_single_impl(&pkg_name, c).await })); } let results: Vec<_> = futures::future::join_all(tasks).await; let mut level_errors = Vec::new(); for (i, res) in results.into_iter().enumerate() { match res { Ok(Ok(pkg)) => { total_installed.push(pkg); } Ok(Err(e)) => { level_errors.push((level_pkgs[i].clone(), e)); } Err(join_err) => { level_errors.push((level_pkgs[i].clone(), join_err.to_string())); } } } if !level_errors.is_empty() { println!("[X] Errors at level {}:", level_idx); for (name, err) in &level_errors { println!(" [!] {}: {}", name.red(), err); } ctrl_c_handle.abort(); return Err(format!("Level {} failed", level_idx)); } /*save db after every level to prevent inconsistent state */ let mut db = InstalledDB::load(); for pkg in &total_installed { db.add_package(pkg.clone()); } let path = Path::new(InstalledDB::PATH); if let Err(e) = db.save_atomic(path) { eprintln!("[X] Failed to save database: {}", e); ctrl_c_handle.abort(); return Err(format!("Failed to save DB: {}", e)); } } ctrl_c_handle.abort(); println!("[>] Synchronization completed successfully."); Ok(()) }