1use std::fs;
2use std::path::{Path, PathBuf};
3use std::time::Duration;
4
5use anyhow::{Context, Result, bail, ensure};
6use octocrab::Octocrab;
7use reqwest::redirect::Policy;
8use tokio::time;
9use verctl_core::repo::Repo;
10
11use crate::release_state::{ReleaseList, ReleaseRecord, find_release};
12use crate::{asset_upload, block, client};
13
14pub fn asset_sha256(token: &str, repo: &Repo, tag: &str, name: &str) -> Result<String> {
30 block(async {
31 let crab = client(token)?;
32 asset_sha256_with(&crab, repo, tag, name).await
33 })
34}
35
36pub(crate) async fn asset_sha256_with(
37 crab: &Octocrab,
38 repo: &Repo,
39 tag: &str,
40 name: &str,
41) -> Result<String> {
42 let release = upload_target(crab, repo, Target::Tag(tag)).await?;
43 let asset = release
44 .assets
45 .iter()
46 .find(|asset| asset.name == name)
47 .with_context(|| format!("release {tag} does not list asset {name}"))?;
48 asset
49 .digest
50 .as_deref()
51 .and_then(|digest| digest.strip_prefix("sha256:"))
52 .map(str::to_owned)
53 .with_context(|| format!("GitHub reports no SHA-256 digest for asset {name} of {tag}"))
54}
55
56pub fn uploaded_assets(token: &str, repo: &Repo, tag: &str) -> Result<Vec<String>> {
64 block(async {
65 let crab = client(token)?;
66 let release = upload_target(&crab, repo, Target::Tag(tag)).await?;
67 Ok(release.uploaded().into_iter().map(str::to_owned).collect())
68 })
69}
70
71#[derive(Debug)]
73#[non_exhaustive]
74pub struct AssetFile {
75 pub name: String,
77 pub path: PathBuf,
79 pub sha256: String,
81}
82
83const DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(5);
85
86pub fn download_release_assets(
102 token: &str,
103 repo: &Repo,
104 tag: &str,
105 names: &[&str],
106 dir: &Path,
107) -> Result<Vec<AssetFile>> {
108 block(async {
109 let crab = client(token)?;
110 download_release_assets_with(&crab, token, repo, tag, names, dir).await
111 })
112}
113
114pub(crate) async fn download_release_assets_with(
115 crab: &Octocrab,
116 token: &str,
117 repo: &Repo,
118 tag: &str,
119 names: &[&str],
120 dir: &Path,
121) -> Result<Vec<AssetFile>> {
122 let release = upload_target(crab, repo, Target::Tag(tag)).await?;
123 let http = reqwest::Client::builder()
124 .redirect(Policy::none())
125 .user_agent(format!("verctl/{}", env!("CARGO_PKG_VERSION")))
126 .timeout(DOWNLOAD_TIMEOUT)
127 .build()
128 .context("HTTP client")?;
129 let mut saved = Vec::new();
130 for name in names {
131 let asset = release
132 .assets
133 .iter()
134 .find(|asset| asset.name == *name)
135 .with_context(|| format!("release {tag} does not list asset {name}"))?;
136 ensure!(
137 !asset.url.is_empty(),
138 "GitHub reports no API URL for asset {name} of {tag}"
139 );
140 let sha256 = asset
141 .digest
142 .as_deref()
143 .and_then(|digest| digest.strip_prefix("sha256:"))
144 .map(str::to_owned)
145 .with_context(|| {
146 format!("GitHub reports no SHA-256 digest for asset {name} of {tag}")
147 })?;
148 let body = download_asset(&http, token, &asset.url)
149 .await
150 .with_context(|| format!("download {name} from release {tag}"))?;
151 let path = dir.join(name);
152 fs::write(&path, &body).with_context(|| path.display().to_string())?;
153 saved.push(AssetFile {
154 name: (*name).to_owned(),
155 path,
156 sha256,
157 });
158 }
159 Ok(saved)
160}
161
162async fn download_asset(http: &reqwest::Client, token: &str, url: &str) -> Result<bytes::Bytes> {
166 use reqwest::header::{ACCEPT, LOCATION};
167 let response = http
168 .get(url)
169 .bearer_auth(token)
170 .header(ACCEPT, "application/octet-stream")
171 .send()
172 .await
173 .with_context(|| format!("GET {url}"))?;
174 let response = if response.status().is_redirection() {
175 let location = response
176 .headers()
177 .get(LOCATION)
178 .and_then(|value| value.to_str().ok())
179 .with_context(|| format!("GET {url}: a redirect with no Location"))?
180 .to_owned();
181 http.get(location)
182 .send()
183 .await
184 .map_err(reqwest::Error::without_url)
185 .with_context(|| format!("GET the storage URL {url} redirects to"))?
186 } else {
187 response
188 };
189 let response = response
190 .error_for_status()
191 .map_err(reqwest::Error::without_url)
192 .with_context(|| format!("GET {url}"))?;
193 ensure!(
194 response.status().is_success(),
195 "GET {url}: unexpected status {}",
196 response.status()
197 );
198 response
199 .bytes()
200 .await
201 .map_err(reqwest::Error::without_url)
202 .with_context(|| format!("read {url}"))
203}
204
205pub fn upload_release_asset(token: &str, repo: &Repo, tag: &str, tarball: &Path) -> Result<String> {
223 upload(token, repo, Target::Tag(tag), tarball)
224}
225
226pub fn upload_to_release(
235 token: &str,
236 repo: &Repo,
237 id: u64,
238 tag: &str,
239 tarball: &Path,
240) -> Result<String> {
241 upload(token, repo, Target::Id { id, tag }, tarball)
242}
243
244fn upload(token: &str, repo: &Repo, target: Target<'_>, tarball: &Path) -> Result<String> {
245 let name = tarball
246 .file_name()
247 .and_then(|name| name.to_str())
248 .context("asset name")?
249 .to_owned();
250 let body =
251 bytes::Bytes::from(fs::read(tarball).with_context(|| tarball.display().to_string())?);
252 block(async {
253 let crab = client(token)?;
254 upload_release_asset_with(&crab, repo, target, &name, body, &UPLOAD_SETTLE_DELAYS).await
255 })
256}
257
258const UPLOAD_SETTLE_DELAYS: [Duration; 12] = [Duration::from_secs(5); 12];
263
264#[derive(Debug, Clone, Copy)]
266pub(crate) enum Target<'a> {
267 Tag(&'a str),
269 Id {
271 id: u64,
273 tag: &'a str,
275 },
276}
277
278async fn upload_target(crab: &Octocrab, repo: &Repo, target: Target<'_>) -> Result<ReleaseRecord> {
280 match target {
281 Target::Tag(tag) => find_release(crab, repo, tag, &ReleaseList::default())
282 .await?
283 .with_context(|| format!("release {tag} does not exist")),
284 Target::Id { id, tag } => crab
285 .get(
286 format!(
287 "/repos/{owner}/{name}/releases/{id}",
288 owner = repo.owner,
289 name = repo.name
290 ),
291 None::<&()>,
292 )
293 .await
294 .with_context(|| format!("read release {tag} (id {id})")),
295 }
296}
297
298pub(crate) async fn upload_release_asset_with(
299 crab: &Octocrab,
300 repo: &Repo,
301 target: Target<'_>,
302 name: &str,
303 body: bytes::Bytes,
304 settle: &[Duration],
305) -> Result<String> {
306 let tag = match target {
307 Target::Tag(tag) | Target::Id { tag, id: _ } => tag,
308 };
309 let release = upload_target(crab, repo, target).await?;
310 if release.uploaded().contains(&name) {
311 return Ok(format!("already {name}"));
312 }
313 let uploaded =
314 asset_upload::post_release_asset(crab, repo, release.id, &release.upload_url, name, body)
315 .await?;
316 match uploaded {
317 Ok(asset) => Ok(asset.browser_download_url.to_string()),
318 Err(error) if asset_upload::is_already_exists(&error) => {
324 let mut delays = settle.iter();
325 loop {
326 let release = upload_target(crab, repo, target).await?;
327 let asset = release
328 .assets
329 .iter()
330 .find(|asset| asset.name == name)
331 .with_context(|| {
332 format!(
333 "GitHub reports asset {name} exists, but release {tag} does not list it"
334 )
335 })?;
336 if asset.state == "uploaded" {
337 return Ok(format!("already {name}"));
338 }
339 let Some(delay) = delays.next() else {
340 bail!(
341 "release {tag} has asset {name} in state {:?}, not uploaded, after waiting for another upload to finish; delete the asset and rerun",
342 asset.state
343 );
344 };
345 time::sleep(*delay).await;
346 }
347 }
348 Err(error) => Err(error).context("upload release asset"),
349 }
350}