forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

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