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};
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}"))
}
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())
})
}
#[derive(Debug)]
#[non_exhaustive]
pub struct AssetFile {
pub name: String,
pub path: PathBuf,
pub sha256: String,
}
const DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(5);
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)
}
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}"))
}
pub fn upload_release_asset(token: &str, repo: &Repo, tag: &str, tarball: &Path) -> Result<String> {
upload(token, repo, Target::Tag(tag), tarball)
}
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
})
}
const UPLOAD_SETTLE_DELAYS: [Duration; 12] = [Duration::from_secs(5); 12];
#[derive(Debug, Clone, Copy)]
pub(crate) enum Target<'a> {
Tag(&'a str),
Id {
id: u64,
tag: &'a str,
},
}
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()),
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"),
}
}