Skip to main content

verctl_github/
release_assets.rs

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
14/// The hex SHA-256 that GitHub stores for asset `name` in the `tag` Release.
15/// It comes from the `digest` of the asset (`sha256:<hex>`, see
16/// [release assets]).
17/// Reading the digest from GitHub, instead of hashing a local file, keeps the
18/// checksum matching the stored asset.
19/// A rerun's build can differ in bytes from the one GitHub kept.
20///
21/// # Errors
22///
23/// Returns an error when the GitHub client cannot be built or the Release
24/// cannot be read.
25/// It also returns one when the Release does not list `name` or the asset has
26/// no SHA-256 digest.
27///
28/// [release assets]: https://docs.github.com/en/rest/releases/assets
29pub 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
56/// The names of the assets of the Release of `tag`, draft or published,
57/// whose upload completed.
58///
59/// # Errors
60///
61/// Returns an error when the GitHub client cannot be built, or when no
62/// Release exists for `tag`.
63pub 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/// A Release asset [`download_release_assets`] saved.
72#[derive(Debug)]
73#[non_exhaustive]
74pub struct AssetFile {
75    /// The asset's name, which is the file name it was saved under.
76    pub name: String,
77    /// Where it was saved.
78    pub path: PathBuf,
79    /// The SHA-256 GitHub reports for the stored file, in lowercase hex.
80    pub sha256: String,
81}
82
83/// How long one asset download may take.
84const DOWNLOAD_TIMEOUT: Duration = Duration::from_mins(5);
85
86/// Save each of `names` from the Release of `tag`, draft or published, into
87/// `dir` under its own name.
88///
89/// GitHub answers the asset API with a redirect to its storage. The token goes
90/// to GitHub only: the client follows no redirect itself, and fetches the
91/// storage URL without it ([release assets]).
92///
93/// # Errors
94///
95/// Returns an error when the GitHub client cannot be built, the Release does
96/// not exist or does not list one of `names`, or GitHub reports no SHA-256
97/// digest for one. It also returns one when a download fails or a file cannot
98/// be written.
99///
100/// [release assets]: https://docs.github.com/en/rest/releases/assets#get-a-release-asset
101pub 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
162/// The bytes of the asset at `url`: its API URL with the token, then the
163/// storage URL GitHub redirects to, without it. An error names `url` and
164/// never the storage URL, whose query string signs the download.
165async 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
205/// Attach `tarball` to the release for `tag`.
206///
207/// Returns the download URL, or `already <name>` when GitHub refuses the
208/// upload because the release already has a complete asset of that name.
209/// The run that got there first, or an earlier attempt of this one, uploaded
210/// it.
211///
212/// # Errors
213///
214/// Returns an error when:
215///
216/// - `tarball` has no UTF-8 file name or cannot be read.
217/// - The GitHub client cannot be built.
218/// - The release for `tag` does not exist.
219/// - The asset of that name exists but its upload does not complete within a
220///   minute.
221/// - The upload fails for a reason other than a duplicate asset.
222pub fn upload_release_asset(token: &str, repo: &Repo, tag: &str, tarball: &Path) -> Result<String> {
223    upload(token, repo, Target::Tag(tag), tarball)
224}
225
226/// [`upload_release_asset`] to the Release `id` of `tag`, which this run
227/// opened or found, so the upload never looks the Release up by its tag
228/// again: two drafts can share a tag name.
229///
230/// # Errors
231///
232/// Returns the errors of [`upload_release_asset`], with the Release read by
233/// its id.
234pub 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
258/// How long an upload refused as a duplicate waits for the other upload to
259/// finish. GitHub lists an asset as soon as its upload starts, in a state
260/// other than `uploaded`. A tarball of a few megabytes uploads in seconds, so a
261/// minute covers a run that lost the race while the winner was still sending.
262const UPLOAD_SETTLE_DELAYS: [Duration; 12] = [Duration::from_secs(5); 12];
263
264/// The Release an upload or a checksum reads.
265#[derive(Debug, Clone, Copy)]
266pub(crate) enum Target<'a> {
267    /// The Release found by its tag, draft or published.
268    Tag(&'a str),
269    /// The Release `id` of `tag`, which the run uses.
270    Id {
271        /// The Release id.
272        id: u64,
273        /// Its tag, for the messages.
274        tag: &'a str,
275    },
276}
277
278/// The Release `target` names.
279async 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        // Two runs can release the same commit, and both build every asset.
319        // The tarballs differ in bytes (tar records file times), so a digest
320        // cannot separate a duplicate from a mismatch. The name carries the
321        // version and the target, and the tag fixes the commit, so a complete
322        // asset of that name is this asset.
323        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}