//! Release operations shared by the web form, the REST API and CI auto-release. Each function //! checks the rules every caller needs (names, limits, that the release belongs to the repo), does //! the git work for tags, stores the row and emits the release webhooks. Callers only translate //! their input and output; pages keep their own form messages and redirects. //! //! A release names a git tag. A missing tag is created as a lightweight tag through //! `after_ref_update`; an existing tag is adopted as it is. Git tags are never deleted, and the tag //! of a published release is never moved in place. use std::io; use std::path::{Path, PathBuf}; use bytes::Bytes; use forge_core::releases::{ MAX_BODY_CHARS, MAX_TITLE_CHARS, NewAsset, NewRelease, Release, ReleaseAsset, ReleaseEdit, clean_content_type, valid_asset_name, }; use forge_core::webhooks::WebhookEvent; use forge_core::{Repo, User}; use forge_git::browse::{self, RefInfo, RefKind}; use forge_git::repo::repo_path; use forge_git::tags::{ commit_exists, create_lightweight_tag, move_lightweight_tag, valid_tag_name, }; use futures_util::{Stream, StreamExt}; use http::StatusCode; use crate::blobs::asset_key; use crate::live::Topic; use crate::post_update::after_ref_update; use crate::state::AppState; use crate::webhooks::emit::{Sender, emit}; /// Wakes the release list and the release pages of `repo`. Called after each write has succeeded. fn bump(state: &AppState, repo: &Repo) { state.live.bump(&Topic::RepoReleases(repo.id.clone())); } /// Why a release operation failed. `NotFound` also covers a release or asset that belongs to a /// different repo, so callers cannot probe other repos through these functions. #[derive(Debug)] pub enum ReleaseError { NotFound, Conflict(String), Invalid(String), TooLarge, Internal(forge_core::Error), } impl ReleaseError { /// The message to show. Internal errors show no detail; the caller logs them. pub fn message(&self) -> String { match self { Self::NotFound => "not found".to_owned(), Self::Conflict(message) | Self::Invalid(message) => message.clone(), Self::TooLarge => "the file is larger than the upload limit".to_owned(), Self::Internal(_) => "something went wrong".to_owned(), } } /// The HTTP status an API answers with. pub fn status(&self) -> StatusCode { match self { Self::NotFound => StatusCode::NOT_FOUND, Self::Conflict(_) => StatusCode::CONFLICT, Self::Invalid(_) => StatusCode::UNPROCESSABLE_ENTITY, Self::TooLarge => StatusCode::PAYLOAD_TOO_LARGE, Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, } } } impl std::fmt::Display for ReleaseError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.message()) } } impl From for ReleaseError { fn from(e: forge_core::Error) -> Self { match e { forge_core::Error::NotFound => Self::NotFound, forge_core::Error::Conflict(message) => Self::Conflict(message), forge_core::Error::Invalid(message) | forge_core::Error::InvalidName(message) => { Self::Invalid(message) } other => Self::Internal(other), } } } impl From for ReleaseError { fn from(e: forge_git::error::Error) -> Self { match e { forge_git::error::Error::InvalidInput(message) => Self::Invalid(message), forge_git::error::Error::RefMoved(_) => { Self::Conflict("the tag moved while it was being changed; try again".to_owned()) } other => Self::Internal(other.into()), } } } /// Input for [`create`]. `target` is a branch name or a commit id. It is used only when the tag /// does not exist yet; an empty or missing target means the repo's default branch. #[derive(Debug, Clone)] pub struct CreateRelease { pub tag: String, pub target: Option, pub title: String, pub body: String, pub draft: bool, pub prerelease: bool, } /// Input for [`update`]. `tag` retags the release: an existing git tag is adopted (and `target` /// must name its commit or be empty), a missing one is created at `target`, or at the old commit /// when `target` is empty. `target` on its own moves the tag of a draft. A published release keeps /// its tag, so it must pick a new one. #[derive(Debug, Clone)] pub struct EditRelease { pub title: String, pub body: String, pub draft: bool, pub prerelease: bool, pub tag: Option, pub target: Option, } /// The on-disk path of a repo. fn path_of(state: &AppState, repo: &Repo) -> Result { Ok(repo_path(&state.config.data_dir, &repo.id)?) } /// Every ref of a repo. Git runs on a blocking thread. async fn refs_of(path: PathBuf) -> Result, ReleaseError> { let refs = tokio::task::spawn_blocking(move || browse::list_refs(&path)) .await .map_err(|e| ReleaseError::Internal(forge_core::Error::Git(e.to_string())))?; Ok(refs?) } /// The commit a tag names, if the tag exists. fn tag_oid(refs: &[RefInfo], tag: &str) -> Option { refs.iter() .find(|r| r.kind == RefKind::Tag && r.name == tag) .map(|r| r.target.clone()) } /// The commit a target names: a branch of the repo, or a full commit id that exists. async fn resolve_target( state: &AppState, path: &Path, refs: &[RefInfo], target: &str, ) -> Result { if let Some(branch) = refs .iter() .find(|r| r.kind == RefKind::Branch && r.name == target) { return Ok(branch.target.clone()); } if commit_exists(&state.git, path, target).await { return Ok(target.to_owned()); } Err(ReleaseError::Invalid(format!( "no branch or commit named {target:?}" ))) } /// The zero object id, which git reads as "no ref yet". fn zero_oid(len: usize) -> String { "0".repeat(len) } /// Tells the ref hooks, webhooks, CI and mirrors that a tag moved from `old` to `new`. async fn fire_tag_hook( state: &AppState, repo: &Repo, actor: &User, tag: &str, old: &str, new: &str, ) { let refname = format!("refs/tags/{tag}"); if let Err(e) = after_ref_update(state, repo, &actor.id, &refname, old, new).await { tracing::error!(error = %e, repo_id = %repo.id, "releases: post-update for a tag failed"); } } /// Rejects a title or notes that are out of bounds. fn check_fields(title: &str, body: &str) -> Result<(), ReleaseError> { if title.is_empty() || title.chars().count() > MAX_TITLE_CHARS { return Err(ReleaseError::Invalid(format!( "the title must be 1 to {MAX_TITLE_CHARS} characters" ))); } if body.chars().count() > MAX_BODY_CHARS { return Err(ReleaseError::Invalid(format!( "the notes must be at most {MAX_BODY_CHARS} characters" ))); } Ok(()) } /// `NotFound` when the release belongs to another repo. fn ensure_same_repo(repo: &Repo, release: &Release) -> Result<(), ReleaseError> { if release.repo_id == repo.id { Ok(()) } else { Err(ReleaseError::NotFound) } } /// The webhook payload of a release event, sent to every hook that subscribes to `release`. async fn emit_release(state: &AppState, repo: &Repo, user: &User, action: &str, release: &Release) { let payload = serde_json::json!({ "release": { "id": release.id, "tag": release.tag, "target_oid": release.target_oid, "name": release.title, "draft": release.draft, "prerelease": release.prerelease, "published_at": release.published_at, } }); emit( state, repo, &Sender::of(user), WebhookEvent::Release, action, payload, ) .await; } /// Creates a release. An existing tag is adopted as it is; a missing one is created as a /// lightweight tag at `target`. A second release on the same tag is `Conflict`. A published /// release emits `published`. pub async fn create( state: &AppState, repo: &Repo, actor: &User, input: CreateRelease, ) -> Result { if !valid_tag_name(&input.tag) { return Err(ReleaseError::Invalid( "the tag name may only use letters, digits and . _ - +".to_owned(), )); } check_fields(&input.title, &input.body)?; if state .store .release_by_tag(&repo.id, &input.tag) .await? .is_some() { return Err(ReleaseError::Conflict( "a release already exists for this tag".to_owned(), )); } let path = path_of(state, repo)?; let refs = refs_of(path.clone()).await?; let target_oid = match tag_oid(&refs, &input.tag) { Some(oid) => oid, None => { let target = input .target .as_deref() .filter(|t| !t.is_empty()) .unwrap_or(&repo.default_branch); let oid = resolve_target(state, &path, &refs, target).await?; create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?; fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(oid.len()), &oid).await; oid } }; let created = state .store .create_release(&NewRelease { repo_id: &repo.id, tag: &input.tag, target_oid: &target_oid, title: &input.title, body: &input.body, draft: input.draft, prerelease: input.prerelease, author_id: &actor.id, }) .await?; bump(state, repo); if !created.draft { emit_release(state, repo, actor, "published", &created).await; } Ok(created) } /// Saves a release. The fields change in place. The tag rules are in [`EditRelease`]. A draft /// that becomes published emits `published`; any other change to a published release emits /// `updated`. pub async fn update( state: &AppState, repo: &Repo, actor: &User, release: &Release, edit: EditRelease, ) -> Result { ensure_same_repo(repo, release)?; check_fields(&edit.title, &edit.body)?; let new_tag = edit.tag.clone().unwrap_or_else(|| release.tag.clone()); let retag = new_tag != release.tag; if retag && !valid_tag_name(&new_tag) { return Err(ReleaseError::Invalid( "the tag name may only use letters, digits and . _ - +".to_owned(), )); } let wanted = edit.target.as_deref().filter(|t| !t.is_empty()); let path = path_of(state, repo)?; let refs = refs_of(path.clone()).await?; let mut target_oid = release.target_oid.clone(); if retag { if state .store .release_by_tag(&repo.id, &new_tag) .await? .is_some() { return Err(ReleaseError::Conflict( "a release already exists for this tag".to_owned(), )); } match tag_oid(&refs, &new_tag) { Some(existing) => { if let Some(target) = wanted && resolve_target(state, &path, &refs, target).await? != existing { return Err(ReleaseError::Invalid(format!( "the tag {new_tag} already exists at another commit" ))); } target_oid = existing; } None => { let oid = match wanted { Some(target) => resolve_target(state, &path, &refs, target).await?, None => release.target_oid.clone(), }; create_lightweight_tag(&state.git, &path, &new_tag, &oid).await?; fire_tag_hook(state, repo, actor, &new_tag, &zero_oid(oid.len()), &oid).await; target_oid = oid; } } } else if let Some(target) = wanted { if !release.draft { return Err(ReleaseError::Invalid( "published release tags can't be moved; pick a new tag".to_owned(), )); } let oid = resolve_target(state, &path, &refs, target).await?; match tag_oid(&refs, &release.tag) { Some(current) if current == oid => {} Some(current) => { move_lightweight_tag(&state.git, &path, &release.tag, &oid, ¤t).await?; fire_tag_hook(state, repo, actor, &release.tag, ¤t, &oid).await; } None => { create_lightweight_tag(&state.git, &path, &release.tag, &oid).await?; fire_tag_hook(state, repo, actor, &release.tag, &zero_oid(oid.len()), &oid).await; } } target_oid = oid; } if (retag || target_oid != release.target_oid) && !state .store .set_release_tag(&release.id, &new_tag, &target_oid) .await? { return Err(ReleaseError::NotFound); } let fields = ReleaseEdit { title: &edit.title, body: &edit.body, draft: edit.draft, prerelease: edit.prerelease, }; if !state.store.update_release(&release.id, &fields).await? { return Err(ReleaseError::NotFound); } bump(state, repo); let after = state .store .release(&release.id) .await? .ok_or(ReleaseError::NotFound)?; let action = match (release.draft, after.draft) { (true, false) => Some("published"), (true, true) => None, (false, _) => Some("updated"), }; if let Some(action) = action { emit_release(state, repo, actor, action, &after).await; } Ok(after) } /// Deletes a release and its assets, then their blobs. The git tag is kept. A published release /// emits `deleted`. pub async fn delete( state: &AppState, repo: &Repo, actor: &User, release: &Release, ) -> Result<(), ReleaseError> { ensure_same_repo(repo, release)?; let Some(asset_ids) = state.store.delete_release(&release.id).await? else { return Err(ReleaseError::NotFound); }; for asset_id in &asset_ids { if let Err(e) = state.blobs.delete(&asset_key(asset_id)).await { tracing::error!(error = %e, asset_id, "releases: could not delete an asset blob"); } } bump(state, repo); if !release.draft { emit_release(state, repo, actor, "deleted", release).await; } Ok(()) } /// Deletes one asset of a release and its blob. `NotFound` when the asset is not on this release. pub async fn delete_asset( state: &AppState, repo: &Repo, release: &Release, asset_id: &str, ) -> Result<(), ReleaseError> { ensure_same_repo(repo, release)?; let Some(row) = state.store.release_asset_by_id(asset_id).await? else { return Err(ReleaseError::NotFound); }; if row.release_id != release.id { return Err(ReleaseError::NotFound); } if !state.store.delete_release_asset(&row.id).await? { return Err(ReleaseError::NotFound); } if let Err(e) = state.blobs.delete(&asset_key(&row.id)).await { tracing::error!(error = %e, asset_id = %row.id, "releases: could not delete an asset blob"); } bump(state, repo); Ok(()) } /// Stores a file as an asset of `release`. The bytes are streamed into a fresh blob, so a refused /// or broken upload leaves nothing behind. A name the release already has is replaced: the row /// takes the new file and keeps its name and download count, and the old blob is deleted after /// the row is swapped. Returns the asset and whether it replaced an older file. #[allow(clippy::too_many_arguments)] // the signature is the one the callers share pub async fn put_asset( state: &AppState, repo: &Repo, release: &Release, uploader: &User, name: &str, content_type: Option<&str>, mut stream: impl Stream> + Unpin, max_bytes: u64, ) -> Result<(ReleaseAsset, bool), ReleaseError> { ensure_same_repo(repo, release)?; if !valid_asset_name(name) { return Err(ReleaseError::Invalid( "the file name may only use letters, digits and . _ - +".to_owned(), )); } let content_type = clean_content_type(content_type); let blob_id = ulid::Ulid::generate().to_string(); let key = asset_key(&blob_id); let mut writer = state.blobs.begin(&key, max_bytes).await?; while let Some(chunk) = stream.next().await { let chunk = match chunk { Ok(chunk) => chunk, Err(_) => { writer.abort().await; return Err(ReleaseError::Invalid( "the upload could not be read".to_owned(), )); } }; if let Err(e) = writer.push(&chunk).await { writer.abort().await; return Err(match e { forge_core::Error::Invalid(_) => ReleaseError::TooLarge, other => other.into(), }); } } let (size, sha256) = writer.finish().await?; let previous = state .store .release_asset(&release.id, name) .await? .map(|asset| asset.id); let new = NewAsset { id: &blob_id, release_id: &release.id, name, size, sha256: &sha256, content_type: &content_type, uploader_id: &uploader.id, }; let stored = match &previous { None => state.store.add_asset(&new).await, Some(old_id) => state.store.replace_asset(old_id, &new).await, }; let stored = match stored { Ok(stored) => stored, Err(e) => { if let Err(del) = state.blobs.delete(&key).await { tracing::error!(error = %del, "releases: could not remove an unlinked blob"); } return Err(e.into()); } }; if let Some(old_id) = &previous && let Err(e) = state.blobs.delete(&asset_key(old_id)).await { tracing::error!(error = %e, asset_id = %old_id, "releases: could not delete a replaced blob"); } bump(state, repo); Ok((stored, previous.is_some())) }