Skip to main content

verctl_github/
releases.rs

1use std::fmt;
2use std::time::Duration;
3
4use anyhow::{Context, Result, bail, ensure};
5use octocrab::Octocrab;
6use octocrab::repos::releases::MakeLatest;
7use tokio::time;
8use verctl_core::repo::Repo;
9
10use crate::drafts::{self, finalize, open_draft_with, publish_draft_with};
11use crate::release_state::{
12    ReleaseList, ReleaseRecord, find_release, find_release_for, read_tag, require_tag_at,
13};
14use crate::{asset_upload, block, client, is_not_found};
15
16/// Where a Release stands: the stable one, or a candidate before it.
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum Stage {
19    /// A stable version: GitHub's defaults apply, so the Release becomes the
20    /// repository's latest.
21    Stable,
22    /// A candidate: a prerelease that never becomes the latest Release, so
23    /// the repository's latest stays the stable one ([create a release]).
24    ///
25    /// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
26    Candidate,
27}
28
29/// The Release a run creates for a tag: a draft for `release`, or a Release
30/// published at once for [`ensure_release`].
31///
32/// Not `#[non_exhaustive]`: `verctl-release` constructs it directly.
33#[derive(Debug, Clone, Copy)]
34pub struct NewRelease<'a> {
35    /// The tag the Release is for.
36    pub tag: &'a str,
37    /// The Release title.
38    pub name: &'a str,
39    /// The Release notes.
40    pub body: &'a str,
41    /// The commit the tag is created at, and the one an existing tag must name.
42    pub sha: &'a str,
43    /// Whether the Release is the stable one or a candidate.
44    pub stage: Stage,
45    /// The asset names the draft must contain before it is published, because
46    /// an immutable Release takes no asset once published ([immutable
47    /// releases]). Empty, the draft is published with none.
48    ///
49    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
50    pub assets: &'a [String],
51}
52
53/// Whether a release run uploaded a package under a tag.
54#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
55pub enum PackageUpload {
56    /// This run published a package under the tag, so an existing release's
57    /// tag must match `sha`.
58    #[default]
59    Shipped,
60    /// Nothing under the tag shipped in this run; an existing published
61    /// release may stay at its earlier commit.
62    Skipped,
63}
64
65/// Create `tag` at `sha` if it is missing. Returns the release HTML URL.
66///
67/// A new Release is a [`Stage::Stable`] one, with GitHub's defaults, and is
68/// published at once. An existing release is used as it is, and a draft found
69/// is published.
70///
71/// An existing release is not trusted: GitHub's `target_commitish` on the
72/// Release object is a branch name more often than a SHA. The git ref is
73/// re-read either way, and a tag that names another commit fails.
74///
75/// # Errors
76///
77/// Returns an error when:
78///
79/// - The GitHub client cannot be built.
80/// - A release or tag lookup fails.
81/// - The release cannot be created, or a draft found cannot be published.
82/// - The tag does not point at `sha`.
83///
84/// The tag is checked against an existing release only when `upload` is
85/// [`PackageUpload::Shipped`].
86pub fn ensure_release(
87    token: &str,
88    repo: &Repo,
89    tag: &str,
90    name: &str,
91    body: &str,
92    sha: &str,
93    upload: PackageUpload,
94) -> Result<String> {
95    let release = NewRelease {
96        tag,
97        name,
98        body,
99        sha,
100        stage: Stage::Stable,
101        assets: &[],
102    };
103    block(async {
104        let crab = client(token)?;
105        ensure_release_with(&crab, repo, &release, upload).await
106    })
107}
108
109/// [`PackageUpload::Shipped`] means this run published a package under the
110/// tag. With [`PackageUpload::Skipped`], an existing published release belongs
111/// to the run that did, and its tag may name that earlier commit. A draft's
112/// tag is always checked.
113pub(crate) async fn ensure_release_with(
114    crab: &Octocrab,
115    repo: &Repo,
116    release: &NewRelease<'_>,
117    upload: PackageUpload,
118) -> Result<String> {
119    let NewRelease {
120        tag,
121        name,
122        body,
123        sha,
124        stage,
125        assets: _,
126    } = *release;
127    let existing = if read_tag(crab, repo, tag).await?.is_some() {
128        find_release(crab, repo, tag, &ReleaseList::default()).await?
129    } else {
130        None
131    };
132    match existing {
133        Some(found) if !found.draft => {
134            if matches!(upload, PackageUpload::Shipped) {
135                require_tag_at(crab, repo, tag, sha).await?;
136            }
137            return Ok(found.html_url);
138        }
139        Some(draft) => {
140            require_tag_at(crab, repo, tag, sha).await?;
141            return finalize(crab, repo, release, &draft).await;
142        }
143        None => {}
144    }
145    let repos = crab.repos(&repo.owner, &repo.name);
146    let releases = repos.releases();
147    let create = releases.create(tag).name(name).body(body);
148    let create = match stage {
149        Stage::Stable => create,
150        Stage::Candidate => create.prerelease(true).make_latest(MakeLatest::False),
151    };
152    let created = create
153        .target_commitish(sha)
154        .send()
155        .await
156        .map_err(|error| release_error(error, tag, sha))?;
157    require_tag_at(crab, repo, tag, sha).await?;
158    Ok(created.html_url.to_string())
159}
160
161/// How long the tag proof waits before each read after the first, while
162/// GitHub answers 404 for a tag that publishing the draft created.
163/// Five reads over 15 seconds, inside the 30 seconds the release-tag-order
164/// spec allows: GitHub can serve a new tag a moment after the Release that
165/// created it, as in rawr run 43414046487.
166pub const TAG_PROOF_DELAYS: [Duration; 4] = [
167    Duration::from_secs(1),
168    Duration::from_secs(2),
169    Duration::from_secs(4),
170    Duration::from_secs(8),
171];
172
173/// What a run finds on GitHub for one release tag, before it writes
174/// anything.
175#[derive(Debug)]
176pub enum ExistingRelease {
177    /// A Release published at HEAD. The run opens no draft for it and proves
178    /// its tag. A mutable one takes the declared tarballs it lacks, so an
179    /// older release missing a target can still be finished.
180    Published(ReleaseRecord),
181    /// No published Release: the run opens a draft for the tag.
182    DraftState(DraftState),
183}
184
185impl ExistingRelease {
186    /// The asset names already on the Release the run uploads to, or `None`
187    /// for a published immutable Release, which takes no asset ([immutable
188    /// releases]). Its shortfall is reported, and nothing is uploaded.
189    ///
190    /// [immutable releases]: https://docs.github.com/en/code-security/supply-chain-security/understanding-your-software-supply-chain/immutable-releases
191    #[must_use]
192    pub fn uploaded(&self) -> Option<Vec<&str>> {
193        match self {
194            Self::Published(release) if release.immutable => None,
195            Self::Published(release) => Some(release.uploaded()),
196            Self::DraftState(draft) => Some(draft.uploaded()),
197        }
198    }
199}
200
201/// A tag with no published Release, and the draft a run finds for it.
202#[derive(Debug)]
203pub enum DraftState {
204    /// No Release exists for the tag.
205    Missing,
206    /// A draft at HEAD, which the run uploads to and publishes.
207    AtHead(ReleaseRecord),
208    /// A draft at another commit or at a branch name. Its tarballs were built
209    /// from other code, so the run deletes it and creates a draft at HEAD.
210    Stale(ReleaseRecord),
211}
212
213impl DraftState {
214    /// The asset names uploaded on the draft the run keeps. A stale draft is
215    /// deleted, so nothing on it counts.
216    #[must_use]
217    pub fn uploaded(&self) -> Vec<&str> {
218        match self {
219            Self::AtHead(draft) => draft.uploaded(),
220            Self::Missing | Self::Stale(_) => Vec::new(),
221        }
222    }
223}
224
225/// Read what GitHub has for `tag`: the tag and its Release, draft or
226/// published, so a run reads what to create before it writes anything.
227///
228/// A tag that exists must name `head`, whatever the Release's state: GitHub
229/// uses an existing tag when a draft is published, so a tag on another commit
230/// would fail the tag proof after the uploads.
231/// A published Release counts as at HEAD when its tag names `head`, or when
232/// GitHub serves no tag yet and the Release's `target_commitish` is `head`.
233/// A draft counts as at HEAD when its `target_commitish` is `head`, or when
234/// its tag names `head`.
235///
236/// The Releases list comes from `list`, which the run shares with its plan.
237///
238/// # Errors
239///
240/// Returns an error when the GitHub client cannot be built, when a lookup
241/// fails, when the tag names a commit other than `head`, or when a Release is
242/// published at another commit.
243pub fn read_release(
244    token: &str,
245    repo: &Repo,
246    tag: &str,
247    head: &str,
248    list: &ReleaseList,
249) -> Result<ExistingRelease> {
250    block(async {
251        let crab = client(token)?;
252        read_release_with(&crab, repo, tag, None, head, list).await
253    })
254}
255
256/// Like [`read_release`], also matching an untagged draft Release
257/// (`untagged-*`) whose title equals `name` so reruns reuse or replace drafts
258/// whose tag GitHub cleared.
259///
260/// # Errors
261///
262/// Returns an error under the same conditions as [`read_release`].
263pub fn read_release_for(
264    token: &str,
265    repo: &Repo,
266    tag: &str,
267    name: &str,
268    head: &str,
269    list: &ReleaseList,
270) -> Result<ExistingRelease> {
271    block(async {
272        let crab = client(token)?;
273        read_release_with(&crab, repo, tag, Some(name), head, list).await
274    })
275}
276
277pub(crate) async fn read_release_with(
278    crab: &Octocrab,
279    repo: &Repo,
280    tag: &str,
281    title: Option<&str>,
282    head: &str,
283    list: &ReleaseList,
284) -> Result<ExistingRelease> {
285    let named = read_tag(crab, repo, tag).await?;
286    if let Some(named) = &named {
287        ensure!(
288            named.eq_ignore_ascii_case(head),
289            "tag {tag} names {named}, not HEAD {head}"
290        );
291    }
292    let Some(release) = find_release_for(crab, repo, tag, title, Some(head), list).await? else {
293        return Ok(ExistingRelease::DraftState(DraftState::Missing));
294    };
295    let untagged = release.tag_name != tag;
296    let at_head =
297        (named.is_some() && !untagged) || release.target_commitish.eq_ignore_ascii_case(head);
298    if release.draft {
299        return Ok(ExistingRelease::DraftState(if at_head {
300            DraftState::AtHead(release)
301        } else {
302            DraftState::Stale(release)
303        }));
304    }
305    ensure!(
306        at_head,
307        "release {tag} is published at {target}, not HEAD {head}, and GitHub serves no tag {tag}",
308        target = release.target_commitish
309    );
310    Ok(ExistingRelease::Published(release))
311}
312
313/// The id of the draft for `release`: the one `found` names at HEAD, or a new
314/// draft with `target_commitish` set to `release.sha`.
315/// A stale draft is deleted first.
316///
317/// The draft creates no tag: GitHub creates it at `target_commitish` when the
318/// draft is published ([create a release]).
319/// Until then the draft can still be changed or deleted, so a failed upload
320/// leaves no tag behind.
321///
322/// # Errors
323///
324/// Returns an error when the GitHub client cannot be built, a stale draft
325/// cannot be deleted, or the draft cannot be created.
326/// A 403 on the create names the missing permission.
327///
328/// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
329pub fn open_draft(
330    token: &str,
331    repo: &Repo,
332    release: &NewRelease<'_>,
333    found: &DraftState,
334) -> Result<u64> {
335    block(async {
336        let crab = client(token)?;
337        open_draft_with(&crab, repo, release, found).await
338    })
339}
340
341/// The HTML URL of the Release `id`, draft or published, which the report of
342/// a run that leaves the draft names.
343///
344/// # Errors
345///
346/// Returns an error when the GitHub client cannot be built or the Release
347/// cannot be read.
348pub fn release_url(token: &str, repo: &Repo, id: u64) -> Result<String> {
349    block(async {
350        let crab = client(token)?;
351        let release: ReleaseRecord = crab
352            .get(
353                format!(
354                    "/repos/{owner}/{name}/releases/{id}",
355                    owner = repo.owner,
356                    name = repo.name
357                ),
358                None::<&()>,
359            )
360            .await
361            .with_context(|| format!("read the release {id}"))?;
362        Ok(release.url().to_owned())
363    })
364}
365
366/// Publish the draft `id` for `release`, which creates its tag at
367/// `release.sha`, and return the Release URL.
368///
369/// The draft is read again first, so the check sees what GitHub has: a
370/// draft that lacks a declared asset is never published.
371///
372/// # Errors
373///
374/// Returns an error when the GitHub client cannot be built, the draft cannot
375/// be read or published, or it lacks a declared asset.
376pub fn publish_draft(
377    token: &str,
378    repo: &Repo,
379    release: &NewRelease<'_>,
380    id: u64,
381) -> Result<String> {
382    block(async {
383        let crab = client(token)?;
384        publish_draft_with(&crab, repo, release, id).await
385    })
386}
387
388/// Write `body` as the notes of draft `id` of `tag`, preserving `tag_name`
389/// while leaving `draft` unset so the draft keeps both its state and its tag.
390///
391/// # Errors
392///
393/// Returns an error when the GitHub client cannot be built or the update
394/// fails.
395pub fn write_draft_body(token: &str, repo: &Repo, tag: &str, id: u64, body: &str) -> Result<()> {
396    block(async {
397        let crab = client(token)?;
398        drafts::write_draft_body_with(&crab, repo, tag, id, body).await
399    })
400}
401
402/// Prove that `tag` names `head`, reading it again after each of `delays`
403/// while GitHub answers 404.
404///
405/// Publishing a draft creates its tag, and GitHub can serve the tag a moment
406/// after the Release. Only a 404 is read again: any other error, and a tag
407/// that names another commit, fail at once.
408///
409/// # Errors
410///
411/// Returns an error when the GitHub client cannot be built, a read fails with
412/// anything but 404, the tag names a commit other than `head`, or every read
413/// answers 404. The last names the tag and the number of reads.
414pub fn prove_tag(
415    token: &str,
416    repo: &Repo,
417    tag: &str,
418    head: &str,
419    delays: &[Duration],
420) -> Result<()> {
421    block(async {
422        let crab = client(token)?;
423        prove_tag_with(&crab, repo, tag, head, delays).await
424    })
425}
426
427pub(crate) async fn prove_tag_with(
428    crab: &Octocrab,
429    repo: &Repo,
430    tag: &str,
431    head: &str,
432    delays: &[Duration],
433) -> Result<()> {
434    let mut waits = delays.iter();
435    let mut reads = 0_usize;
436    loop {
437        reads += 1;
438        if let Some(named) = read_tag(crab, repo, tag).await? {
439            ensure!(
440                named.eq_ignore_ascii_case(head),
441                "tag {tag} names {named}, not HEAD {head}"
442            );
443            return Ok(());
444        }
445        let Some(wait) = waits.next() else {
446            bail!(
447                "GitHub serves no tag {tag} after {reads} reads, though its Release is published; rerun release to read the tag again"
448            );
449        };
450        time::sleep(*wait).await;
451    }
452}
453
454/// The Release for a vendored set's `tag`, created at `sha` when the tag has
455/// none. Returns its HTML URL.
456///
457/// An existing Release is used as it is.
458/// Its tag records which commit built the first asset, and that commit is
459/// not a version commit, so the tag target is not checked.
460///
461/// A new Release is created with `make_latest: false`.
462/// GitHub otherwise makes every new published Release the latest of the
463/// repository ([create a release]).
464/// A vendored library must not displace the Release of the repository itself.
465///
466/// # Errors
467///
468/// Returns an error when the GitHub client cannot be built or when reading the
469/// Release fails with anything but 404.
470/// It also returns one when creating the Release fails for any reason other
471/// than another job having created it first.
472///
473/// [create a release]: https://docs.github.com/en/rest/releases/releases#create-a-release
474pub fn ensure_vendored_release(
475    token: &str,
476    repo: &Repo,
477    tag: &str,
478    body: &str,
479    sha: &str,
480) -> Result<String> {
481    block(async {
482        let crab = client(token)?;
483        ensure_vendored_release_with(&crab, repo, tag, body, sha).await
484    })
485}
486
487/// Every target's job runs this, so two can find the Release missing at once.
488/// GitHub refuses one of them with `already_exists`, and that job reads the
489/// Release the other created.
490pub(crate) async fn ensure_vendored_release_with(
491    crab: &Octocrab,
492    repo: &Repo,
493    tag: &str,
494    body: &str,
495    sha: &str,
496) -> Result<String> {
497    let repos = crab.repos(&repo.owner, &repo.name);
498    let releases = repos.releases();
499    match releases.get_by_tag(tag).await {
500        Ok(release) => return Ok(release.html_url.to_string()),
501        Err(error) if is_not_found(&error) => {}
502        Err(error) => return Err(error).with_context(|| format!("read release {tag}")),
503    }
504    let created = releases
505        .create(tag)
506        .name(tag)
507        .body(body)
508        .target_commitish(sha)
509        .make_latest(MakeLatest::False)
510        .send()
511        .await;
512    match created {
513        Ok(release) => Ok(release.html_url.to_string()),
514        Err(error) if asset_upload::is_already_exists(&error) => {
515            let release = releases
516                .get_by_tag(tag)
517                .await
518                .with_context(|| format!("read release {tag}, which another job created"))?;
519            Ok(release.html_url.to_string())
520        }
521        Err(error) => Err(release_error(error, tag, sha)),
522    }
523}
524
525/// Names the cause of GitHub's 403 for a new Release.
526/// Creating a Release takes `contents: write`, plus `workflows: write` when
527/// the commit the tag would point at has a `.github/workflows` tree that
528/// differs from the default branch.
529/// The `X-Accepted-GitHub-Permissions` header of the refusal lists both sets.
530///
531/// An Actions `GITHUB_TOKEN` can never carry `workflows`, so releasing an
532/// older version commit fails once a later commit changes a workflow.
533pub(crate) fn release_error(error: octocrab::Error, tag: &str, sha: &str) -> anyhow::Error {
534    let forbidden = matches!(
535        &error,
536        octocrab::Error::GitHub { source, backtrace: _ } if source.status_code.as_u16() == 403
537    );
538    let error = anyhow::Error::new(error).context("create GitHub release");
539    if forbidden {
540        error.context(ReleaseRefused {
541            tag: tag.to_owned(),
542            sha: sha.to_owned(),
543        })
544    } else {
545        error
546    }
547}
548
549/// GitHub's 403 on creating a Release.
550/// The token lacks a permission the commit needs.
551/// A rerun with a token that has the permission can still create the Release.
552#[derive(Debug)]
553pub(crate) struct ReleaseRefused {
554    tag: String,
555    sha: String,
556}
557
558impl fmt::Display for ReleaseRefused {
559    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
560        write!(
561            f,
562            "GitHub refused to create {tag} at {sha}. When that commit's .github/workflows differ from the default branch, the Releases API also needs workflows: write, which GITHUB_TOKEN lacks; rerun verctl release at that commit with a token that has it",
563            tag = self.tag,
564            sha = self.sha
565        )
566    }
567}