forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.010.7 MiBb00f3f4Tahinli1 month ago147 commits

release_ops.rs538 lines, 18.1 KiBHistoryRawDownload
1//! Release operations shared by the web form, the REST API and CI auto-release. Each function
2//! checks the rules every caller needs (names, limits, that the release belongs to the repo), does
3//! the git work for tags, stores the row and emits the release webhooks. Callers only translate
4//! their input and output; pages keep their own form messages and redirects.
5//!
6//! A release names a git tag. A missing tag is created as a lightweight tag through
7//! `after_ref_update`; an existing tag is adopted as it is. Git tags are never deleted, and the tag
8//! of a published release is never moved in place.
9
10use std::io;
11use std::path::{Path, PathBuf};
12
13use bytes::Bytes;
14use forge_core::releases::{
15 MAX_BODY_CHARS, MAX_TITLE_CHARS, NewAsset, NewRelease, Release, ReleaseAsset, ReleaseEdit,
16 clean_content_type, valid_asset_name,
17};
18use forge_core::webhooks::WebhookEvent;
19use forge_core::{Repo, User};
20use forge_git::browse::{self, RefInfo, RefKind};
21use forge_git::repo::repo_path;
22use forge_git::tags::{
23 commit_exists, create_lightweight_tag, move_lightweight_tag, valid_tag_name,
24};
25use futures_util::{Stream, StreamExt};
26use http::StatusCode;
27
28use crate::blobs::asset_key;
29use crate::live::Topic;
30use crate::post_update::after_ref_update;
31use crate::state::AppState;
32use crate::webhooks::emit::{Sender, emit};
33
34/// Wakes the release list and the release pages of `repo`. Called after each write has succeeded.
35fn bump(state: &AppState, repo: &Repo) {
36 state.live.bump(&Topic::RepoReleases(repo.id.clone()));
37}
38
39/// Why a release operation failed. `NotFound` also covers a release or asset that belongs to a
40/// different repo, so callers cannot probe other repos through these functions.
41#[derive(Debug)]
42pub enum ReleaseError {
43 NotFound,
44 Conflict(String),
45 Invalid(String),
46 TooLarge,
47 Internal(forge_core::Error),
48}
49
50impl ReleaseError {
51 /// The message to show. Internal errors show no detail; the caller logs them.
52 pub fn message(&self) -> String {
53 match self {
54 Self::NotFound => "not found".to_owned(),
55 Self::Conflict(message) | Self::Invalid(message) => message.clone(),
56 Self::TooLarge => "the file is larger than the upload limit".to_owned(),
57 Self::Internal(_) => "something went wrong".to_owned(),
58 }
59 }
60
61 /// The HTTP status an API answers with.
62 pub fn status(&self) -> StatusCode {
63 match self {
64 Self::NotFound => StatusCode::NOT_FOUND,
65 Self::Conflict(_) => StatusCode::CONFLICT,
66 Self::Invalid(_) => StatusCode::UNPROCESSABLE_ENTITY,
67 Self::TooLarge => StatusCode::PAYLOAD_TOO_LARGE,
68 Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
69 }
70 }
71}
72
73impl std::fmt::Display for ReleaseError {
74 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
75 f.write_str(&self.message())
76 }
77}
78
79impl From<forge_core::Error> for ReleaseError {
80 fn from(e: forge_core::Error) -> Self {
81 match e {
82 forge_core::Error::NotFound => Self::NotFound,
83 forge_core::Error::Conflict(message) => Self::Conflict(message),
84 forge_core::Error::Invalid(message) | forge_core::Error::InvalidName(message) => {
85 Self::Invalid(message)
86 }
87 other => Self::Internal(other),
88 }
89 }
90}
91
92impl From<forge_git::error::Error> for ReleaseError {
93 fn from(e: forge_git::error::Error) -> Self {
94 match e {
95 forge_git::error::Error::InvalidInput(message) => Self::Invalid(message),
96 forge_git::error::Error::RefMoved(_) => {
97 Self::Conflict("the tag moved while it was being changed; try again".to_owned())
98 }
99 other => Self::Internal(other.into()),
100 }
101 }
102}
103
104/// Input for [`create`]. `target` is a branch name or a commit id. It is used only when the tag
105/// does not exist yet; an empty or missing target means the repo's default branch.
106#[derive(Debug, Clone)]
107pub struct CreateRelease {
108 pub tag: String,
109 pub target: Option<String>,
110 pub title: String,
111 pub body: String,
112 pub draft: bool,
113 pub prerelease: bool,
114}
115
116/// Input for [`update`]. `tag` retags the release: an existing git tag is adopted (and `target`
117/// must name its commit or be empty), a missing one is created at `target`, or at the old commit
118/// when `target` is empty. `target` on its own moves the tag of a draft. A published release keeps
119/// its tag, so it must pick a new one.
120#[derive(Debug, Clone)]
121pub struct EditRelease {
122 pub title: String,
123 pub body: String,
124 pub draft: bool,
125 pub prerelease: bool,
126 pub tag: Option<String>,
127 pub target: Option<String>,
128}
129
130/// The on-disk path of a repo.
131fn path_of(state: &AppState, repo: &Repo) -> Result<PathBuf, ReleaseError> {
132 Ok(repo_path(&state.config.data_dir, &repo.id)?)
133}
134
135/// Every ref of a repo. Git runs on a blocking thread.
136async fn refs_of(path: PathBuf) -> Result<Vec<RefInfo>, ReleaseError> {
137 let refs = tokio::task::spawn_blocking(move || browse::list_refs(&path))
138 .await
139 .map_err(|e| ReleaseError::Internal(forge_core::Error::Git(e.to_string())))?;
140 Ok(refs?)
141}
142
143/// The commit a tag names, if the tag exists.
144fn tag_oid(refs: &[RefInfo], tag: &str) -> Option<String> {
145 refs.iter()
146 .find(|r| r.kind == RefKind::Tag && r.name == tag)
147 .map(|r| r.target.clone())
148}
149
150/// The commit a target names: a branch of the repo, or a full commit id that exists.
151async fn resolve_target(
152 state: &AppState,
153 path: &Path,
154 refs: &[RefInfo],
155 target: &str,
156) -> Result<String, ReleaseError> {
157 if let Some(branch) = refs
158 .iter()
159 .find(|r| r.kind == RefKind::Branch && r.name == target)
160 {
161 return Ok(branch.target.clone());
162 }
163 if commit_exists(&state.git, path, target).await {
164 return Ok(target.to_owned());
165 }
166 Err(ReleaseError::Invalid(format!(
167 "no branch or commit named {target:?}"
168 )))
169}
170
171/// The zero object id, which git reads as "no ref yet".
172fn zero_oid(len: usize) -> String {
173 "0".repeat(len)
174}
175
176/// Tells the ref hooks, webhooks, CI and mirrors that a tag moved from `old` to `new`.
177async fn fire_tag_hook(
178 state: &AppState,
179 repo: &Repo,
180 actor: &User,
181 tag: &str,
182 old: &str,
183 new: &str,
184) {
185 let refname = format!("refs/tags/{tag}");
186 if let Err(e) = after_ref_update(state, repo, &actor.id, &refname, old, new).await {
187 tracing::error!(error = %e, repo_id = %repo.id, "releases: post-update for a tag failed");
188 }
189}
190
191/// Rejects a title or notes that are out of bounds.
192fn check_fields(title: &str, body: &str) -> Result<(), ReleaseError> {
193 if title.is_empty() || title.chars().count() > MAX_TITLE_CHARS {
194 return Err(ReleaseError::Invalid(format!(
195 "the title must be 1 to {MAX_TITLE_CHARS} characters"
196 )));
197 }
198 if body.chars().count() > MAX_BODY_CHARS {
199 return Err(ReleaseError::Invalid(format!(
200 "the notes must be at most {MAX_BODY_CHARS} characters"
201 )));
202 }
203 Ok(())
204}
205
206/// `NotFound` when the release belongs to another repo.
207fn ensure_same_repo(repo: &Repo, release: &Release) -> Result<(), ReleaseError> {
208 if release.repo_id == repo.id {
209 Ok(())
210 } else {
211 Err(ReleaseError::NotFound)
212 }
213}
214
215/// The webhook payload of a release event, sent to every hook that subscribes to `release`.
216async fn emit_release(state: &AppState, repo: &Repo, user: &User, action: &str, release: &Release) {
217 let payload = serde_json::json!({
218 "release": {
219 "id": release.id,
220 "tag": release.tag,
221 "target_oid": release.target_oid,
222 "name": release.title,
223 "draft": release.draft,
224 "prerelease": release.prerelease,
225 "published_at": release.published_at,
226 }
227 });
228 emit(
229 state,
230 repo,
231 &Sender::of(user),
232 WebhookEvent::Release,
233 action,
234 payload,
235 )
236 .await;
237}
238
239/// Creates a release. An existing tag is adopted as it is; a missing one is created as a
240/// lightweight tag at `target`. A second release on the same tag is `Conflict`. A published
241/// release emits `published`.
242pub async fn create(
243 state: &AppState,
244 repo: &Repo,
245 actor: &User,
246 input: CreateRelease,
247) -> Result<Release, ReleaseError> {
248 if !valid_tag_name(&input.tag) {
249 return Err(ReleaseError::Invalid(
250 "the tag name may only use letters, digits and . _ - +".to_owned(),
251 ));
252 }
253 check_fields(&input.title, &input.body)?;
254 if state
255 .store
256 .release_by_tag(&repo.id, &input.tag)
257 .await?
258 .is_some()
259 {
260 return Err(ReleaseError::Conflict(
261 "a release already exists for this tag".to_owned(),
262 ));
263 }
264 let path = path_of(state, repo)?;
265 let refs = refs_of(path.clone()).await?;
266 let target_oid = match tag_oid(&refs, &input.tag) {
267 Some(oid) => oid,
268 None => {
269 let target = input
270 .target
271 .as_deref()
272 .filter(|t| !t.is_empty())
273 .unwrap_or(&repo.default_branch);
274 let oid = resolve_target(state, &path, &refs, target).await?;
275 create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?;
276 fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(oid.len()), &oid).await;
277 oid
278 }
279 };
280 let created = state
281 .store
282 .create_release(&NewRelease {
283 repo_id: &repo.id,
284 tag: &input.tag,
285 target_oid: &target_oid,
286 title: &input.title,
287 body: &input.body,
288 draft: input.draft,
289 prerelease: input.prerelease,
290 author_id: &actor.id,
291 })
292 .await?;
293 bump(state, repo);
294 if !created.draft {
295 emit_release(state, repo, actor, "published", &created).await;
296 }
297 Ok(created)
298}
299
300/// Saves a release. The fields change in place. The tag rules are in [`EditRelease`]. A draft
301/// that becomes published emits `published`; any other change to a published release emits
302/// `updated`.
303pub async fn update(
304 state: &AppState,
305 repo: &Repo,
306 actor: &User,
307 release: &Release,
308 edit: EditRelease,
309) -> Result<Release, ReleaseError> {
310 ensure_same_repo(repo, release)?;
311 check_fields(&edit.title, &edit.body)?;
312 let new_tag = edit.tag.clone().unwrap_or_else(|| release.tag.clone());
313 let retag = new_tag != release.tag;
314 if retag && !valid_tag_name(&new_tag) {
315 return Err(ReleaseError::Invalid(
316 "the tag name may only use letters, digits and . _ - +".to_owned(),
317 ));
318 }
319 let wanted = edit.target.as_deref().filter(|t| !t.is_empty());
320 let path = path_of(state, repo)?;
321 let refs = refs_of(path.clone()).await?;
322 let mut target_oid = release.target_oid.clone();
323
324 if retag {
325 if state
326 .store
327 .release_by_tag(&repo.id, &new_tag)
328 .await?
329 .is_some()
330 {
331 return Err(ReleaseError::Conflict(
332 "a release already exists for this tag".to_owned(),
333 ));
334 }
335 match tag_oid(&refs, &new_tag) {
336 Some(existing) => {
337 if let Some(target) = wanted
338 && resolve_target(state, &path, &refs, target).await? != existing
339 {
340 return Err(ReleaseError::Invalid(format!(
341 "the tag {new_tag} already exists at another commit"
342 )));
343 }
344 target_oid = existing;
345 }
346 None => {
347 let oid = match wanted {
348 Some(target) => resolve_target(state, &path, &refs, target).await?,
349 None => release.target_oid.clone(),
350 };
351 create_lightweight_tag(&state.git, &path, &new_tag, &oid).await?;
352 fire_tag_hook(state, repo, actor, &new_tag, &zero_oid(oid.len()), &oid).await;
353 target_oid = oid;
354 }
355 }
356 } else if let Some(target) = wanted {
357 if !release.draft {
358 return Err(ReleaseError::Invalid(
359 "published release tags can't be moved; pick a new tag".to_owned(),
360 ));
361 }
362 let oid = resolve_target(state, &path, &refs, target).await?;
363 match tag_oid(&refs, &release.tag) {
364 Some(current) if current == oid => {}
365 Some(current) => {
366 move_lightweight_tag(&state.git, &path, &release.tag, &oid, &current).await?;
367 fire_tag_hook(state, repo, actor, &release.tag, &current, &oid).await;
368 }
369 None => {
370 create_lightweight_tag(&state.git, &path, &release.tag, &oid).await?;
371 fire_tag_hook(state, repo, actor, &release.tag, &zero_oid(oid.len()), &oid).await;
372 }
373 }
374 target_oid = oid;
375 }
376
377 if (retag || target_oid != release.target_oid)
378 && !state
379 .store
380 .set_release_tag(&release.id, &new_tag, &target_oid)
381 .await?
382 {
383 return Err(ReleaseError::NotFound);
384 }
385 let fields = ReleaseEdit {
386 title: &edit.title,
387 body: &edit.body,
388 draft: edit.draft,
389 prerelease: edit.prerelease,
390 };
391 if !state.store.update_release(&release.id, &fields).await? {
392 return Err(ReleaseError::NotFound);
393 }
394 bump(state, repo);
395 let after = state
396 .store
397 .release(&release.id)
398 .await?
399 .ok_or(ReleaseError::NotFound)?;
400 let action = match (release.draft, after.draft) {
401 (true, false) => Some("published"),
402 (true, true) => None,
403 (false, _) => Some("updated"),
404 };
405 if let Some(action) = action {
406 emit_release(state, repo, actor, action, &after).await;
407 }
408 Ok(after)
409}
410
411/// Deletes a release and its assets, then their blobs. The git tag is kept. A published release
412/// emits `deleted`.
413pub async fn delete(
414 state: &AppState,
415 repo: &Repo,
416 actor: &User,
417 release: &Release,
418) -> Result<(), ReleaseError> {
419 ensure_same_repo(repo, release)?;
420 let Some(asset_ids) = state.store.delete_release(&release.id).await? else {
421 return Err(ReleaseError::NotFound);
422 };
423 for asset_id in &asset_ids {
424 if let Err(e) = state.blobs.delete(&asset_key(asset_id)).await {
425 tracing::error!(error = %e, asset_id, "releases: could not delete an asset blob");
426 }
427 }
428 bump(state, repo);
429 if !release.draft {
430 emit_release(state, repo, actor, "deleted", release).await;
431 }
432 Ok(())
433}
434
435/// Deletes one asset of a release and its blob. `NotFound` when the asset is not on this release.
436pub async fn delete_asset(
437 state: &AppState,
438 repo: &Repo,
439 release: &Release,
440 asset_id: &str,
441) -> Result<(), ReleaseError> {
442 ensure_same_repo(repo, release)?;
443 let Some(row) = state.store.release_asset_by_id(asset_id).await? else {
444 return Err(ReleaseError::NotFound);
445 };
446 if row.release_id != release.id {
447 return Err(ReleaseError::NotFound);
448 }
449 if !state.store.delete_release_asset(&row.id).await? {
450 return Err(ReleaseError::NotFound);
451 }
452 if let Err(e) = state.blobs.delete(&asset_key(&row.id)).await {
453 tracing::error!(error = %e, asset_id = %row.id, "releases: could not delete an asset blob");
454 }
455 bump(state, repo);
456 Ok(())
457}
458
459/// Stores a file as an asset of `release`. The bytes are streamed into a fresh blob, so a refused
460/// or broken upload leaves nothing behind. A name the release already has is replaced: the row
461/// takes the new file and keeps its name and download count, and the old blob is deleted after
462/// the row is swapped. Returns the asset and whether it replaced an older file.
463#[allow(clippy::too_many_arguments)] // the signature is the one the callers share
464pub async fn put_asset(
465 state: &AppState,
466 repo: &Repo,
467 release: &Release,
468 uploader: &User,
469 name: &str,
470 content_type: Option<&str>,
471 mut stream: impl Stream<Item = io::Result<Bytes>> + Unpin,
472 max_bytes: u64,
473) -> Result<(ReleaseAsset, bool), ReleaseError> {
474 ensure_same_repo(repo, release)?;
475 if !valid_asset_name(name) {
476 return Err(ReleaseError::Invalid(
477 "the file name may only use letters, digits and . _ - +".to_owned(),
478 ));
479 }
480 let content_type = clean_content_type(content_type);
481 let blob_id = ulid::Ulid::generate().to_string();
482 let key = asset_key(&blob_id);
483 let mut writer = state.blobs.begin(&key, max_bytes).await?;
484 while let Some(chunk) = stream.next().await {
485 let chunk = match chunk {
486 Ok(chunk) => chunk,
487 Err(_) => {
488 writer.abort().await;
489 return Err(ReleaseError::Invalid(
490 "the upload could not be read".to_owned(),
491 ));
492 }
493 };
494 if let Err(e) = writer.push(&chunk).await {
495 writer.abort().await;
496 return Err(match e {
497 forge_core::Error::Invalid(_) => ReleaseError::TooLarge,
498 other => other.into(),
499 });
500 }
501 }
502 let (size, sha256) = writer.finish().await?;
503
504 let previous = state
505 .store
506 .release_asset(&release.id, name)
507 .await?
508 .map(|asset| asset.id);
509 let new = NewAsset {
510 id: &blob_id,
511 release_id: &release.id,
512 name,
513 size,
514 sha256: &sha256,
515 content_type: &content_type,
516 uploader_id: &uploader.id,
517 };
518 let stored = match &previous {
519 None => state.store.add_asset(&new).await,
520 Some(old_id) => state.store.replace_asset(old_id, &new).await,
521 };
522 let stored = match stored {
523 Ok(stored) => stored,
524 Err(e) => {
525 if let Err(del) = state.blobs.delete(&key).await {
526 tracing::error!(error = %del, "releases: could not remove an unlinked blob");
527 }
528 return Err(e.into());
529 }
530 };
531 if let Some(old_id) = &previous
532 && let Err(e) = state.blobs.delete(&asset_key(old_id)).await
533 {
534 tracing::error!(error = %e, asset_id = %old_id, "releases: could not delete a replaced blob");
535 }
536 bump(state, repo);
537 Ok((stored, previous.is_some()))
538}