diff options
| author | rorka900 <rorka900@gmail.com> | 2026-04-24 17:53:49 +0300 |
|---|---|---|
| committer | rorka900 <rorka900@gmail.com> | 2026-04-24 17:53:49 +0300 |
| commit | 9c9ce088193c2506da372c76685076bbfead0690 (patch) | |
| tree | 8eacd30624a4d6da552f8de44a1e1273bfede3d4 /src/parallel.rs | |
| parent | f2ab400fb6750fbe017309757f06339437b7c4b8 (diff) | |
| download | ror-9c9ce088193c2506da372c76685076bbfead0690.tar.gz ror-9c9ce088193c2506da372c76685076bbfead0690.zip | |
feat: modernize CLI with clap subcommands and add declarative apply1.0.0-r1
Diffstat (limited to 'src/parallel.rs')
| -rw-r--r-- | src/parallel.rs | 737 |
1 files changed, 341 insertions, 396 deletions
diff --git a/src/parallel.rs b/src/parallel.rs index b8b201b..fbbbcfe 100644 --- a/src/parallel.rs +++ b/src/parallel.rs @@ -1,480 +1,425 @@ -use std::collections::{HashMap, HashSet, VecDeque}; +// 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::thread; -use crate::config::Config; -use crate::install::{self, Dependency, InstalledDB, load_package, parse_dep, version_satisfies, get_package_info}; +use std::time::Duration; +use std::io::Write; + use colored::Colorize; -use crate::debug; +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<Mutex<HashMap<String, Arc<Package>>>> = + 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<Arc<Package>> { + let mut cache = PACKAGE_CACHE.lock().unwrap(); + if let Some(pkg) = cache.get(name) { + return Some(Arc::clone(pkg)); + } -type Result<T> = std::result::Result<T, String>; + let path = crate::install::find_package_file(name)?; + let content = std::fs::read_to_string(path).ok()?; + let pkg = serde_yaml::from_str::<Package>(&content).ok()?; -struct DependencyGraph { - edges: HashMap<String, Vec<String>>, - reverse: HashMap<String, Vec<String>>, + let arc = Arc::new(pkg); + cache.insert(arc.name.clone(), Arc::clone(&arc)); + Some(arc) } -impl DependencyGraph { - fn new() -> Self { - debug!("DependencyGraph::new()"); - Self { edges: HashMap::new(), reverse: HashMap::new() } +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, +} - fn add_dep(&mut self, pkg: String, dep: String) { - debug!("DependencyGraph::add_dep: {} -> {}", pkg, dep); - self.edges.entry(pkg.clone()).or_insert_with(Vec::new).push(dep.clone()); - self.reverse.entry(dep).or_insert_with(Vec::new).push(pkg); +impl AtomicInstaller { + fn new(shadow: tempfile::TempDir) -> Self { + Self { shadow } } - fn compute_levels(&self) -> Vec<Vec<String>> { - debug!("DependencyGraph::compute_levels: start, edges={}", self.edges.len()); - let mut in_degree: HashMap<String, usize> = HashMap::new(); - for (pkg, deps) in &self.edges { - in_degree.entry(pkg.clone()).or_insert(0); - for dep in deps { - *in_degree.entry(dep.clone()).or_insert(0) += 1; - } - } - for (pkg, children) in &self.reverse { - in_degree.entry(pkg.clone()).or_insert(0); - for child in children { - in_degree.entry(child.clone()).or_insert(0); - } - } - let mut levels = Vec::new(); - let mut queue: VecDeque<String> = in_degree.iter() - .filter(|&(_, °)| deg == 0) - .map(|(pkg, _)| pkg.clone()) - .collect(); - debug!("compute_levels: initial zero-degree queue size={}", queue.len()); - while !queue.is_empty() { - let level_pkgs: Vec<String> = queue.drain(..).collect(); - debug!("compute_levels: level {} packages={:?}", levels.len(), level_pkgs); - levels.push(level_pkgs.clone()); - for pkg in &level_pkgs { - if let Some(children) = self.reverse.get(pkg) { - for child in children { - if let Some(deg) = in_degree.get_mut(child) { - *deg -= 1; - debug!("compute_levels: {} in_degree -> {}", child, deg); - if *deg == 0 { - debug!("compute_levels: {} ready, adding to queue", child); - queue.push_back(child.clone()); - } - } - } - } + fn commit( + self, + files: &[String], + src_dir: &Path, + target_root: &str, + ) -> Result<Vec<String>, 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 cyclic: Vec<_> = in_degree.iter() - .filter(|&(_, &d)| d > 0) - .map(|(name, _)| name.as_str()) - .collect(); - if !cyclic.is_empty() { - eprintln!( - "{} Warning: cycle detected among packages, they will be installed in arbitrary order", - "[ror]".yellow().bold() - ); - debug!("compute_levels: CYCLE detected among: {:?}", cyclic); - } - debug!("compute_levels: total levels={}", levels.len()); - levels - } -} -#[allow(dead_code)] -fn dep_name(raw: &str) -> String { - let (name, _) = parse_dep(raw); - name -} + let parent = dst.parent().ok_or("Invalid path")?; + std::fs::create_dir_all(parent) + .map_err(|e| format!("Create parent {}: {}", parent.display(), e))?; -fn is_dep_satisfied(raw: &str, db: &InstalledDB) -> bool { - let (name, constraint) = parse_dep(raw); - match db.packages.get(&name) { - None => { - debug!("is_dep_satisfied: '{}' not installed", name); - false - } - Some(installed) => { - match constraint { - None => { - debug!("is_dep_satisfied: '{}' installed (no version req)", name); - true + 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)); } - Some(c) => { - let ok = version_satisfies(&installed.version, &c); - debug!( - "is_dep_satisfied: '{}' installed={} required={:?}{} ok={}", - name, installed.version, c.op, c.version, ok - ); - ok + 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()); } - } -} -fn needs_update(raw: &str, db: &InstalledDB) -> bool { - let (name, constraint) = parse_dep(raw); - match db.packages.get(&name) { - None => false, - Some(installed) => match constraint { - None => false, - Some(c) => { - let ok = version_satisfies(&installed.version, &c); - if !ok { - debug!("needs_update: '{}' installed={} fails {:?}{}", name, installed.version, c.op, c.version); - } - !ok + for (bak, _) in backup_paths { + if bak.exists() { + let _ = std::fs::remove_file(&bak); } - }, + } + + Ok(installed) } } -fn collect_required_packages( - packages: &[String], - installed_db: &InstalledDB, - outdated: &mut HashSet<String>, -) -> Result<HashSet<String>> { - debug!("collect_required_packages: start with {:?}", packages); - let mut required = HashSet::new(); - let mut stack: Vec<String> = packages.iter().cloned().collect(); - - while let Some(pkg_name) = stack.pop() { - debug!("collect_required_packages: processing '{}'", pkg_name); - - if required.contains(&pkg_name) { - debug!("collect_required_packages: '{}' already in required set, skip", pkg_name); - continue; +async fn download_one(url: &str, expected_sha: &str, _cfg: &Config) -> Result<PathBuf, String> { + 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)); } - if installed_db.is_installed(&pkg_name) { - let needs_ver_update = get_package_info(&pkg_name).map(|(_, avail)| { - let inst_ver = &installed_db.packages[&pkg_name].version; - let newer = avail != *inst_ver && avail > *inst_ver; - debug!("collect_required_packages: '{}' installed={} available={} newer={}", pkg_name, inst_ver, avail, newer); - newer - }).unwrap_or(false); - - if needs_ver_update { - debug!("collect_required_packages: '{}' outdated, queuing for update", pkg_name); - outdated.insert(pkg_name.clone()); - required.insert(pkg_name.clone()); - } else { - debug!("collect_required_packages: '{}' up-to-date, skip", pkg_name); - let pkg = match load_package(&pkg_name) { - Some(p) => p, - None => continue, - }; - for dep in &pkg.depends { - match dep { - Dependency::Single(raw) => { - if needs_update(raw, installed_db) { - let (name, _) = parse_dep(raw); - debug!("collect_required_packages: dep '{}' of '{}' is outdated", name, pkg_name); - outdated.insert(name.clone()); - if !required.contains(&name) { stack.push(name); } - } - } - Dependency::Any(alts) => { - for alt in alts { - if needs_update(alt, installed_db) { - let (name, _) = parse_dep(alt); - debug!("collect_required_packages: alt dep '{}' of '{}' is outdated", name, pkg_name); - outdated.insert(name.clone()); - if !required.contains(&name) { stack.push(name); } - } - } - } - } - } - continue; - } - } else { - required.insert(pkg_name.clone()); - } + 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 pkg = match load_package(&pkg_name) { - Some(p) => p, - None => { - debug!("collect_required_packages: '{}' not found in repo", pkg_name); - return Err(format!("Package '{}' not found", pkg_name)); - } - }; - - debug!("collect_required_packages: '{}' has {} deps", pkg_name, pkg.depends.len()); - - for dep in &pkg.depends { - match dep { - Dependency::Single(raw) => { - let (name, _) = parse_dep(raw); - debug!("collect_required_packages: single dep '{}' for '{}'", raw, pkg_name); - if !is_dep_satisfied(raw, installed_db) && !required.contains(&name) { - debug!("collect_required_packages: queuing dep '{}'", name); - stack.push(name); - } - } - Dependency::Any(alternatives) => { - debug!("collect_required_packages: any dep {:?} for '{}'", alternatives, pkg_name); - let satisfied = alternatives.iter().any(|a| is_dep_satisfied(a, installed_db)); - if satisfied { - debug!("collect_required_packages: any dep already satisfied for '{}'", pkg_name); - continue; - } - if let Some(first) = alternatives.first() { - let (name, _) = parse_dep(first); - debug!("collect_required_packages: choosing first alt '{}' for '{}'", name, pkg_name); - if !required.contains(&name) { stack.push(name); } - } else { - return Err(format!("Empty alternative list in package '{}'", pkg_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 + )); } } - } - debug!("collect_required_packages: required={:?} outdated={:?}", required, outdated); - Ok(required) + Ok(file_path) + }) + .await + .unwrap_or_else(|_| Err("Download timed out".into())); + + result } -fn build_graph(packages: &HashSet<String>, installed_db: &InstalledDB) -> Result<DependencyGraph> { - debug!("build_graph: building for {} packages", packages.len()); - let mut graph = DependencyGraph::new(); - - for pkg_name in packages { - debug!("build_graph: processing '{}'", pkg_name); - let pkg = match load_package(pkg_name) { - Some(p) => p, - None => { - debug!("build_graph: '{}' not found", pkg_name); - return Err(format!("Package '{}' not found", pkg_name)); - } - }; - - for dep in &pkg.depends { - match dep { - Dependency::Single(raw) => { - let (name, _) = parse_dep(raw); - if packages.contains(&name) { - debug!("build_graph: edge {} -> {}", pkg_name, name); - graph.add_dep(pkg_name.clone(), name.clone()); - } else if !is_dep_satisfied(raw, installed_db) { - debug!("build_graph: missing dep '{}' for '{}'", name, pkg_name); - return Err(format!("Dependency '{}' of '{}' is missing or unsatisfied", raw, pkg_name)); - } else { - debug!("build_graph: dep '{}' already satisfied outside graph", name); - } - } - Dependency::Any(alternatives) => { - debug!("build_graph: any dep {:?} for '{}'", alternatives, pkg_name); - let found = alternatives.iter().find(|a| { - let (n, _) = parse_dep(a); - packages.contains(&n) - }); - if let Some(chosen) = found { - let (name, _) = parse_dep(chosen); - debug!("build_graph: choosing alt '{}' for '{}'", name, pkg_name); - graph.add_dep(pkg_name.clone(), name.clone()); - } else { - let satisfied = alternatives.iter().any(|a| is_dep_satisfied(a, installed_db)); - if !satisfied { - debug!("build_graph: no available alt for '{}'", pkg_name); - return Err(format!("No alternative from {:?} for '{}' is available", alternatives, pkg_name)); - } - debug!("build_graph: alt dep for '{}' satisfied outside graph", pkg_name); +/*race-condition download: tries all mirrors and returns the first success. */ +async fn race_download( + urls: Vec<String>, + expected_sha: &str, + cfg: Arc<Config>, +) -> 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::<Result<(PathBuf, String), String>>(); + 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(_) => {} } - } + })); } - debug!("build_graph: done, graph has {} nodes", graph.edges.len()); - Ok(graph) + match rx.await { + Ok(Ok((path, win_url))) => { + for h in handles { + h.abort(); + } + Ok((path, win_url)) + } + _ => Err("All mirrors failed".into()), + } } -fn check_conflicts(required: &HashSet<String>, installed_db: &InstalledDB) -> Result<()> { - debug!("check_conflicts: checking {} packages", required.len()); - let mut pkg_map = HashMap::new(); +async fn install_single_impl( + pkg_name: &str, + cfg: Arc<Config>, +) -> Result<InstalledPackage, String> { + println!("[{}] Resolving {}...", "[ror]".cyan().bold(), pkg_name); - for pkg_name in required { - let pkg = match load_package(pkg_name) { - Some(p) => p, - None => { - debug!("check_conflicts: '{}' not found", pkg_name); - return Err(format!("Package '{}' not found", pkg_name)); - } - }; - pkg_map.insert(pkg_name.clone(), pkg); - } + let start_time = std::time::Instant::now(); - for (name, pkg) in &pkg_map { - for conflict in &pkg.conflicts { - if installed_db.is_installed(conflict) { - debug!("check_conflicts: '{}' conflicts with installed '{}'", name, conflict); - return Err(format!("Package '{}' conflicts with installed package '{}'", name, conflict)); + 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); } } } - let names: Vec<_> = pkg_map.keys().cloned().collect(); - for i in 0..names.len() { - for j in i + 1..names.len() { - let a = &names[i]; - let b = &names[j]; - let pkg_a = &pkg_map[a]; - let pkg_b = &pkg_map[b]; - if pkg_a.conflicts.contains(b) || pkg_b.conflicts.contains(a) { - debug!("check_conflicts: '{}' and '{}' conflict each other", a, b); - return Err(format!("Packages '{}' and '{}' conflict with each other", a, b)); - } - } + if urls.is_empty() { + return Err("No download URLs provided".to_string()); } - debug!("check_conflicts: no conflicts"); - Ok(()) -} + 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); -fn install_single_package(pkg_name: &str, cfg: Arc<Config>, db_mutex: &Mutex<InstalledDB>) -> Result<()> { - debug!("install_single_package: start '{}'", pkg_name); - println!("{} Installing {}...", ">>>".cyan(), pkg_name); + verify_gpg_signature(&archive_path, &asc_path, &key_full_path) + .map_err(|e| format!("GPG Verification Failed: {}", e))?; - let installed_pkg = match install::install_package_with_result(pkg_name, &*cfg) { - Ok(p) => { - debug!("install_single_package: '{}' installed successfully v{}", pkg_name, p.version); - p + let _ = std::fs::remove_file(&asc_path); } - Err(e) => { - debug!("install_single_package: '{}' failed: {}", pkg_name, e); - return Err(e); + } + + 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)? } }; - let mut db = db_mutex.lock().unwrap(); - debug!("install_single_package: acquired db lock for '{}'", pkg_name); - db.add_package(installed_pkg); + println!("[{}] Installing {}...", "[ror]".yellow(), pkg_name); - if let Err(e) = db.save() { - debug!("install_single_package: db save failed for '{}': {}", pkg_name, e); - eprintln!("{} Failed to save installed DB: {}", "[ror]".red().bold(), e); - return Err(format!("Failed to save installed DB: {}", e)); - } + let installer = AtomicInstaller::new(shadow); + let installed_files = + installer.commit(&files_extracted, &work_dir, &binary.install_prefix)?; - debug!("install_single_package: '{}' registered in db", pkg_name); - println!("{} Package registered in database", "[ror]".green()); - Ok(()) + 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 fn install_packages_parallel(packages: &[String], cfg: Arc<Config>) -> Result<()> { - debug!("install_packages_parallel: called with {:?}", packages); - let installed_db = InstalledDB::load(); - debug!("install_packages_parallel: loaded installed db, {} packages", installed_db.packages.len()); +pub async fn install_packages_parallel( + packages: &[String], + cfg: Arc<Config>, +) -> Result<(), String> { + println!("[>] Starting package synchronization..."); - let mut outdated: HashSet<String> = HashSet::new(); - let required = collect_required_packages(packages, &installed_db, &mut outdated)?; + let ctrl_c_handle = tokio::spawn(async { + tokio::signal::ctrl_c().await.ok(); + INTERRUPTED.store(true, Ordering::SeqCst); + }); - if !outdated.is_empty() { - println!("{} Outdated dependencies detected: {}", "[ror]".yellow().bold(), outdated.iter().cloned().collect::<Vec<_>>().join(", ").yellow()); - debug!("install_packages_parallel: outdated set={:?}", outdated); - } + 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!("{} All packages already installed and up-to-date.", "[ror]".green()); - debug!("install_packages_parallel: nothing to install"); + println!("[>] Nothing to install."); + ctrl_c_handle.abort(); return Ok(()); } - debug!("install_packages_parallel: required={:?}", required); - check_conflicts(&required, &installed_db)?; + resolver::check_conflicts(&required, &installed_db)?; + let graph = resolver::build_graph(&required, &installed_db)?; + let levels = graph.compute_levels(); - let graph = build_graph(&required, &installed_db)?; - let mut levels = graph.compute_levels(); + let mut total_installed: Vec<InstalledPackage> = Vec::new(); - if levels.is_empty() && !required.is_empty() { - debug!("install_packages_parallel: no edges, using flat level"); - levels.push(required.iter().cloned().collect()); - } - - let total_pkgs: usize = levels.iter().map(|l| l.len()).sum(); - let mut installed_count = 0usize; - - println!( - "{} Installing {} package(s) across {} level(s)", - "[ror]".blue().bold(), - total_pkgs, - levels.len() - ); - debug!("install_packages_parallel: total={} levels={}", total_pkgs, levels.len()); - - let db_mutex = Arc::new(Mutex::new(InstalledDB::load())); - - for (level_idx, level_pkgs) in levels.into_iter().enumerate() { - println!("{} Level {}: {} package(s)", ">>>".cyan(), level_idx, level_pkgs.len()); - debug!("install_packages_parallel: starting level {} pkgs={:?}", level_idx, level_pkgs); + 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()); + } - let level_total = level_pkgs.len(); - let mut handles = Vec::new(); + 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(); - let cfg = Arc::clone(&cfg); - let db_mutex = Arc::clone(&db_mutex); - let is_outdated = outdated.contains(&pkg_name); - debug!("install_packages_parallel: spawning thread for '{}' (outdated={})", pkg_name, is_outdated); - - let handle = thread::spawn(move || { - if is_outdated { - debug!("install_single_package: '{}' is outdated, removing old version first", pkg_name); - let db = db_mutex.lock().unwrap(); - let files = db.packages.get(&pkg_name).map(|p| p.files.clone()).unwrap_or_default(); - drop(db); - crate::delete::remove_package_files_only(&pkg_name, &files); - let mut db = db_mutex.lock().unwrap(); - db.packages.remove(&pkg_name); - drop(db); - } - install_single_package(&pkg_name, cfg, &db_mutex) - }); - handles.push((pkg, handle)); + tasks.push(tokio::spawn(async move { + install_single_impl(&pkg_name, c).await + })); } - let mut errors = Vec::new(); - let mut level_done = 0usize; - - for (pkg_name, handle) in handles { - match handle.join() { - Ok(Ok(())) => { - installed_count += 1; - level_done += 1; - debug!("install_packages_parallel: '{}' done ({}/{})", pkg_name, installed_count, total_pkgs); - eprint!( - "\r\x1b[K\x1b[36m[{:>3}/{:<3}]\x1b[0m level {}, total {}/{} {}", - level_done, level_total, level_idx, installed_count, total_pkgs, pkg_name - ); - use std::io::Write; - std::io::stderr().flush().ok(); + 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)) => { - debug!("install_packages_parallel: '{}' error: {}", pkg_name, e); - errors.push(e); + level_errors.push((level_pkgs[i].clone(), e)); } - Err(_) => { - debug!("install_packages_parallel: '{}' thread panicked", pkg_name); - errors.push(format!("Thread panicked for '{}'", pkg_name)); + Err(join_err) => { + level_errors.push((level_pkgs[i].clone(), join_err.to_string())); } } } - eprintln!(); + 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)); + } - if !errors.is_empty() { - eprintln!("{} Errors at level {}: {:?}", "[ror]".red().bold(), level_idx, errors); - debug!("install_packages_parallel: level {} failed with {} errors", level_idx, errors.len()); - return Err(format!("Installation failed at level {}", 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()); } - debug!("install_packages_parallel: level {} complete", level_idx); + 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)); + } } - println!("{} All packages installed successfully.", "[ror]".green().bold()); - debug!("install_packages_parallel: all done"); + ctrl_c_handle.abort(); + println!("[>] Synchronization completed successfully."); Ok(()) } |