From fc13100db28fa29a72d61c212df7e3ced45644e3 Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Tue, 15 Jul 2025 17:39:41 +0200 Subject: [PATCH 01/15] feat: Integrate `uv` into `tower-runtime` --- Cargo.toml | 1 + crates/tower-runtime/Cargo.toml | 1 + crates/tower-runtime/src/local.rs | 112 ++--------- crates/tower-uv/Cargo.toml | 16 ++ crates/tower-uv/src/install.rs | 305 ++++++++++++++++++++++++++++++ crates/tower-uv/src/lib.rs | 115 +++++++++++ 6 files changed, 453 insertions(+), 97 deletions(-) create mode 100644 crates/tower-uv/Cargo.toml create mode 100644 crates/tower-uv/src/install.rs create mode 100644 crates/tower-uv/src/lib.rs diff --git a/Cargo.toml b/Cargo.toml index 151b0644..2f25c280 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,7 @@ tower-cmd = { path = "crates/tower-cmd" } tower-package = { path = "crates/tower-package" } tower-runtime = { path = "crates/tower-runtime" } tower-telemetry = { path = "crates/tower-telemetry" } +tower-uv = { path = "crates/tower-uv" } tracing = { version = "0.1" } tracing-appender = "0.2" tracing-subscriber = { version = "0.3", features = ["json", "env-filter"] } diff --git a/crates/tower-runtime/Cargo.toml b/crates/tower-runtime/Cargo.toml index 184a5be6..5ecaf2b5 100644 --- a/crates/tower-runtime/Cargo.toml +++ b/crates/tower-runtime/Cargo.toml @@ -12,3 +12,4 @@ tokio = { workspace = true } snafu = { workspace = true } tower-package = { workspace = true } tower-telemetry = { workspace = true } +tower-uv = { workspace = true } diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index 9a82efd4..ac108598 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -127,6 +127,9 @@ async fn find_bash() -> Result { impl App for LocalApp { async fn start(opts: StartOptions) -> Result { + // We need a uv instance to run the actual app. + let uv = tower_uv::Uv::new(); + let ctx = opts.ctx.clone(); let package = opts.package; let environment = opts.environment; @@ -149,69 +152,6 @@ impl App for LocalApp { opts.cwd.unwrap_or(package_path.to_path_buf()) }; - let mut is_virtualenv = false; - - if Path::new(&working_dir.join("requirements.txt")).exists() { - debug!(ctx: &ctx, "requirements.txt file found. installing dependencies"); - - // There's a requirements.txt, so we'll create a new virtualenv and install the files - // taht we want in there. - let res = Command::new(python_path) - .current_dir(&working_dir) - .arg("-m") - .arg("venv") - .arg(".venv") - .kill_on_drop(true) - .spawn(); - - if let Ok(mut child) = res { - // Wait for the child to complete entirely. - child.wait().await.expect("child failed to exit"); - } else { - return Err(Error::VirtualEnvCreationFailed); - } - - let pip_path = find_pip(working_dir.join(".venv").join("bin")).await?; - - // We need to update our local python, too - // - // TODO: Find a better way to operate in the context of a virtual env here. - python_path = find_python(Some(working_dir.join(".venv").join("bin"))).await?; - debug!(ctx: &ctx, "using virtualenv python at {:?}", python_path); - - is_virtualenv = true; - - let res = Command::new(pip_path) - .current_dir(&working_dir) - .arg("install") - .arg("-r") - .arg(working_dir.join("requirements.txt")) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .kill_on_drop(true) - .spawn(); - - if let Ok(mut child) = res { - if let Some(ref sender) = opts.output_sender { - // Let's also send our logs to this output channel. - let stdout = child.stdout.take().expect("no stdout"); - tokio::spawn(drain_output(FD::Stdout, Channel::Setup, sender.clone(), BufReader::new(stdout))); - - let stderr = child.stderr.take().expect("no stderr"); - tokio::spawn(drain_output(FD::Stderr, Channel::Setup, sender.clone(), BufReader::new(stderr))); - - } - - debug!(ctx: &ctx, "waiting for dependency installation to complete"); - - // Wait for the child to complete entirely. - child.wait().await.expect("child failed to exit"); - } - } else { - debug!(ctx: &ctx, "missing requirements.txt file found. no dependencies to install"); - } - debug!(ctx: &ctx, " - working directory: {:?}", &working_dir); let res = if package.manifest.invoke.ends_with(".sh") { @@ -220,13 +160,12 @@ impl App for LocalApp { let params= opts.parameters; let other_env_vars = opts.env_vars; - Self::execute_bash_program(&ctx, &environment, working_dir, is_virtualenv, package_path, &manifest, secrets, params, other_env_vars).await + Self::execute_bash_program(&ctx, &environment, working_dir, package_path, &manifest, secrets, params, other_env_vars).await } else { let manifest = &package.manifest; let secrets = opts.secrets; - let params= opts.parameters; - let mut other_env_vars = opts.env_vars; - + let params = opts.parameters; + let other_env_vars = opts.env_vars; if !package.manifest.import_paths.is_empty() { debug!(ctx: &ctx, "adding import paths to PYTHONPATH: {:?}", package.manifest.import_paths); @@ -252,11 +191,11 @@ impl App for LocalApp { other_env_vars.insert("PYTHONPATH".to_string(), import_paths); } } + let env_vars = make_env_vars(&ctx, env, &cwd, &secrets, ¶ms, &other_env_vars); - // We need to resolve the program - let program_path = working_dir.join(manifest.invoke.clone()); - - Self::execute_python_program(&ctx, &environment, working_dir, is_virtualenv, python_path, program_path, &manifest, secrets, params, other_env_vars).await + // Now we also need to find the program to execute. + let program_path = package_path.join(&manifest.invoke); + uv.execute(package_path, program_path, env_vars, opts.output_sender).await; }; if let Ok(mut child) = res { @@ -267,7 +206,6 @@ impl App for LocalApp { let stderr = child.stderr.take().expect("no stderr"); tokio::spawn(drain_output(FD::Stderr, Channel::Setup, sender.clone(), BufReader::new(stderr))); - } let child = Arc::new(Mutex::new(child)); @@ -333,6 +271,7 @@ impl App for LocalApp { } impl LocalApp { +<<<<<<< HEAD async fn execute_python_program( ctx: &tower_telemetry::Context, env: &str, @@ -372,11 +311,12 @@ impl LocalApp { Ok(child) } +======= +>>>>>>> b76cd83 (feat: Integrate `uv` into `tower-runtime`) async fn execute_bash_program( ctx: &tower_telemetry::Context, env: &str, cwd: PathBuf, - is_virtualenv: bool, package_path: PathBuf, manifest: &Manifest, secrets: HashMap, @@ -394,7 +334,7 @@ impl LocalApp { .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) - .envs(make_env_vars(&ctx, env, &cwd, is_virtualenv, &secrets, ¶ms, &other_env_vars)) + .envs(make_env_vars(&ctx, env, &cwd, &secrets, ¶ms, &other_env_vars)) .kill_on_drop(true) .spawn()?; @@ -411,7 +351,7 @@ fn make_env_var_key(src: &str) -> String { } } -fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, is_virtualenv: bool, secs: &HashMap, params: &HashMap, other_env_vars: &HashMap) -> HashMap { +fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, secs: &HashMap, params: &HashMap, other_env_vars: &HashMap) -> HashMap { let mut res = HashMap::new(); debug!(ctx: &ctx, "converting {} env variables", (params.len() + secs.len())); @@ -431,28 +371,6 @@ fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, is_vi res.insert(key.to_string(), value.to_string()); } - // If we're in a virtual environment, we need to add the bin directory to the PATH so that we - // can find any executables that were installed there. - if is_virtualenv { - let venv_dir = cwd.join(".venv"); - let venv_path = venv_dir - .to_string_lossy() - .to_string(); - - let bin_path = venv_dir.join("bin") - .to_string_lossy() - .to_string(); - - if let Ok(path) = std::env::var("PATH") { - res.insert("PATH".to_string(), format!("{}:{}", bin_path, path)); - } else { - res.insert("PATH".to_string(), bin_path); - } - - // We also insert a VIRTUAL_ENV path such that we can - res.insert("VIRTUAL_ENV".to_string(), venv_path); - } - // We also need a PYTHONPATH that is set to the current working directory to help with the // dependency resolution problem at runtime. let pythonpath = cwd.to_string_lossy().to_string(); diff --git a/crates/tower-uv/Cargo.toml b/crates/tower-uv/Cargo.toml new file mode 100644 index 00000000..ffd63f59 --- /dev/null +++ b/crates/tower-uv/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "tower-uv" +version = { workspace = true } +authors = { workspace = true } +edition = { workspace = true } +rust-version = { workspace = true } +license = { workspace = true } + +[dependencies] +async-compression = { workspace = true } +async_zip = { workspace = true } +futures-lite = { workspace = true } +reqwest = { workspace = true } +tokio = { workspace = true } +tokio-tar = { workspace = true } +tower-telemetry = { workspace = true } diff --git a/crates/tower-uv/src/install.rs b/crates/tower-uv/src/install.rs new file mode 100644 index 00000000..2d1cefd9 --- /dev/null +++ b/crates/tower-uv/src/install.rs @@ -0,0 +1,305 @@ +use std::env; +use std::path::PathBuf; + +use tokio_tar::Archive; +use tokio::process::Command; +use async_compression::tokio::bufread::GzipDecoder; +use async_zip::tokio::read::seek::ZipFileReader; +use futures_lite::io::AsyncReadExt; + +use tower_telemetry::debug; + +#[derive(Debug)] +pub enum Error { + IoError(std::io::Error), + Other(String), +} + +impl From for Error { + fn from(err: std::io::Error) -> Self { + Error::IoError(err) + } +} + +impl From for Error { + fn from(err: String) -> Self { + Error::Other(err) + } +} + +pub fn get_default_uv_bin_dir() -> Result { + Ok(PathBuf::from(".tower/bin")) +} + +#[derive(Debug)] +pub struct ArchiveSelector; + +impl ArchiveSelector { + /// Get the appropriate archive name for the current platform + pub async fn get_archive_name() -> Result { + let arch = env::consts::ARCH; + let os = env::consts::OS; + + match (arch, os) { + // macOS + ("aarch64", "macos") => Ok("uv-aarch64-apple-darwin.tar.gz".to_string()), + ("x86_64", "macos") => Ok("uv-x86_64-apple-darwin.tar.gz".to_string()), + + // Windows + ("aarch64", "windows") => Ok("uv-aarch64-pc-windows-msvc.zip".to_string()), + ("x86_64", "windows") => Ok("uv-x86_64-pc-windows-msvc.zip".to_string()), + ("x86", "windows") => Ok("uv-i686-pc-windows-msvc.zip".to_string()), + + // Linux + ("aarch64", "linux") => { + if Self::is_musl_target() { + Ok("uv-aarch64-unknown-linux-musl.tar.gz".to_string()) + } else if Self::check_glibc(2, 28).await { + Ok("uv-aarch64-unknown-linux-gnu.tar.gz".to_string()) + } else { + Ok("uv-aarch64-unknown-linux-musl.tar.gz".to_string()) + } + } + ("x86_64", "linux") => { + if Self::is_musl_target() { + Ok("uv-x86_64-unknown-linux-musl.tar.gz".to_string()) + } else if Self::check_glibc(2, 17).await { + Ok("uv-x86_64-unknown-linux-gnu.tar.gz".to_string()) + } else { + Ok("uv-x86_64-unknown-linux-musl.tar.gz".to_string()) + } + } + ("x86", "linux") => { + if Self::is_musl_target() { + Ok("uv-i686-unknown-linux-musl.tar.gz".to_string()) + } else if Self::check_glibc(2, 17).await { + Ok("uv-i686-unknown-linux-gnu.tar.gz".to_string()) + } else { + Ok("uv-i686-unknown-linux-musl.tar.gz".to_string()) + } + } + ("arm", "linux") => { + // ARM v6 - only musl available + Ok("uv-arm-unknown-linux-musleabihf.tar.gz".to_string()) + } + ("armv7", "linux") => { + if Self::is_musl_target() { + Ok("uv-armv7-unknown-linux-musleabihf.tar.gz".to_string()) + } else if Self::check_glibc(2, 17).await { + Ok("uv-armv7-unknown-linux-gnueabihf.tar.gz".to_string()) + } else { + Ok("uv-armv7-unknown-linux-musleabihf.tar.gz".to_string()) + } + } + ("powerpc64", "linux") => { + if Self::check_glibc(2, 17).await { + Ok("uv-powerpc64-unknown-linux-gnu.tar.gz".to_string()) + } else { + Err("PowerPC64 requires glibc 2.17 or newer".to_string()) + } + } + ("powerpc64le", "linux") => { + if Self::check_glibc(2, 17).await { + Ok("uv-powerpc64le-unknown-linux-gnu.tar.gz".to_string()) + } else { + Err("PowerPC64LE requires glibc 2.17 or newer".to_string()) + } + } + ("riscv64", "linux") => { + if Self::check_glibc(2, 31).await { + Ok("uv-riscv64gc-unknown-linux-gnu.tar.gz".to_string()) + } else { + Err("RISC-V 64 requires glibc 2.31 or newer".to_string()) + } + } + ("s390x", "linux") => { + if Self::check_glibc(2, 17).await { + Ok("uv-s390x-unknown-linux-gnu.tar.gz".to_string()) + } else { + Err("s390x requires glibc 2.17 or newer".to_string()) + } + } + + _ => Err(format!("Unsupported platform: {} {}", arch, os)), + } + } + + /// Check if the current target uses musl libc + fn is_musl_target() -> bool { + // Check if we're compiled with musl + cfg!(target_env = "musl") + } + + /// Check if glibc version meets minimum requirements + async fn check_glibc(major: u32, minor: u32) -> bool { + // Only check glibc on Linux with gnu env + if !cfg!(target_os = "linux") || cfg!(target_env = "musl") { + return false; + } + + // Try to get glibc version using ldd + if let Ok(output) = Command::new("ldd") + .arg("--version") + .output() + .await + { + if let Ok(version_str) = String::from_utf8(output.stdout) { + return Self::parse_glibc_version(&version_str, major, minor); + } + } + + // Fallback: try to read from /lib/libc.so.6 + if let Ok(output) = Command::new("/lib/libc.so.6") + .output() + .await + { + if let Ok(version_str) = String::from_utf8(output.stdout) { + return Self::parse_glibc_version(&version_str, major, minor); + } + } + + // If we can't determine the version, assume it's old + false + } + + /// Parse glibc version string and compare with required version + fn parse_glibc_version(version_str: &str, req_major: u32, req_minor: u32) -> bool { + // Look for version pattern like "2.17" or "2.31" + for line in version_str.lines() { + if let Some(version_part) = line.split_whitespace() + .find(|part| part.contains('.') && part.chars().next().unwrap_or('0').is_ascii_digit()) + { + let version_clean = version_part.trim_matches(|c: char| !c.is_ascii_digit() && c != '.'); + let parts: Vec<&str> = version_clean.split('.').collect(); + + if parts.len() >= 2 { + if let (Ok(major), Ok(minor)) = (parts[0].parse::(), parts[1].parse::()) { + return major > req_major || (major == req_major && minor >= req_minor); + } + } + } + } + false + } +} + +fn extract_package_name(archive: String) -> String { + // Remove .tar.gz or .zip extension + archive + .strip_suffix(".tar.gz") + .or(archive.strip_suffix(".zip")) + .unwrap_or(&archive) + .to_string() +} + +async fn download_uv_archive(path: &PathBuf, archive: String) -> Result { + debug!("Downloading UV archive: {}", archive); + let url = format!("https://github.com/astral-sh/uv/releases/download/0.7.13/{}", archive); + + // Create the directory if it doesn't exist + std::fs::create_dir_all(&path).map_err(Error::IoError)?; + + // Download the file + let response = reqwest::get(url) + .await + .map_err(|e| Error::Other(e.to_string()))?; + + let bytes = response.bytes() + .await + .map_err(|e| Error::Other(e.to_string()))?; + + // Determine archive type from extension + if archive.ends_with(".tar.gz") { + let cursor = std::io::Cursor::new(bytes); + let tar = GzipDecoder::new(cursor); + + // Extract the tar.gz archive + Archive::new(tar) + .unpack(path) + .await?; + + let package_name = extract_package_name(archive.clone()); + Ok(path.join(package_name).join("uv")) + } else if archive.ends_with(".zip") { + // Write zip data to a temporary file since async-zip works with files + let temp_path = path.join("temp.zip"); + tokio::fs::write(&temp_path, bytes).await?; + + // Open the zip file using seek reader with compression support + let file = tokio::fs::File::open(&temp_path).await?; + let mut zip = ZipFileReader::with_tokio(file) + .await + .map_err(|e| Error::Other(format!("Failed to open zip file: {}", e)))?; + + let package_name = extract_package_name(archive.clone()); + let uv_path = "uv".to_string(); + let uv_exe_path = "uv.exe".to_string(); + + // Find the UV executable entry + let entries = zip.file().entries(); + let entry_index = entries + .iter() + .enumerate() + .find(|(_, entry)| { + let name = entry.filename().as_str().unwrap_or(""); + name == uv_path || name == uv_exe_path + }) + .map(|(index, _)| index) + .ok_or_else(|| Error::Other("UV executable not found in archive".to_string()))?; + + // Create the package directory + let target_dir = path.join(&package_name); + std::fs::create_dir_all(&target_dir)?; + + // Extract the file with proper error handling for compression + let filename = entries[entry_index].filename().as_str().unwrap_or("uv").to_string(); + let is_exe = filename.ends_with(".exe"); + let target_path = target_dir.join(if is_exe { "uv.exe" } else { "uv" }); + + let mut reader = zip.reader_with_entry(entry_index) + .await + .map_err(|e| Error::Other(format!("Failed to create entry reader for {}: {}", filename, e)))?; + let mut file = tokio::fs::File::create(&target_path).await?; + + // Manually copy data since ZipEntryReader doesn't implement AsyncRead + let mut buffer = [0u8; 8192]; + let mut total_bytes = 0; + loop { + let bytes_read = reader.read(&mut buffer) + .await + .map_err(|e| Error::Other(format!("Failed to read from zip entry: {}", e)))?; + if bytes_read == 0 { + break; + } + tokio::io::AsyncWriteExt::write_all(&mut file, &buffer[..bytes_read]) + .await + .map_err(|e| Error::Other(format!("Failed to write to output file: {}", e)))?; + total_bytes += bytes_read; + } + + debug!("Successfully extracted {} bytes to {:?}", total_bytes, target_path); + + // Make the file executable on Unix systems + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mut perms = std::fs::metadata(&target_path)?.permissions(); + perms.set_mode(0o755); + std::fs::set_permissions(&target_path, perms)?; + } + + // Clean up temporary zip file + tokio::fs::remove_file(temp_path).await?; + + Ok(target_path) + } else { + return Err(Error::Other(format!("Unsupported archive format: {}", archive))); + } +} + +pub async fn download_uv_for_arch(path: &PathBuf) -> Result { + let archive = ArchiveSelector::get_archive_name().await?; + let path = download_uv_archive(path, archive).await?; + debug!("Downloaded UV to: {:?}", path); + Ok(path) +} diff --git a/crates/tower-uv/src/lib.rs b/crates/tower-uv/src/lib.rs new file mode 100644 index 00000000..3628f73e --- /dev/null +++ b/crates/tower-uv/src/lib.rs @@ -0,0 +1,115 @@ +use std::path::PathBuf; +use std::collections::HashMap; +use tokio::process::{Command, Child}; + +mod install; + +#[derive(Debug)] +pub enum Error { + IoError(std::io::Error), + NotFound(String), + PermissionDenied(String), + Other(String), +} + +impl From for Error { + fn from(err: std::io::Error) -> Self { + // Convert std::fs::Error to your custom Error type + Error::IoError(err) + } +} + +impl From for Error { + fn from(err: install::Error) -> Self { + match err { + install::Error::IoError(e) => Error::IoError(e), + install::Error::Other(msg) => Error::Other(msg), + } + } +} + +async fn find_uv_binary() -> Option { + if let Ok(default_path) = install::get_default_uv_bin_dir() { + // Check if the default path exists + if default_path.exists() { + let uv_path = default_path.join("uv"); + if uv_path.exists() { + return Some(uv_path); + } + } + } + + // First, check if uv is already in the PATH + let output = Command::new("which") + .arg("uv") + .output() + .await; + + if let Ok(output) = output { + let path_str = String::from_utf8_lossy(&output.stdout); + let path = PathBuf::from(path_str.trim()); + + // If this is a path that actually exists, then we assume that it's `uv` and we can + // continue. + if path.exists() { + Some(path) + } else { + None + } + } else{ + None + } +} + +async fn find_or_setup_uv() -> Result { + // If we get here, uv wasn't found in PATH, so let's download it + if let Some(path) = find_uv_binary().await { + Ok(path) + } else { + let path = install::get_default_uv_bin_dir()?; + + // Create the directory if it doesn't exist + std::fs::create_dir_all(&path).map_err(Error::IoError)?; + + let parent = path.parent() + .ok_or_else(|| Error::NotFound("Parent directory not found".to_string()))? + .to_path_buf(); + + // We download this code to the UV directory + let exe = install::download_uv_for_arch(&parent).await?; + + // Target is the UV binary we want. + let target = path.join("uv"); + + // Copy the `uv` binary into the default directory + std::fs::copy(&exe, &target) + .map_err(|e| Error::IoError(e))?; + + Ok(target) + } +} + +pub struct Uv { + pub uv_path: PathBuf, +} + +impl Uv { + pub async fn new() -> Result { + let uv_path = find_or_setup_uv().await?; + Ok(Uv { uv_path }) + } + + pub async fn execute(&self, cwd: &PathBuf, program: &PathBuf, env_vars: HashMap) -> Result { + let child = Command::new(&self.uv_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .arg("run") + .arg(program) + .cwd(cwd) + .env_vars(env_vars) + .spawn(); + + Ok(child) + } +} From a691eeef0643a9df301bd93815c1f1b92d599984 Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Tue, 15 Jul 2025 17:50:19 +0200 Subject: [PATCH 02/15] chore: Plumb in `tower-uv` to `tower-runtime` --- Cargo.lock | 78 +++++++++++++++++- Cargo.toml | 2 + crates/tower-runtime/src/errors.rs | 11 +++ crates/tower-runtime/src/local.rs | 126 +++++++---------------------- crates/tower-uv/src/lib.rs | 7 +- 5 files changed, 121 insertions(+), 103 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 2e545ea4..8c762564 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -140,11 +140,27 @@ checksum = "59a194f9d963d8099596278594b3107448656ba73831c9d8c783e613ce86da64" dependencies = [ "flate2", "futures-core", + "futures-io", "memchr", "pin-project-lite", "tokio", ] +[[package]] +name = "async_zip" +version = "0.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527207465fb6dcafbf661b0d4a51d0d2306c9d0c2975423079a6caa807930daf" +dependencies = [ + "async-compression", + "crc32fast", + "futures-lite", + "pin-project", + "thiserror 1.0.69", + "tokio", + "tokio-util", +] + [[package]] name = "autocfg" version = "1.4.0" @@ -675,6 +691,12 @@ dependencies = [ "str-buf", ] +[[package]] +name = "fastrand" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be" + [[package]] name = "fd-lock" version = "3.0.13" @@ -771,6 +793,19 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" +[[package]] +name = "futures-lite" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5edaec856126859abb19ed65f39e90fea3a9574b9707f13539acf4abf7eb532" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + [[package]] name = "futures-macro" version = "0.3.31" @@ -1563,6 +1598,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39" +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + [[package]] name = "parking_lot" version = "0.12.3" @@ -1611,6 +1652,26 @@ version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" +[[package]] +name = "pin-project" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.100", +] + [[package]] name = "pin-project-lite" version = "0.2.16" @@ -1747,7 +1808,7 @@ dependencies = [ "once_cell", "socket2", "tracing", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -2648,6 +2709,7 @@ checksum = "6b9590b93e6fcc1739458317cccd391ad3955e2bde8913edf6f95f9e65a8f034" dependencies = [ "bytes", "futures-core", + "futures-io", "futures-sink", "pin-project-lite", "tokio", @@ -2789,6 +2851,7 @@ dependencies = [ "tokio", "tower-package", "tower-telemetry", + "tower-uv", ] [[package]] @@ -2806,6 +2869,19 @@ dependencies = [ "tracing-subscriber", ] +[[package]] +name = "tower-uv" +version = "0.3.20" +dependencies = [ + "async-compression", + "async_zip", + "futures-lite", + "reqwest", + "tokio", + "tokio-tar", + "tower-telemetry", +] + [[package]] name = "tower-version" version = "0.3.20" diff --git a/Cargo.toml b/Cargo.toml index 2f25c280..116d1a0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ repository = "https://github.com/tower/tower-cli" aes-gcm = "0.10" anyhow = "1.0.95" async-compression = { version = "0.4", features = ["tokio", "gzip"] } +async_zip = { version = "0.0.16", features = ["tokio", "tokio-fs", "deflate"] } base64 = "0.22" bytes = "1" chrono = { version = "0.4", features = ["serde"] } @@ -26,6 +27,7 @@ crypto = { path = "crates/crypto" } dirs = "5" futures = "0.3" futures-util = "0.3" +futures-lite = "2.6" glob = "0.3" http = "1.1" indicatif = "0.17" diff --git a/crates/tower-runtime/src/errors.rs b/crates/tower-runtime/src/errors.rs index 78ac4785..c6819440 100644 --- a/crates/tower-runtime/src/errors.rs +++ b/crates/tower-runtime/src/errors.rs @@ -74,3 +74,14 @@ impl From for Error { Error::UnsupportedPlatform } } + +impl From for Error { + fn from(err: tower_uv::Error) -> Self { + match err { + tower_uv::Error::IoError(_) => Error::SpawnFailed, + tower_uv::Error::NotFound(_) => Error::SpawnFailed, + tower_uv::Error::PermissionDenied(_) => Error::SpawnFailed, + tower_uv::Error::Other(_) => Error::SpawnFailed, + } + } +} diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index ac108598..3f173a7d 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -1,5 +1,10 @@ +<<<<<<< HEAD use std::path::{Path, PathBuf}; use std::env; +======= +use std::path::PathBuf; +use std::env::{self, current_dir}; +>>>>>>> dc0898c (chore: Plumb in `tower-uv` to `tower-runtime`) use std::process::Stdio; use std::sync::Arc; use std::collections::HashMap; @@ -90,32 +95,6 @@ async fn find_executable_in_path(executable_name: &str) -> Option { None } -async fn find_pip(dir: PathBuf) -> Result { - if let Some(path) = find_executable_in_path_buf("pip", dir).await { - Ok(path) - } else { - Err(Error::MissingPip) - } -} - -async fn find_python(dir: Option) -> Result { - if let Some(dir) = dir { - // find a local python - if let Some(path) = find_executable_in_path_buf("python", dir).await { - Ok(path) - } else { - Err(Error::MissingPython) - } - } else { - // find the system installed python - if let Some(path) = find_executable_in_path("python").await { - Ok(path) - } else { - Err(Error::MissingPython) - } - } -} - async fn find_bash() -> Result { if let Some(path) = find_executable_in_path("bash").await { Ok(path) @@ -128,7 +107,7 @@ async fn find_bash() -> Result { impl App for LocalApp { async fn start(opts: StartOptions) -> Result { // We need a uv instance to run the actual app. - let uv = tower_uv::Uv::new(); + let uv = tower_uv::Uv::new().await?; let ctx = opts.ctx.clone(); let package = opts.package; @@ -141,10 +120,6 @@ impl App for LocalApp { .unwrap() .to_path_buf(); - // We'll need the Python path for later on. - let mut python_path = find_python(None).await?; - debug!(ctx: &ctx, "using system python at {:?}", python_path); - // set for later on. let working_dir = if package.manifest.version == Some(2) { package_path.join(&package.manifest.app_dir_name) @@ -154,13 +129,13 @@ impl App for LocalApp { debug!(ctx: &ctx, " - working directory: {:?}", &working_dir); - let res = if package.manifest.invoke.ends_with(".sh") { + let mut child = if package.manifest.invoke.ends_with(".sh") { let manifest = &package.manifest; let secrets = opts.secrets; let params= opts.parameters; let other_env_vars = opts.env_vars; - Self::execute_bash_program(&ctx, &environment, working_dir, package_path, &manifest, secrets, params, other_env_vars).await + Self::execute_bash_program(&ctx, &environment, working_dir, package_path, &manifest, secrets, params, other_env_vars).await? } else { let manifest = &package.manifest; let secrets = opts.secrets; @@ -191,39 +166,34 @@ impl App for LocalApp { other_env_vars.insert("PYTHONPATH".to_string(), import_paths); } } - let env_vars = make_env_vars(&ctx, env, &cwd, &secrets, ¶ms, &other_env_vars); + let env_vars = make_env_vars(&ctx, &environment, &package_path, &secrets, ¶ms, &other_env_vars); // Now we also need to find the program to execute. let program_path = package_path.join(&manifest.invoke); - uv.execute(package_path, program_path, env_vars, opts.output_sender).await; + uv.execute(&package_path, &program_path, env_vars).await? }; - if let Ok(mut child) = res { - if let Some(ref sender) = opts.output_sender { - // Let's also send our logs to this output channel. - let stdout = child.stdout.take().expect("no stdout"); - tokio::spawn(drain_output(FD::Stdout, Channel::Setup, sender.clone(), BufReader::new(stdout))); + if let Some(ref sender) = opts.output_sender { + // Let's also send our logs to this output channel. + let stdout = child.stdout.take().expect("no stdout"); + tokio::spawn(drain_output(FD::Stdout, Channel::Setup, sender.clone(), BufReader::new(stdout))); - let stderr = child.stderr.take().expect("no stderr"); - tokio::spawn(drain_output(FD::Stderr, Channel::Setup, sender.clone(), BufReader::new(stderr))); - } + let stderr = child.stderr.take().expect("no stderr"); + tokio::spawn(drain_output(FD::Stderr, Channel::Setup, sender.clone(), BufReader::new(stderr))); + } - let child = Arc::new(Mutex::new(child)); - let (sx, rx) = oneshot::channel::(); + let child = Arc::new(Mutex::new(child)); + let (sx, rx) = oneshot::channel::(); - tokio::spawn(wait_for_process(ctx.clone(), sx, Arc::clone(&child))); + tokio::spawn(wait_for_process(ctx.clone(), sx, Arc::clone(&child))); - Ok(Self { - ctx, - package: Some(package), - child: Some(child), - waiter: Mutex::new(rx), - status: Mutex::new(None), - }) - } else { - debug!(ctx: &ctx, "failed to spawn process: {}", res.err().unwrap()); - Err(Error::SpawnFailed) - } + Ok(Self { + ctx, + package: Some(package), + child: Some(child), + waiter: Mutex::new(rx), + status: Mutex::new(None), + }) } async fn status(&self) -> Result { @@ -271,48 +241,6 @@ impl App for LocalApp { } impl LocalApp { -<<<<<<< HEAD - async fn execute_python_program( - ctx: &tower_telemetry::Context, - env: &str, - cwd: PathBuf, - is_virtualenv: bool, - python_path: PathBuf, - program_path: PathBuf, - manifest: &Manifest, - secrets: HashMap, - params: HashMap, - other_env_vars: HashMap, - ) -> Result { - let env_vars = make_env_vars( - &ctx, - env, - &cwd, - is_virtualenv, - &secrets, - ¶ms, - &other_env_vars, - ); - - debug!(ctx: &ctx, " - python script {}", manifest.invoke); - debug!(ctx: &ctx, " - python path {}", env_vars.get("PYTHONPATH").unwrap()); - - let child = Command::new(python_path) - .current_dir(&cwd) - .arg("-u") - .arg(program_path) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .envs(env_vars) - .kill_on_drop(true) - .spawn()?; - - Ok(child) - } - -======= ->>>>>>> b76cd83 (feat: Integrate `uv` into `tower-runtime`) async fn execute_bash_program( ctx: &tower_telemetry::Context, env: &str, diff --git a/crates/tower-uv/src/lib.rs b/crates/tower-uv/src/lib.rs index 3628f73e..49b855aa 100644 --- a/crates/tower-uv/src/lib.rs +++ b/crates/tower-uv/src/lib.rs @@ -1,5 +1,6 @@ use std::path::PathBuf; use std::collections::HashMap; +use std::process::Stdio; use tokio::process::{Command, Child}; mod install; @@ -104,11 +105,11 @@ impl Uv { .stdin(Stdio::null()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) + .current_dir(cwd) .arg("run") .arg(program) - .cwd(cwd) - .env_vars(env_vars) - .spawn(); + .envs(env_vars) + .spawn()?; Ok(child) } From 9cb59c7a26c8b72a399ec45d07fd37fe5384577d Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Tue, 15 Jul 2025 18:16:45 +0200 Subject: [PATCH 03/15] chore: Tuning to make `tower-runtime` work a bit easier --- crates/tower-runtime/src/local.rs | 2 ++ crates/tower-uv/src/lib.rs | 3 +++ 2 files changed, 5 insertions(+) diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index 3f173a7d..ee33aaae 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -322,6 +322,8 @@ fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, secs: res.insert("TOWER_ENVIRONMENT".to_string(), env.to_string()); } + res.insert("PYTHONUNBUFFERED".to_string(), "x".to_string()); + res } diff --git a/crates/tower-uv/src/lib.rs b/crates/tower-uv/src/lib.rs index 49b855aa..764fdc59 100644 --- a/crates/tower-uv/src/lib.rs +++ b/crates/tower-uv/src/lib.rs @@ -106,6 +106,9 @@ impl Uv { .stdout(Stdio::piped()) .stderr(Stdio::piped()) .current_dir(cwd) + .arg("--color") + .arg("never") + .arg("--no-progress") .arg("run") .arg(program) .envs(env_vars) From 01206a41044b8aafff969f8c03a9a7293b933edd Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 13:05:21 +0200 Subject: [PATCH 04/15] chore: Run the whole execution process in a thread --- Cargo.lock | 1 + crates/tower-runtime/Cargo.toml | 1 + crates/tower-runtime/src/local.rs | 291 +++++++++++++++++------------- crates/tower-uv/src/lib.rs | 35 +++- 4 files changed, 202 insertions(+), 126 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 8c762564..6e25f5b2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2849,6 +2849,7 @@ dependencies = [ "chrono", "snafu", "tokio", + "tokio-util", "tower-package", "tower-telemetry", "tower-uv", diff --git a/crates/tower-runtime/Cargo.toml b/crates/tower-runtime/Cargo.toml index 5ecaf2b5..99770ec3 100644 --- a/crates/tower-runtime/Cargo.toml +++ b/crates/tower-runtime/Cargo.toml @@ -9,6 +9,7 @@ license = { workspace = true } [dependencies] chrono = { workspace = true } tokio = { workspace = true } +tokio-util = { workspace = true } snafu = { workspace = true } tower-package = { workspace = true } tower-telemetry = { workspace = true } diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index ee33aaae..6bec0616 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -22,15 +22,23 @@ use crate::{ use tokio::{ fs, io::{AsyncRead, BufReader, AsyncBufReadExt}, - time::{timeout, Duration}, - sync::Mutex, process::{Child, Command}, - sync::oneshot, - sync::oneshot::error::TryRecvError, + sync::{ + Mutex, + oneshot::{ + self, + error::TryRecvError, + }, + }, + task::JoinHandle, + time::{timeout, Duration}, }; +use tokio_util::sync::CancellationToken; + use tower_package::{Manifest, Package}; use tower_telemetry::debug; +use tower_uv::Uv; use crate::{ FD, @@ -42,15 +50,17 @@ use crate::{ pub struct LocalApp { ctx: tower_telemetry::Context, - // LocalApp needs to take ownership of the package as a way of taking responsibility for it's - // lifetime and, most importantly, it's contents. The compiler complains that we never actually - // use this struct member, so we allow the dead_code attribute to silence the warning. - #[allow(dead_code)] - package: Option, - - child: Option>>, status: Mutex>, + + // waiter is what we use to communicate that the overall process is finished by the execution + // handle. waiter: Mutex>, + + // terminator is what we use to flag that we want to terminate the child process. + terminator: Mutex, + + // execute_handle keeps track of the current state of the execution lifecycle. + execute_handle: Option>>, } // Helper function to check if a file is executable @@ -103,78 +113,79 @@ async fn find_bash() -> Result { } } +async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_token: CancellationToken) -> Result<(), Error> { + let ctx = opts.ctx.clone(); + let package = opts.package; + let environment = opts.environment; + let package_path = package.unpacked_path + .clone() + .unwrap() + .to_path_buf(); + + // set for later on. + let working_dir = if package.manifest.version == Some(2) { + package_path.join(&package.manifest.app_dir_name) + } else { + opts.cwd.unwrap_or(package_path.to_path_buf()) + }; -impl App for LocalApp { - async fn start(opts: StartOptions) -> Result { - // We need a uv instance to run the actual app. - let uv = tower_uv::Uv::new().await?; + debug!(ctx: &ctx, " - working directory: {:?}", &working_dir); - let ctx = opts.ctx.clone(); - let package = opts.package; - let environment = opts.environment; - debug!(ctx: &ctx, "executing app with version {:?}", package.manifest.version); - - // This is the base path of where the package was unpacked. - let package_path = package.unpacked_path - .clone() - .unwrap() - .to_path_buf(); - - // set for later on. - let working_dir = if package.manifest.version == Some(2) { - package_path.join(&package.manifest.app_dir_name) - } else { - opts.cwd.unwrap_or(package_path.to_path_buf()) - }; + let manifest = &package.manifest; + let secrets = opts.secrets; + let params = opts.parameters; + let other_env_vars = opts.env_vars; - debug!(ctx: &ctx, " - working directory: {:?}", &working_dir); + if !package.manifest.import_paths.is_empty() { + debug!(ctx: &ctx, "adding import paths to PYTHONPATH: {:?}", package.manifest.import_paths); - let mut child = if package.manifest.invoke.ends_with(".sh") { - let manifest = &package.manifest; - let secrets = opts.secrets; - let params= opts.parameters; - let other_env_vars = opts.env_vars; + let import_paths = package.manifest.import_paths + .iter() + .map(|p| package_path.join(p)) + .collect::>(); - Self::execute_bash_program(&ctx, &environment, working_dir, package_path, &manifest, secrets, params, other_env_vars).await? - } else { - let manifest = &package.manifest; - let secrets = opts.secrets; - let params = opts.parameters; - let other_env_vars = opts.env_vars; - if !package.manifest.import_paths.is_empty() { - debug!(ctx: &ctx, "adding import paths to PYTHONPATH: {:?}", package.manifest.import_paths); - - let import_paths = package.manifest.import_paths - .iter() - .map(|p| package_path.join(p)) - .collect::>(); - - let import_paths = std::env::join_paths(import_paths)? - .to_string_lossy() - .to_string(); - - if other_env_vars.contains_key("PYTHONPATH") { - // If we already have a PYTHONPATH, we need to append to it. - let existing = other_env_vars.get("PYTHONPATH").unwrap(); - let pythonpath = std::env::join_paths(vec![existing, &import_paths])? - .to_string_lossy() - .to_string(); - - other_env_vars.insert("PYTHONPATH".to_string(), pythonpath); - } else { - // Otherwise, we just set it. - other_env_vars.insert("PYTHONPATH".to_string(), import_paths); - } - } - let env_vars = make_env_vars(&ctx, &environment, &package_path, &secrets, ¶ms, &other_env_vars); + let import_paths = std::env::join_paths(import_paths)? + .to_string_lossy() + .to_string(); - // Now we also need to find the program to execute. - let program_path = package_path.join(&manifest.invoke); - uv.execute(&package_path, &program_path, env_vars).await? - }; + if other_env_vars.contains_key("PYTHONPATH") { + // If we already have a PYTHONPATH, we need to append to it. + let existing = other_env_vars.get("PYTHONPATH").unwrap(); + let pythonpath = std::env::join_paths(vec![existing, &import_paths])? + .to_string_lossy() + .to_string(); + other_env_vars.insert("PYTHONPATH".to_string(), pythonpath); + } else { + // Otherwise, we just set it. + other_env_vars.insert("PYTHONPATH".to_string(), import_paths); + } + } + + if is_bash_package(&package) { + let child = execute_bash_program( + &ctx, + &environment, + working_dir, + package_path, + &manifest, + secrets, + params, + other_env_vars, + ).await?; + + let _ = sx.send(wait_for_process(ctx.clone(), &cancel_token, child).await); + } else { + let uv = Uv::new().await?; + let env_vars = make_env_vars(&ctx, &environment, &package_path, &secrets, ¶ms, &other_env_vars); + + // Now we also need to find the program to execute. + let program_path = package_path.join(&manifest.invoke); + + let mut child = uv.sync(&package_path, &env_vars).await?; + + // Drain the logs to the output channel. if let Some(ref sender) = opts.output_sender { - // Let's also send our logs to this output channel. let stdout = child.stdout.take().expect("no stdout"); tokio::spawn(drain_output(FD::Stdout, Channel::Setup, sender.clone(), BufReader::new(stdout))); @@ -182,16 +193,43 @@ impl App for LocalApp { tokio::spawn(drain_output(FD::Stderr, Channel::Setup, sender.clone(), BufReader::new(stderr))); } - let child = Arc::new(Mutex::new(child)); + // Let's wait for the setup to finish. We don't care about the results. + wait_for_process(ctx.clone(), &cancel_token, child).await; + + let mut child = uv.run(&package_path, &program_path, &env_vars).await?; + + // Drain the logs to the output channel. + if let Some(ref sender) = opts.output_sender { + let stdout = child.stdout.take().expect("no stdout"); + tokio::spawn(drain_output(FD::Stdout, Channel::Program, sender.clone(), BufReader::new(stdout))); + + let stderr = child.stderr.take().expect("no stderr"); + tokio::spawn(drain_output(FD::Stderr, Channel::Program, sender.clone(), BufReader::new(stderr))); + } + + let _ = sx.send(wait_for_process(ctx.clone(), &cancel_token, child).await); + } + + return Ok(()) +} + +impl App for LocalApp { + async fn start(opts: StartOptions) -> Result { + let ctx = opts.ctx.clone(); + let cancel_token = CancellationToken::new(); + let terminator = Mutex::new(cancel_token.clone()); + let (sx, rx) = oneshot::channel::(); + let waiter = Mutex::new(rx); - tokio::spawn(wait_for_process(ctx.clone(), sx, Arc::clone(&child))); + let handle = tokio::spawn(execute_local_app(opts, sx, cancel_token)); + let execute_handle = Some(handle); Ok(Self { ctx, - package: Some(package), - child: Some(child), - waiter: Mutex::new(rx), + execute_handle, + terminator, + waiter, status: Mutex::new(None), }) } @@ -224,50 +262,45 @@ impl App for LocalApp { } async fn terminate(&mut self) -> Result<(), Error> { - if let Some(proc) = &mut self.child { - let mut child = proc.lock().await; + let terminator = self.terminator.lock().await; + terminator.cancel(); - if let Err(err) = child.kill().await { - debug!(ctx: &self.ctx, "failed to terminate app: {}", err); - Err(Error::TerminateFailed) - } else { - Ok(()) - } - } else { - // Nothing to terminate. Should this be an error? - Ok(()) - } + // Now we should wait for the join handle to finish. + if let Some(execute_handle) = self.execute_handle.take() { + execute_handle.await; + self.execute_handle = None; + } + + Ok(()) } } -impl LocalApp { - async fn execute_bash_program( - ctx: &tower_telemetry::Context, - env: &str, - cwd: PathBuf, - package_path: PathBuf, - manifest: &Manifest, - secrets: HashMap, - params: HashMap, - other_env_vars: HashMap, - ) -> Result { - let bash_path = find_bash().await?; - debug!(ctx: &ctx, "using bash at {:?}", bash_path); - - debug!(ctx: &ctx, " - bash script {}", manifest.invoke); - - let child = Command::new(bash_path) - .current_dir(&cwd) - .arg(package_path.join(manifest.invoke.clone())) - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .envs(make_env_vars(&ctx, env, &cwd, &secrets, ¶ms, &other_env_vars)) - .kill_on_drop(true) - .spawn()?; - - Ok(child) - } +async fn execute_bash_program( + ctx: &tower_telemetry::Context, + env: &str, + cwd: PathBuf, + package_path: PathBuf, + manifest: &Manifest, + secrets: HashMap, + params: HashMap, + other_env_vars: HashMap, +) -> Result { + let bash_path = find_bash().await?; + debug!(ctx: &ctx, "using bash at {:?}", bash_path); + + debug!(ctx: &ctx, " - bash script {}", manifest.invoke); + + let child = Command::new(bash_path) + .current_dir(&cwd) + .arg(package_path.join(manifest.invoke.clone())) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .envs(make_env_vars(&ctx, env, &cwd, &secrets, ¶ms, &other_env_vars)) + .kill_on_drop(true) + .spawn()?; + + Ok(child) } fn make_env_var_key(src: &str) -> String { @@ -327,13 +360,17 @@ fn make_env_vars(ctx: &tower_telemetry::Context, env: &str, cwd: &PathBuf, secs: res } -async fn wait_for_process(ctx: tower_telemetry::Context, sx: oneshot::Sender, proc: Arc>) { +async fn wait_for_process(ctx: tower_telemetry::Context, cancel_token: &CancellationToken, mut child: Child) -> i32 { let code = loop { - let mut child = proc.lock().await; - let timeout = timeout(Duration::from_millis(250), child.wait()).await; + if cancel_token.is_cancelled() { + debug!(ctx: &ctx, "process cancelled, terminating child process"); + let _ = child.kill().await; + break -1; // return -1 to indicate that the process was cancelled. + } - if let Ok(res) = timeout { + let timeout = timeout(Duration::from_millis(25), child.wait()).await; + if let Ok(res) = timeout { if let Ok(status) = res { break status.code().expect("no status code"); } else { @@ -347,7 +384,7 @@ async fn wait_for_process(ctx: tower_telemetry::Context, sx: oneshot::Sender(fd: FD, channel: Channel, output: OutputSender, input: BufReader) { @@ -365,3 +402,7 @@ async fn drain_output(fd: FD, channel: Channel, output: Ou } } + +fn is_bash_package(package: &Package) -> bool { + return package.manifest.invoke.ends_with(".sh") +} diff --git a/crates/tower-uv/src/lib.rs b/crates/tower-uv/src/lib.rs index 764fdc59..68f27185 100644 --- a/crates/tower-uv/src/lib.rs +++ b/crates/tower-uv/src/lib.rs @@ -2,6 +2,7 @@ use std::path::PathBuf; use std::collections::HashMap; use std::process::Stdio; use tokio::process::{Command, Child}; +use tower_telemetry::debug; mod install; @@ -100,7 +101,39 @@ impl Uv { Ok(Uv { uv_path }) } - pub async fn execute(&self, cwd: &PathBuf, program: &PathBuf, env_vars: HashMap) -> Result { + pub async fn venv(&self, cwd: &PathBuf, env_vars: &HashMap) -> Result { + debug!("Executing UV ({:?}) venv in {:?}", &self.uv_path, cwd); + + let child = Command::new(&self.uv_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .current_dir(cwd) + .arg("venv") + .envs(env_vars) + .spawn()?; + + Ok(child) + } + + pub async fn sync(&self, cwd: &PathBuf, env_vars: &HashMap) -> Result { + debug!("Executing UV ({:?}) sync in {:?}", &self.uv_path, cwd); + + let child = Command::new(&self.uv_path) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .current_dir(cwd) + .arg("sync") + .envs(env_vars) + .spawn()?; + + Ok(child) + } + + pub async fn run(&self, cwd: &PathBuf, program: &PathBuf, env_vars: &HashMap) -> Result { + debug!("Executing UV ({:?}) run {:?} in {:?}", &self.uv_path, program, cwd); + let child = Command::new(&self.uv_path) .stdin(Stdio::null()) .stdout(Stdio::piped()) From 928d7b0f88ac5e101510388f41d3908fedf10303 Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 13:27:07 +0200 Subject: [PATCH 05/15] chore: Fix some issues from rebase --- crates/tower-runtime/src/local.rs | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index 6bec0616..1ba31048 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -1,10 +1,5 @@ -<<<<<<< HEAD -use std::path::{Path, PathBuf}; -use std::env; -======= use std::path::PathBuf; -use std::env::{self, current_dir}; ->>>>>>> dc0898c (chore: Plumb in `tower-uv` to `tower-runtime`) +use std::env; use std::process::Stdio; use std::sync::Arc; use std::collections::HashMap; @@ -134,7 +129,7 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ let manifest = &package.manifest; let secrets = opts.secrets; let params = opts.parameters; - let other_env_vars = opts.env_vars; + let mut other_env_vars = opts.env_vars; if !package.manifest.import_paths.is_empty() { debug!(ctx: &ctx, "adding import paths to PYTHONPATH: {:?}", package.manifest.import_paths); From 0a7cd0b1bfcf598376a46545fa30156290c6738f Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 13:34:46 +0200 Subject: [PATCH 06/15] chore: Remove some build warnings and check for cancellation --- crates/tower-runtime/src/errors.rs | 3 +++ crates/tower-runtime/src/local.rs | 36 +++++++++++++++++++++++++----- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/crates/tower-runtime/src/errors.rs b/crates/tower-runtime/src/errors.rs index c6819440..5162fc6d 100644 --- a/crates/tower-runtime/src/errors.rs +++ b/crates/tower-runtime/src/errors.rs @@ -61,6 +61,9 @@ pub enum Error { #[snafu(display("running Tower apps on this platform is not supported"))] UnsupportedPlatform, + + #[snafu(display("cancelled"))] + Cancelled, } impl From for Error { diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index 1ba31048..9ff1f3d0 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -1,7 +1,6 @@ use std::path::PathBuf; use std::env; use std::process::Stdio; -use std::sync::Arc; use std::collections::HashMap; #[cfg(unix)] @@ -43,8 +42,6 @@ use crate::{ }; pub struct LocalApp { - ctx: tower_telemetry::Context, - status: Mutex>, // waiter is what we use to communicate that the overall process is finished by the execution @@ -157,6 +154,18 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ } } + // We insert these checks for cancellation along the way to see if the process was + // terminated by someone. + // + // We do this before instantiating `Uv` because that can be somewhat time consuming. Likewise + // this stops us from instantiating a bash process. + if cancel_token.is_cancelled() { + // if there's a waiter, we want them to know that the process was cancelled so we have + // to return something on the relevant channel. + let _ = sx.send(-1); + return Err(Error::Cancelled); + } + if is_bash_package(&package) { let child = execute_bash_program( &ctx, @@ -177,6 +186,14 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ // Now we also need to find the program to execute. let program_path = package_path.join(&manifest.invoke); + // Check once more if the process was cancelled before we do a uv sync. The sync itself, + // once started, will take a while and we have logic for checking for cancellation. + if cancel_token.is_cancelled() { + // again tell any waiters that we cancelled. + let _ = sx.send(-1); + return Err(Error::Cancelled); + } + let mut child = uv.sync(&package_path, &env_vars).await?; // Drain the logs to the output channel. @@ -191,6 +208,14 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ // Let's wait for the setup to finish. We don't care about the results. wait_for_process(ctx.clone(), &cancel_token, child).await; + // Check once more to see if the process was cancelled, this will bail us out early. + if cancel_token.is_cancelled() { + // if there's a waiter, we want them to know that the process was cancelled so we have + // to return something on the relevant channel. + let _ = sx.send(-1); + return Err(Error::Cancelled); + } + let mut child = uv.run(&package_path, &program_path, &env_vars).await?; // Drain the logs to the output channel. @@ -205,12 +230,12 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ let _ = sx.send(wait_for_process(ctx.clone(), &cancel_token, child).await); } + // Everything was properly executed I suppose. return Ok(()) } impl App for LocalApp { async fn start(opts: StartOptions) -> Result { - let ctx = opts.ctx.clone(); let cancel_token = CancellationToken::new(); let terminator = Mutex::new(cancel_token.clone()); @@ -221,7 +246,6 @@ impl App for LocalApp { let execute_handle = Some(handle); Ok(Self { - ctx, execute_handle, terminator, waiter, @@ -262,7 +286,7 @@ impl App for LocalApp { // Now we should wait for the join handle to finish. if let Some(execute_handle) = self.execute_handle.take() { - execute_handle.await; + let _ = execute_handle.await; self.execute_handle = None; } From 13adcdfac92cb892e1e0a42b6774176218117e6d Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 13:36:51 +0200 Subject: [PATCH 07/15] chore: Clean up some formatting. --- crates/tower-uv/src/install.rs | 6 +++--- crates/tower-uv/src/lib.rs | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/crates/tower-uv/src/install.rs b/crates/tower-uv/src/install.rs index 2d1cefd9..68e51e51 100644 --- a/crates/tower-uv/src/install.rs +++ b/crates/tower-uv/src/install.rs @@ -218,8 +218,8 @@ async fn download_uv_archive(path: &PathBuf, archive: String) -> Result Result Option { } else { None } - } else{ + } else { None } } From fe33de44696d0e3a3295f412f44c3adaf4722585 Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 14:05:54 +0200 Subject: [PATCH 08/15] chore: Some final reintegration tests and/or cleanups. --- crates/tower-runtime/src/local.rs | 6 +++--- crates/tower-uv/src/lib.rs | 3 +++ 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index 9ff1f3d0..c41c7642 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -184,7 +184,7 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ let env_vars = make_env_vars(&ctx, &environment, &package_path, &secrets, ¶ms, &other_env_vars); // Now we also need to find the program to execute. - let program_path = package_path.join(&manifest.invoke); + let program_path = working_dir.join(&manifest.invoke); // Check once more if the process was cancelled before we do a uv sync. The sync itself, // once started, will take a while and we have logic for checking for cancellation. @@ -194,7 +194,7 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ return Err(Error::Cancelled); } - let mut child = uv.sync(&package_path, &env_vars).await?; + let mut child = uv.sync(&working_dir, &env_vars).await?; // Drain the logs to the output channel. if let Some(ref sender) = opts.output_sender { @@ -216,7 +216,7 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ return Err(Error::Cancelled); } - let mut child = uv.run(&package_path, &program_path, &env_vars).await?; + let mut child = uv.run(&working_dir, &program_path, &env_vars).await?; // Drain the logs to the output channel. if let Some(ref sender) = opts.output_sender { diff --git a/crates/tower-uv/src/lib.rs b/crates/tower-uv/src/lib.rs index af7d6d7e..79e0443c 100644 --- a/crates/tower-uv/src/lib.rs +++ b/crates/tower-uv/src/lib.rs @@ -124,6 +124,9 @@ impl Uv { .stdout(Stdio::piped()) .stderr(Stdio::piped()) .current_dir(cwd) + .arg("--color") + .arg("never") + .arg("--no-progress") .arg("sync") .envs(env_vars) .spawn()?; From b29d63a4a4191b2c2de91aef3d39173e7b3e8207 Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 14:07:41 +0200 Subject: [PATCH 09/15] chore: Only use our package working dir when required. --- crates/tower-runtime/src/local.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/tower-runtime/src/local.rs b/crates/tower-runtime/src/local.rs index c41c7642..76c16124 100644 --- a/crates/tower-runtime/src/local.rs +++ b/crates/tower-runtime/src/local.rs @@ -118,7 +118,7 @@ async fn execute_local_app(opts: StartOptions, sx: oneshot::Sender, cancel_ let working_dir = if package.manifest.version == Some(2) { package_path.join(&package.manifest.app_dir_name) } else { - opts.cwd.unwrap_or(package_path.to_path_buf()) + package_path.to_path_buf() }; debug!(ctx: &ctx, " - working directory: {:?}", &working_dir); From d61b423d004ed51f393339d2ab76f22a7676d8cd Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 14:11:00 +0200 Subject: [PATCH 10/15] chore: Move our UV version --- crates/tower-uv/src/install.rs | 5 ++++- crates/tower-uv/src/lib.rs | 3 +++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/tower-uv/src/install.rs b/crates/tower-uv/src/install.rs index 68e51e51..25677da3 100644 --- a/crates/tower-uv/src/install.rs +++ b/crates/tower-uv/src/install.rs @@ -9,6 +9,9 @@ use futures_lite::io::AsyncReadExt; use tower_telemetry::debug; +// Copy the UV_VERSION locally to make this a bit more ergonomic. +const UV_VERSION: &str = crate::UV_VERSION; + #[derive(Debug)] pub enum Error { IoError(std::io::Error), @@ -194,7 +197,7 @@ fn extract_package_name(archive: String) -> String { async fn download_uv_archive(path: &PathBuf, archive: String) -> Result { debug!("Downloading UV archive: {}", archive); - let url = format!("https://github.com/astral-sh/uv/releases/download/0.7.13/{}", archive); + let url = format!("https://github.com/astral-sh/uv/releases/download/{}/{}", UV_VERSION, archive); // Create the directory if it doesn't exist std::fs::create_dir_all(&path).map_err(Error::IoError)?; diff --git a/crates/tower-uv/src/lib.rs b/crates/tower-uv/src/lib.rs index 79e0443c..1998b21b 100644 --- a/crates/tower-uv/src/lib.rs +++ b/crates/tower-uv/src/lib.rs @@ -6,6 +6,9 @@ use tower_telemetry::debug; mod install; +// UV_VERSION is the version of UV to download and install when setting up a local UV deployment. +pub const UV_VERSION: &str = "0.7.13"; + #[derive(Debug)] pub enum Error { IoError(std::io::Error), From 3618a1d23f9221075c53b16be916beb1d2dc7d9e Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 15:11:47 +0200 Subject: [PATCH 11/15] chore: Add a CI step to check for OpenSSL --- .github/workflows/test-rust.yml | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/.github/workflows/test-rust.yml b/.github/workflows/test-rust.yml index 8268147f..afd4b1cc 100644 --- a/.github/workflows/test-rust.yml +++ b/.github/workflows/test-rust.yml @@ -51,6 +51,22 @@ jobs: env: RUST_LOG: debug + - name: Continue to evict openssl + run: > + cargo tree -i openssl-sys + if [[ $? -eq 0 ]]; + then + echo "openssl is present in the dependency tree. Please evict it." + exit 1 + fi + + cargo tree -i native-tls + if [[ $? -eq 0 ]]; + then + echo "native-tls is present in the dependency tree. Please evict it." + exit 1 + fi + # integration-test: # runs-on: ${{ matrix.os }} # strategy: From 246fb79f9d0bca195307d897f545af4df5ba5ab7 Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 15:15:14 +0200 Subject: [PATCH 12/15] chore: Slightly different syntax for cmdlet --- .github/workflows/test-rust.yml | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/.github/workflows/test-rust.yml b/.github/workflows/test-rust.yml index afd4b1cc..df1c188f 100644 --- a/.github/workflows/test-rust.yml +++ b/.github/workflows/test-rust.yml @@ -53,19 +53,19 @@ jobs: - name: Continue to evict openssl run: > - cargo tree -i openssl-sys + cargo tree -i openssl-sys; if [[ $? -eq 0 ]]; then - echo "openssl is present in the dependency tree. Please evict it." - exit 1 - fi + echo "openssl is present in the dependency tree. Please evict it."; + exit 1; + fi; - cargo tree -i native-tls + cargo tree -i native-tls; if [[ $? -eq 0 ]]; then - echo "native-tls is present in the dependency tree. Please evict it." - exit 1 - fi + echo "native-tls is present in the dependency tree. Please evict it."; + exit 1; + fi; # integration-test: # runs-on: ${{ matrix.os }} From c03ce43b3617f0998501f3343ff6bdbe1518e3ea Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 15:18:46 +0200 Subject: [PATCH 13/15] chore: Naught dependency detection, now with 100% more Claude --- .github/workflows/test-rust.yml | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/test-rust.yml b/.github/workflows/test-rust.yml index df1c188f..3ce537e2 100644 --- a/.github/workflows/test-rust.yml +++ b/.github/workflows/test-rust.yml @@ -53,19 +53,19 @@ jobs: - name: Continue to evict openssl run: > - cargo tree -i openssl-sys; - if [[ $? -eq 0 ]]; - then - echo "openssl is present in the dependency tree. Please evict it."; - exit 1; - fi; + echo "Checking for openssl-sys in dependency tree..." + if cargo tree -i openssl-sys >/dev/null 2>&1; then + echo "openssl-sys is present in the dependency tree. Please evict it." + exit 1 + fi - cargo tree -i native-tls; - if [[ $? -eq 0 ]]; - then - echo "native-tls is present in the dependency tree. Please evict it."; - exit 1; - fi; + echo "Checking for native-tls in dependency tree..." + if cargo tree -i native-tls >/dev/null 2>&1; then + echo "native-tls is present in the dependency tree. Please evict it." + exit 1 + fi + + echo "✅ No naughty dependencies found" # integration-test: # runs-on: ${{ matrix.os }} From d36c8bb2a470eed180c4ca6af30c54ca439584d7 Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 15:20:41 +0200 Subject: [PATCH 14/15] chore: Shell needs to be bash! Of course! --- .github/workflows/test-rust.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/test-rust.yml b/.github/workflows/test-rust.yml index 3ce537e2..4eb6dffd 100644 --- a/.github/workflows/test-rust.yml +++ b/.github/workflows/test-rust.yml @@ -52,6 +52,7 @@ jobs: RUST_LOG: debug - name: Continue to evict openssl + shell: bash run: > echo "Checking for openssl-sys in dependency tree..." if cargo tree -i openssl-sys >/dev/null 2>&1; then From fab206b5230c06652e1d1cf59a4de5fc4ec6b9b8 Mon Sep 17 00:00:00 2001 From: Brad Heller Date: Wed, 16 Jul 2025 15:25:40 +0200 Subject: [PATCH 15/15] chore: Extract script into file --- .github/check-for-naughty-dependencies.sh | 13 +++++++++++++ .github/workflows/test-rust.yml | 19 ++----------------- 2 files changed, 15 insertions(+), 17 deletions(-) create mode 100644 .github/check-for-naughty-dependencies.sh diff --git a/.github/check-for-naughty-dependencies.sh b/.github/check-for-naughty-dependencies.sh new file mode 100644 index 00000000..2e4d9632 --- /dev/null +++ b/.github/check-for-naughty-dependencies.sh @@ -0,0 +1,13 @@ +echo "Checking for openssl-sys in dependency tree..." +if cargo tree -i openssl-sys >/dev/null 2>&1; then + echo "openssl-sys is present in the dependency tree. Please evict it." + exit 1 +fi + +echo "Checking for native-tls in dependency tree..." +if cargo tree -i native-tls >/dev/null 2>&1; then + echo "native-tls is present in the dependency tree. Please evict it." + exit 1 +fi + +echo "✅ No naughty dependencies found" diff --git a/.github/workflows/test-rust.yml b/.github/workflows/test-rust.yml index 4eb6dffd..044d7125 100644 --- a/.github/workflows/test-rust.yml +++ b/.github/workflows/test-rust.yml @@ -51,23 +51,8 @@ jobs: env: RUST_LOG: debug - - name: Continue to evict openssl - shell: bash - run: > - echo "Checking for openssl-sys in dependency tree..." - if cargo tree -i openssl-sys >/dev/null 2>&1; then - echo "openssl-sys is present in the dependency tree. Please evict it." - exit 1 - fi - - echo "Checking for native-tls in dependency tree..." - if cargo tree -i native-tls >/dev/null 2>&1; then - echo "native-tls is present in the dependency tree. Please evict it." - exit 1 - fi - - echo "✅ No naughty dependencies found" - + - run: bash .github/check-for-naughty-dependencies.sh + # integration-test: # runs-on: ${{ matrix.os }} # strategy: