verctl-github 0.9.7

GitHub REST client for verctl releases, pull requests, tags, and branch rules
Documentation
use std::fs;
use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result, bail, ensure};
use octocrab::Octocrab;
use reqwest::redirect::Policy;
use tokio::time;
use verctl_core::repo::Repo;

use crate::release_state::{ReleaseList, ReleaseRecord, find_release};
use crate::{asset_upload, block, client};

/// The hex SHA-256 that GitHub stores for asset `name` in the `tag` Release.
/// It comes from the `digest` of the asset (`sha256:<hex>`, see
/// [release assets]).
/// Reading the digest from GitHub, instead of hashing a local file, keeps the
/// checksum matching the stored asset.
/// A rerun's build can differ in bytes from the one GitHub kept.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built or the Release
/// cannot be read.
/// It also returns one when the Release does not list `name` or the asset has
/// no SHA-256 digest.
///
/// [release assets]: https://docs.github.com/en/rest/releases/assets
pub fn asset_sha256(token: &str, repo: &Repo, tag: &str, name: &str) -> Result<String> {
    block(async {
        let crab = client(token)?;
        asset_sha256_with(&crab, repo, tag, name).await
    })
}

pub(crate) async fn asset_sha256_with(
    crab: &Octocrab,
    repo: &Repo,
    tag: &str,
    name: &str,
) -> Result<String> {
    let release = upload_target(crab, repo, Target::Tag(tag)).await?;
    let asset = release
        .assets
        .iter()
        .find(|asset| asset.name == name)
        .with_context(|| format!("release {tag} does not list asset {name}"))?;
    asset
        .digest
        .as_deref()
        .and_then(|digest| digest.strip_prefix("sha256:"))
        .map(str::to_owned)
        .with_context(|| format!("GitHub reports no SHA-256 digest for asset {name} of {tag}"))
}

/// The names of the assets of the Release of `tag`, draft or published,
/// whose upload completed.
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, or when no
/// Release exists for `tag`.
pub fn uploaded_assets(token: &str, repo: &Repo, tag: &str) -> Result<Vec<String>> {
    block(async {
        let crab = client(token)?;
        let release = upload_target(&crab, repo, Target::Tag(tag)).await?;
        Ok(release.uploaded().into_iter().map(str::to_owned).collect())
    })
}

/// A Release asset [`download_release_assets`] saved.
#[derive(Debug)]
#[non_exhaustive]
pub struct AssetFile {
    /// The asset's name, which is the file name it was saved under.
    pub name: String,
    /// Where it was saved.
    pub path: PathBuf,
    /// The SHA-256 GitHub reports for the stored file, in lowercase hex.
    pub sha256: String,
}

/// How long one asset download may take.
const DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(5);

/// Save each of `names` from the Release of `tag`, draft or published, into
/// `dir` under its own name.
///
/// GitHub answers the asset API with a redirect to its storage. The token goes
/// to GitHub only: the client follows no redirect itself, and fetches the
/// storage URL without it ([release assets]).
///
/// # Errors
///
/// Returns an error when the GitHub client cannot be built, the Release does
/// not exist or does not list one of `names`, or GitHub reports no SHA-256
/// digest for one. It also returns one when a download fails or a file cannot
/// be written.
///
/// [release assets]: https://docs.github.com/en/rest/releases/assets#get-a-release-asset
pub fn download_release_assets(
    token: &str,
    repo: &Repo,
    tag: &str,
    names: &[&str],
    dir: &Path,
) -> Result<Vec<AssetFile>> {
    block(async {
        let crab = client(token)?;
        download_release_assets_with(&crab, token, repo, tag, names, dir).await
    })
}

pub(crate) async fn download_release_assets_with(
    crab: &Octocrab,
    token: &str,
    repo: &Repo,
    tag: &str,
    names: &[&str],
    dir: &Path,
) -> Result<Vec<AssetFile>> {
    let release = upload_target(crab, repo, Target::Tag(tag)).await?;
    let http = reqwest::Client::builder()
        .redirect(Policy::none())
        .user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
        .timeout(DOWNLOAD_TIMEOUT)
        .build()
        .context("HTTP client")?;
    let mut saved = Vec::new();
    for name in names {
        let asset = release
            .assets
            .iter()
            .find(|asset| asset.name == *name)
            .with_context(|| format!("release {tag} does not list asset {name}"))?;
        ensure!(
            !asset.url.is_empty(),
            "GitHub reports no API URL for asset {name} of {tag}"
        );
        let sha256 = asset
            .digest
            .as_deref()
            .and_then(|digest| digest.strip_prefix("sha256:"))
            .map(str::to_owned)
            .with_context(|| {
                format!("GitHub reports no SHA-256 digest for asset {name} of {tag}")
            })?;
        let body = download_asset(&http, token, &asset.url)
            .await
            .with_context(|| format!("download {name} from release {tag}"))?;
        let path = dir.join(name);
        fs::write(&path, &body).with_context(|| path.display().to_string())?;
        saved.push(AssetFile {
            name: (*name).to_owned(),
            path,
            sha256,
        });
    }
    Ok(saved)
}

/// The bytes of the asset at `url`: its API URL with the token, then the
/// storage URL GitHub redirects to, without it. An error names `url` and
/// never the storage URL, whose query string signs the download.
async fn download_asset(http: &reqwest::Client, token: &str, url: &str) -> Result<bytes::Bytes> {
    use reqwest::header::{ACCEPT, LOCATION};
    let response = http
        .get(url)
        .bearer_auth(token)
        .header(ACCEPT, "application/octet-stream")
        .send()
        .await
        .with_context(|| format!("GET {url}"))?;
    let response = if response.status().is_redirection() {
        let location = response
            .headers()
            .get(LOCATION)
            .and_then(|value| value.to_str().ok())
            .with_context(|| format!("GET {url}: a redirect with no Location"))?
            .to_owned();
        http.get(location)
            .send()
            .await
            .map_err(reqwest::Error::without_url)
            .with_context(|| format!("GET the storage URL {url} redirects to"))?
    } else {
        response
    };
    let response = response
        .error_for_status()
        .map_err(reqwest::Error::without_url)
        .with_context(|| format!("GET {url}"))?;
    ensure!(
        response.status().is_success(),
        "GET {url}: unexpected status {}",
        response.status()
    );
    response
        .bytes()
        .await
        .map_err(reqwest::Error::without_url)
        .with_context(|| format!("read {url}"))
}

/// Attach `tarball` to the release for `tag`.
///
/// Returns the download URL, or `already <name>` when GitHub refuses the
/// upload because the release already has a complete asset of that name.
/// The run that got there first, or an earlier attempt of this one, uploaded
/// it.
///
/// # Errors
///
/// Returns an error when:
///
/// - `tarball` has no UTF-8 file name or cannot be read.
/// - The GitHub client cannot be built.
/// - The release for `tag` does not exist.
/// - The asset of that name exists but its upload does not complete within a
///   minute.
/// - The upload fails for a reason other than a duplicate asset.
pub fn upload_release_asset(token: &str, repo: &Repo, tag: &str, tarball: &Path) -> Result<String> {
    upload(token, repo, Target::Tag(tag), tarball)
}

/// [`upload_release_asset`] to the Release `id` of `tag`, which this run
/// opened or found, so the upload never looks the Release up by its tag
/// again: two drafts can share a tag name.
///
/// # Errors
///
/// Returns the errors of [`upload_release_asset`], with the Release read by
/// its id.
pub fn upload_to_release(
    token: &str,
    repo: &Repo,
    id: u64,
    tag: &str,
    tarball: &Path,
) -> Result<String> {
    upload(token, repo, Target::Id { id, tag }, tarball)
}

fn upload(token: &str, repo: &Repo, target: Target<'_>, tarball: &Path) -> Result<String> {
    let name = tarball
        .file_name()
        .and_then(|name| name.to_str())
        .context("asset name")?
        .to_owned();
    let body =
        bytes::Bytes::from(fs::read(tarball).with_context(|| tarball.display().to_string())?);
    block(async {
        let crab = client(token)?;
        upload_release_asset_with(&crab, repo, target, &name, body, &UPLOAD_SETTLE_DELAYS).await
    })
}

/// How long an upload refused as a duplicate waits for the other upload to
/// finish. GitHub lists an asset as soon as its upload starts, in a state
/// other than `uploaded`. A tarball of a few megabytes uploads in seconds, so a
/// minute covers a run that lost the race while the winner was still sending.
const UPLOAD_SETTLE_DELAYS: [Duration; 12] = [Duration::from_secs(5); 12];

/// The Release an upload or a checksum reads.
#[derive(Debug, Clone, Copy)]
pub(crate) enum Target<'a> {
    /// The Release found by its tag, draft or published.
    Tag(&'a str),
    /// The Release `id` of `tag`, which the run uses.
    Id {
        /// The Release id.
        id: u64,
        /// Its tag, for the messages.
        tag: &'a str,
    },
}

/// The Release `target` names.
async fn upload_target(crab: &Octocrab, repo: &Repo, target: Target<'_>) -> Result<ReleaseRecord> {
    match target {
        Target::Tag(tag) => find_release(crab, repo, tag, &ReleaseList::default())
            .await?
            .with_context(|| format!("release {tag} does not exist")),
        Target::Id { id, tag } => crab
            .get(
                format!(
                    "/repos/{owner}/{name}/releases/{id}",
                    owner = repo.owner,
                    name = repo.name
                ),
                None::<&()>,
            )
            .await
            .with_context(|| format!("read release {tag} (id {id})")),
    }
}

pub(crate) async fn upload_release_asset_with(
    crab: &Octocrab,
    repo: &Repo,
    target: Target<'_>,
    name: &str,
    body: bytes::Bytes,
    settle: &[Duration],
) -> Result<String> {
    let tag = match target {
        Target::Tag(tag) | Target::Id { tag, id: _ } => tag,
    };
    let release = upload_target(crab, repo, target).await?;
    if release.uploaded().contains(&name) {
        return Ok(format!("already {name}"));
    }
    let uploaded =
        asset_upload::post_release_asset(crab, repo, release.id, &release.upload_url, name, body)
            .await?;
    match uploaded {
        Ok(asset) => Ok(asset.browser_download_url.to_string()),
        // Two runs can release the same commit, and both build every asset.
        // The tarballs differ in bytes (tar records file times), so a digest
        // cannot separate a duplicate from a mismatch. The name carries the
        // version and the target, and the tag fixes the commit, so a complete
        // asset of that name is this asset.
        Err(error) if asset_upload::is_already_exists(&error) => {
            let mut delays = settle.iter();
            loop {
                let release = upload_target(crab, repo, target).await?;
                let asset = release
                    .assets
                    .iter()
                    .find(|asset| asset.name == name)
                    .with_context(|| {
                        format!(
                            "GitHub reports asset {name} exists, but release {tag} does not list it"
                        )
                    })?;
                if asset.state == "uploaded" {
                    return Ok(format!("already {name}"));
                }
                let Some(delay) = delays.next() else {
                    bail!(
                        "release {tag} has asset {name} in state {:?}, not uploaded, after waiting for another upload to finish; delete the asset and rerun",
                        asset.state
                    );
                };
                time::sleep(*delay).await;
            }
        }
        Err(error) => Err(error).context("upload release asset"),
    }
}