"""Fetch the latest uv release on the daemon host and stage uv over SSH.""" from __future__ import annotations import re import os from pathlib import Path, PurePosixPath import shlex import tempfile _ASSETS = { ("Darwin", "arm64"): "aarch64-apple-darwin", ("Darwin", "x86_64"): "x86_64-apple-darwin", ("Linux", "aarch64"): "aarch64-unknown-linux-musl", ("Linux", "x86_64"): "x86_64-unknown-linux-musl", } def latest_release() -> str: from urllib.request import Request, urlopen releases = "https://github.com/astral-sh/uv/releases" with urlopen(Request(f"{releases}/latest", method="HEAD"), timeout=15) as response: tag = response.geturl().removeprefix(f"{releases}/tag/") if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+", tag): raise ValueError(f"unexpected uv release URL: {tag}") return tag def _archive(version: str, platform: str) -> bytes: from urllib.request import urlopen name = f"uv-{platform}.tar.gz" home = Path(os.environ.get("ALBEDO_HOME") or "~/.albedo").expanduser() path = home / "cache" / "uv" / version / name try: return path.read_bytes() except FileNotFoundError: pass url = f"https://github.com/astral-sh/uv/releases/download/{version}/{name}" with urlopen(url, timeout=60) as response: data = response.read() path.parent.mkdir(parents=True, exist_ok=True) with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as output: partial = Path(output.name) try: output.write(data) output.flush() partial.replace(path) finally: partial.unlink(missing_ok=True) return data def ensure_uv(target: str, system: str, arch: str, home: str) -> str: """Return the absolute path of the atomically staged remote uv.""" import albedo_ssh platform = _ASSETS.get((system, arch)) if platform is None: raise ValueError(f"no Albedo uv bootstrap for {system} {arch}") version = latest_release() directory = PurePosixPath(home, albedo_ssh.STAGED_DIR, "uv", version, platform) binary = str(directory / "uv") quoted = shlex.quote(binary) # Some SSH wrappers lose a command's exit status. Require the remote shell # to confirm that it actually found or installed an executable. confirm = f"test -x {quoted} && echo ready" probe = albedo_ssh.run( target, albedo_ssh.in_login_shell(confirm), albedo_ssh.PROBE_TIMEOUT ) if probe.returncode == 0 and probe.stdout.strip() == b"ready": return binary if probe.returncode not in (0, 1): raise OSError( probe.stderr.decode(errors="replace").strip() or "uv probe failed" ) script = ( f"set -eu; umask 077; mkdir -p {shlex.quote(str(directory))}; " f"p=$(mktemp {quoted}.XXXXXX); trap 'rm -f \"$p\"' EXIT; " f'tar -xzOf - uv-{platform}/uv > "$p"; chmod 700 "$p"; mv -f "$p" {quoted}; {confirm}' ) install = albedo_ssh.run( target, albedo_ssh.in_login_shell(script), albedo_ssh.STAGE_TIMEOUT, _archive(version, platform), ) if install.returncode or install.stdout.strip() != b"ready": raise OSError( install.stderr.decode(errors="replace").strip() or "uv staging failed" ) return binary