Public CI JSON API (runs list by ref, run detail with jobs and steps, live run SSE) and tag API (create through the push post-update path, list)
Browse files at this commit7ef8c05e80fe9e95f1980863607b88abd52b467cParent: 2e29cbcSome checks failed
Show checks
ci/buildjob was cancelledDetails
- feat
- public CI JSON API (runs list by ref, run detail with jobs and steps, live run SSE) and tag API (create through the push post-update path, list)
- fixes: plain job log stream flushes a final line without newline once the job ends, pressure test no longer depends on host swap
11 changed files +511 -20
- crates/forge-core/src/store/ci.rs +24 -0
- crates/forge-runner/src/pressure.rs +1 -1
- crates/forge-web-app/src/api/ci.rs +183 -0
- crates/forge-web-app/src/api/mod.rs +2 -0
- crates/forge-web-app/src/api/releases.rs +31 -0
- crates/forge-web-app/src/api/tags.rs +85 -0
- crates/forge-web-app/src/ci/api_tests.rs +48 -0
- crates/forge-web-app/src/release_ops.rs +49 -11
- crates/forge-web-pages/src/pages/ci_job.rs +7 -8
- crates/forge-web/src/routes.snap +5 -0
- docs/api.md +76 -0
crates/forge-core/src/store/ci.rsmodified+24 -0
| @@ -1584,6 +1584,30 @@ impl Store { | ||
| 1584 | 1584 | Ok((runs, total)) |
| 1585 | 1585 | } |
| 1586 | 1586 | |
| 1587 | + pub async fn runs_on_ref( | |
| 1588 | + &self, | |
| 1589 | + repo_id: &str, | |
| 1590 | + git_ref: &str, | |
| 1591 | + limit: u32, | |
| 1592 | + ) -> Result<Vec<CiRun>> { | |
| 1593 | + let conn = self.read_conn().await; | |
| 1594 | + fetch_all( | |
| 1595 | + &conn, | |
| 1596 | + &format!( | |
| 1597 | + "SELECT {RUN_COLS} FROM ci_runs WHERE repo_id = ?1 \ | |
| 1598 | + AND git_ref IN (?2, 'refs/heads/' || ?2, 'refs/tags/' || ?2) \ | |
| 1599 | + ORDER BY number DESC LIMIT ?3" | |
| 1600 | + ), | |
| 1601 | + ( | |
| 1602 | + repo_id.to_string(), | |
| 1603 | + git_ref.to_string(), | |
| 1604 | + i64::from(limit.clamp(1, MAX_PER_PAGE)), | |
| 1605 | + ), | |
| 1606 | + map_run, | |
| 1607 | + ) | |
| 1608 | + .await | |
| 1609 | + } | |
| 1610 | + | |
| 1587 | 1611 | pub async fn jobs_for_run(&self, run_id: &str) -> Result<Vec<CiJob>> { |
| 1588 | 1612 | let conn = self.read_conn().await; |
| 1589 | 1613 | jobs_of_run(&conn, run_id).await |
crates/forge-runner/src/pressure.rsmodified+1 -1
| @@ -867,7 +867,7 @@ mod tests { | ||
| 867 | 867 | let b = pressure.register("b", "test", tx_b); |
| 868 | 868 | fake_job(tmp.path(), "a", 2 * GIB); |
| 869 | 869 | let dir_b = fake_job(tmp.path(), "b", 2 * GIB); |
| 870 | - fs::write(dir_b.join("memory.stat"), "anon 1\n").expect("stat"); | |
| 870 | + fs::write(dir_b.join("memory.stat"), "anon 0\n").expect("stat"); | |
| 871 | 871 | pressure.settle(Cause::Jobs); |
| 872 | 872 | pressure.settle(Cause::Pressure); |
| 873 | 873 | assert!(b.requeued()); |
crates/forge-web-app/src/api/ci.rsadded+183 -0
| @@ -0,0 +1,183 @@ | ||
| 1 | +use forge_core::ci::{CiRun, JobStep, StepState}; | |
| 2 | +use forge_core::{Action, Store, User, authorize}; | |
| 3 | +use serde_json::{Value, json}; | |
| 4 | +use topcoat::context::{Cx, context}; | |
| 5 | +use topcoat::router::request::headers; | |
| 6 | +use topcoat::router::response::Response; | |
| 7 | +use topcoat::router::{StatusCode, path_param, route}; | |
| 8 | + | |
| 9 | +use crate::api; | |
| 10 | +use crate::client_ip::client_ip; | |
| 11 | +use crate::live::{changed_stream, events_response}; | |
| 12 | +use crate::state::AppState; | |
| 13 | +use crate::views::query_value; | |
| 14 | + | |
| 15 | +path_param!(owner); | |
| 16 | +path_param!(repo); | |
| 17 | +path_param!(run_number); | |
| 18 | + | |
| 19 | +const DEFAULT_LIMIT: u32 = 20; | |
| 20 | + | |
| 21 | +fn step_state(state: StepState) -> &'static str { | |
| 22 | + match state { | |
| 23 | + StepState::Running => "running", | |
| 24 | + StepState::Passed => "success", | |
| 25 | + StepState::Failed => "failure", | |
| 26 | + StepState::Cancelled => "cancelled", | |
| 27 | + } | |
| 28 | +} | |
| 29 | + | |
| 30 | +async fn run_json(store: &Store, run: &CiRun) -> forge_core::Result<Value> { | |
| 31 | + let jobs = store.jobs_for_run(&run.id).await?; | |
| 32 | + let steps = store.steps_for_run(&run.id).await?; | |
| 33 | + let started_at = jobs | |
| 34 | + .iter() | |
| 35 | + .filter_map(|job| job.started_at.as_deref()) | |
| 36 | + .min(); | |
| 37 | + let jobs: Vec<Value> = jobs | |
| 38 | + .iter() | |
| 39 | + .map(|job| { | |
| 40 | + let steps: Vec<Value> = steps | |
| 41 | + .iter() | |
| 42 | + .filter(|step: &&JobStep| step.job_id == job.id) | |
| 43 | + .map(|step| { | |
| 44 | + json!({ | |
| 45 | + "name": step.name, | |
| 46 | + "state": step_state(step.state(job.state)), | |
| 47 | + "started_at": step.started_at, | |
| 48 | + "finished_at": step.finished_at, | |
| 49 | + }) | |
| 50 | + }) | |
| 51 | + .collect(); | |
| 52 | + json!({ | |
| 53 | + "id": job.id, | |
| 54 | + "name": job.name, | |
| 55 | + "state": job.state.as_str(), | |
| 56 | + "started_at": job.started_at, | |
| 57 | + "finished_at": job.finished_at, | |
| 58 | + "exit_code": job.exit_code, | |
| 59 | + "steps": steps, | |
| 60 | + }) | |
| 61 | + }) | |
| 62 | + .collect(); | |
| 63 | + Ok(json!({ | |
| 64 | + "number": run.number, | |
| 65 | + "ref": run.git_ref, | |
| 66 | + "sha": run.commit_oid, | |
| 67 | + "trigger": run.trigger, | |
| 68 | + "state": run.state.as_str(), | |
| 69 | + "created_at": run.created_at, | |
| 70 | + "started_at": started_at, | |
| 71 | + "finished_at": run.finished_at, | |
| 72 | + "jobs": jobs, | |
| 73 | + })) | |
| 74 | +} | |
| 75 | + | |
| 76 | +async fn readable(store: &Store, actor: Option<&User>, repo_id: &str) -> bool { | |
| 77 | + let Ok(Some(repo)) = store.repo_by_id(repo_id).await else { | |
| 78 | + return false; | |
| 79 | + }; | |
| 80 | + let Ok((role, org_role)) = store.user_roles(&repo, actor).await else { | |
| 81 | + return false; | |
| 82 | + }; | |
| 83 | + authorize(actor, &repo, role, org_role, Action::Read).is_ok() | |
| 84 | +} | |
| 85 | + | |
| 86 | +async fn reader(cx: &Cx) -> Result<(forge_core::Repo, Option<User>), api::Refusal> { | |
| 87 | + let state = context::<AppState>(cx); | |
| 88 | + let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?; | |
| 89 | + let repo = api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Read).await?; | |
| 90 | + Ok((repo, actor)) | |
| 91 | +} | |
| 92 | + | |
| 93 | +async fn run_of(cx: &Cx, repo_id: &str) -> Result<CiRun, api::Refusal> { | |
| 94 | + let state = context::<AppState>(cx); | |
| 95 | + let missing = || Box::new(api::error(StatusCode::NOT_FOUND, "run not found")); | |
| 96 | + let number = run_number(cx).parse::<i64>().map_err(|_| missing())?; | |
| 97 | + match state.store.run_by_number(repo_id, number).await { | |
| 98 | + Ok(Some(run)) => Ok(run), | |
| 99 | + Ok(None) => Err(missing()), | |
| 100 | + Err(e) => Err(api::internal(e)), | |
| 101 | + } | |
| 102 | +} | |
| 103 | + | |
| 104 | +#[route(GET "/api/v1/repos/{owner}/{repo}/ci/runs")] | |
| 105 | +async fn list_runs(cx: &Cx) -> topcoat::Result<Response> { | |
| 106 | + let state = context::<AppState>(cx); | |
| 107 | + let (repo, _) = match reader(cx).await { | |
| 108 | + Ok(found) => found, | |
| 109 | + Err(res) => return Ok(*res), | |
| 110 | + }; | |
| 111 | + let limit = query_value(cx, "limit") | |
| 112 | + .and_then(|raw| raw.parse::<u32>().ok()) | |
| 113 | + .unwrap_or(DEFAULT_LIMIT); | |
| 114 | + let runs = match query_value(cx, "ref") { | |
| 115 | + Some(git_ref) => state.store.runs_on_ref(&repo.id, &git_ref, limit).await, | |
| 116 | + None => state | |
| 117 | + .store | |
| 118 | + .list_runs(&repo.id, 1, limit) | |
| 119 | + .await | |
| 120 | + .map(|(runs, _)| runs), | |
| 121 | + }; | |
| 122 | + let runs = match runs { | |
| 123 | + Ok(runs) => runs, | |
| 124 | + Err(e) => return Ok(*api::internal(e)), | |
| 125 | + }; | |
| 126 | + let mut out = Vec::with_capacity(runs.len()); | |
| 127 | + for run in &runs { | |
| 128 | + match run_json(&state.store, run).await { | |
| 129 | + Ok(value) => out.push(value), | |
| 130 | + Err(e) => return Ok(*api::internal(e)), | |
| 131 | + } | |
| 132 | + } | |
| 133 | + Ok(api::json(StatusCode::OK, &out)) | |
| 134 | +} | |
| 135 | + | |
| 136 | +#[route(GET "/api/v1/repos/{owner}/{repo}/ci/runs/{run_number}")] | |
| 137 | +async fn get_run(cx: &Cx) -> topcoat::Result<Response> { | |
| 138 | + let state = context::<AppState>(cx); | |
| 139 | + let result = async { | |
| 140 | + let (repo, _) = reader(cx).await?; | |
| 141 | + let run = run_of(cx, &repo.id).await?; | |
| 142 | + run_json(&state.store, &run).await.map_err(api::internal) | |
| 143 | + } | |
| 144 | + .await; | |
| 145 | + Ok(match result { | |
| 146 | + Ok(value) => api::json(StatusCode::OK, &value), | |
| 147 | + Err(res) => *res, | |
| 148 | + }) | |
| 149 | +} | |
| 150 | + | |
| 151 | +#[route(GET "/api/v1/repos/{owner}/{repo}/ci/runs/{run_number}/events")] | |
| 152 | +async fn run_events(cx: &Cx) -> topcoat::Result<Response> { | |
| 153 | + let state = context::<AppState>(cx); | |
| 154 | + let (repo, actor, run) = match async { | |
| 155 | + let (repo, actor) = reader(cx).await?; | |
| 156 | + let run = run_of(cx, &repo.id).await?; | |
| 157 | + Ok::<_, api::Refusal>((repo, actor, run)) | |
| 158 | + } | |
| 159 | + .await | |
| 160 | + { | |
| 161 | + Ok(found) => found, | |
| 162 | + Err(res) => return Ok(*res), | |
| 163 | + }; | |
| 164 | + let wake = state.ci_live.subscribe_run(&run.id); | |
| 165 | + let store = state.store.clone(); | |
| 166 | + let events = changed_stream(wake, true, "run", move || { | |
| 167 | + let store = store.clone(); | |
| 168 | + let actor = actor.clone(); | |
| 169 | + let repo_id = repo.id.clone(); | |
| 170 | + let run_id = run.id.clone(); | |
| 171 | + async move { | |
| 172 | + if !readable(&store, actor.as_ref(), &repo_id).await { | |
| 173 | + return Ok(None); | |
| 174 | + } | |
| 175 | + let Some(run) = store.run_by_id(&run_id).await? else { | |
| 176 | + return Ok(None); | |
| 177 | + }; | |
| 178 | + let value = run_json(&store, &run).await?; | |
| 179 | + Ok(Some((value.to_string(), run.state.is_terminal()))) | |
| 180 | + } | |
| 181 | + }); | |
| 182 | + events_response(cx, events) | |
| 183 | +} |
crates/forge-web-app/src/api/mod.rsmodified+2 -0
| @@ -1,7 +1,9 @@ | ||
| 1 | +pub mod ci; | |
| 1 | 2 | pub mod gitea; |
| 2 | 3 | pub mod packages; |
| 3 | 4 | pub mod releases; |
| 4 | 5 | pub mod statuses; |
| 6 | +pub mod tags; | |
| 5 | 7 | |
| 6 | 8 | use std::net::IpAddr; |
| 7 | 9 | use std::path::PathBuf; |
crates/forge-web-app/src/api/releases.rsmodified+31 -0
| @@ -876,4 +876,35 @@ mod tests { | ||
| 876 | 876 | assert_eq!(status, 200); |
| 877 | 877 | assert_eq!(one["draft"], true); |
| 878 | 878 | } |
| 879 | + | |
| 880 | + #[tokio::test] | |
| 881 | + async fn tags_are_created_once_by_writers_and_listed() { | |
| 882 | + let f = fixture(None).await; | |
| 883 | + let uri = format!("/api/v1/repos/{OWNER}/{REPO}/tags"); | |
| 884 | + let body = br#"{"tag_name": "v0.5.0"}"#.to_vec(); | |
| 885 | + let reader = bearer(&f.reader_token); | |
| 886 | + let owner = bearer(&f.owner_token); | |
| 887 | + let json = Some("application/json"); | |
| 888 | + let (status, _) = send(&f.router, "POST", &uri, Some(&reader), json, body.clone()).await; | |
| 889 | + assert_eq!(status, 403); | |
| 890 | + let (status, created) = | |
| 891 | + send(&f.router, "POST", &uri, Some(&owner), json, body.clone()).await; | |
| 892 | + assert_eq!(status, 201, "{created}"); | |
| 893 | + assert_eq!(created["name"], "v0.5.0"); | |
| 894 | + assert_eq!(created["sha"].as_str().map(str::len), Some(40)); | |
| 895 | + let (status, _) = send(&f.router, "POST", &uri, Some(&owner), json, body).await; | |
| 896 | + assert_eq!(status, 409); | |
| 897 | + let (status, list) = send( | |
| 898 | + &f.router, | |
| 899 | + "GET", | |
| 900 | + &format!("{uri}?limit=5"), | |
| 901 | + None, | |
| 902 | + None, | |
| 903 | + Vec::new(), | |
| 904 | + ) | |
| 905 | + .await; | |
| 906 | + assert_eq!(status, 200); | |
| 907 | + assert_eq!(list[0]["name"], "v0.5.0"); | |
| 908 | + assert_eq!(list[0]["sha"], created["sha"]); | |
| 909 | + } | |
| 879 | 910 | } |
crates/forge-web-app/src/api/tags.rsadded+85 -0
| @@ -0,0 +1,85 @@ | ||
| 1 | +use forge_core::Action; | |
| 2 | +use serde::Deserialize; | |
| 3 | +use serde_json::json; | |
| 4 | +use topcoat::context::{Cx, context}; | |
| 5 | +use topcoat::router::request::headers; | |
| 6 | +use topcoat::router::response::Response; | |
| 7 | +use topcoat::router::{Body, StatusCode, path_param, route}; | |
| 8 | + | |
| 9 | +use crate::api::{self, Refusal}; | |
| 10 | +use crate::client_ip::client_ip; | |
| 11 | +use crate::release_ops::{self, ReleaseError}; | |
| 12 | +use crate::state::AppState; | |
| 13 | +use crate::views::query_value; | |
| 14 | + | |
| 15 | +path_param!(owner); | |
| 16 | +path_param!(repo); | |
| 17 | + | |
| 18 | +const MAX_JSON_BYTES: usize = 4 * 1024; | |
| 19 | +const DEFAULT_LIMIT: usize = 30; | |
| 20 | +const MAX_LIMIT: usize = 100; | |
| 21 | + | |
| 22 | +#[derive(Deserialize)] | |
| 23 | +struct CreateBody { | |
| 24 | + tag_name: String, | |
| 25 | + #[serde(default)] | |
| 26 | + target: Option<String>, | |
| 27 | +} | |
| 28 | + | |
| 29 | +fn failure(e: ReleaseError) -> Refusal { | |
| 30 | + match e { | |
| 31 | + ReleaseError::Internal(cause) => api::internal(cause), | |
| 32 | + other => Box::new(api::error(other.status(), &other.message())), | |
| 33 | + } | |
| 34 | +} | |
| 35 | + | |
| 36 | +#[route(POST "/api/v1/repos/{owner}/{repo}/tags")] | |
| 37 | +async fn create_tag(cx: &Cx, body: Body) -> topcoat::Result<Response> { | |
| 38 | + let state = context::<AppState>(cx); | |
| 39 | + let result = async { | |
| 40 | + let (repo, user) = | |
| 41 | + api::load_writer(state, client_ip(cx), headers(cx), owner(cx), repo(cx)).await?; | |
| 42 | + let input: CreateBody = api::json_body(body, MAX_JSON_BYTES).await?; | |
| 43 | + let sha = release_ops::create_tag( | |
| 44 | + state, | |
| 45 | + &repo, | |
| 46 | + &user, | |
| 47 | + &input.tag_name, | |
| 48 | + input.target.as_deref(), | |
| 49 | + ) | |
| 50 | + .await | |
| 51 | + .map_err(failure)?; | |
| 52 | + Ok::<_, Refusal>(json!({ "name": input.tag_name, "sha": sha })) | |
| 53 | + } | |
| 54 | + .await; | |
| 55 | + Ok(match result { | |
| 56 | + Ok(value) => api::json(StatusCode::CREATED, &value), | |
| 57 | + Err(res) => *res, | |
| 58 | + }) | |
| 59 | +} | |
| 60 | + | |
| 61 | +#[route(GET "/api/v1/repos/{owner}/{repo}/tags")] | |
| 62 | +async fn list_tags(cx: &Cx) -> topcoat::Result<Response> { | |
| 63 | + let state = context::<AppState>(cx); | |
| 64 | + let result = async { | |
| 65 | + let actor = api::authenticate(state, client_ip(cx), headers(cx)).await?; | |
| 66 | + let repo = api::load_repo(state, actor.as_ref(), owner(cx), repo(cx), Action::Read).await?; | |
| 67 | + let limit = query_value(cx, "limit") | |
| 68 | + .and_then(|raw| raw.parse::<usize>().ok()) | |
| 69 | + .unwrap_or(DEFAULT_LIMIT) | |
| 70 | + .clamp(1, MAX_LIMIT); | |
| 71 | + let tags = release_ops::list_tags(state, &repo, limit) | |
| 72 | + .await | |
| 73 | + .map_err(failure)?; | |
| 74 | + let tags: Vec<_> = tags | |
| 75 | + .iter() | |
| 76 | + .map(|t| json!({ "name": t.name, "sha": t.target })) | |
| 77 | + .collect(); | |
| 78 | + Ok::<_, Refusal>(tags) | |
| 79 | + } | |
| 80 | + .await; | |
| 81 | + Ok(match result { | |
| 82 | + Ok(value) => api::json(StatusCode::OK, &value), | |
| 83 | + Err(res) => *res, | |
| 84 | + }) | |
| 85 | +} |
crates/forge-web-app/src/ci/api_tests.rsmodified+48 -0
| @@ -1469,3 +1469,51 @@ async fn a_stopped_runner_is_offline_until_it_calls_again_and_can_remove_itself( | ||
| 1469 | 1469 | .await; |
| 1470 | 1470 | assert_eq!(sent.status, 401); |
| 1471 | 1471 | } |
| 1472 | + | |
| 1473 | +#[tokio::test] | |
| 1474 | +async fn public_ci_api_lists_runs_and_streams_the_run() { | |
| 1475 | + let env = bare(|_| {}).await; | |
| 1476 | + let run = make_run(&env, "push", None, COMMIT, &[job("build", spec(&[], &[]))]).await; | |
| 1477 | + let base = format!("/api/v1/repos/{OWNER}/{REPO}/ci/runs"); | |
| 1478 | + | |
| 1479 | + let list = send( | |
| 1480 | + &env.router, | |
| 1481 | + "GET", | |
| 1482 | + &format!("{base}?ref=main&limit=5"), | |
| 1483 | + &[], | |
| 1484 | + Vec::new(), | |
| 1485 | + ) | |
| 1486 | + .await; | |
| 1487 | + assert_eq!(list.status, 200); | |
| 1488 | + let list = list.json(); | |
| 1489 | + assert_eq!(list[0]["number"], run.number); | |
| 1490 | + assert_eq!(list[0]["jobs"][0]["name"], "build"); | |
| 1491 | + assert_eq!(list[0]["jobs"][0]["state"], "queued"); | |
| 1492 | + | |
| 1493 | + let one = send( | |
| 1494 | + &env.router, | |
| 1495 | + "GET", | |
| 1496 | + &format!("{base}/{}", run.number), | |
| 1497 | + &[], | |
| 1498 | + Vec::new(), | |
| 1499 | + ) | |
| 1500 | + .await; | |
| 1501 | + assert_eq!(one.status, 200); | |
| 1502 | + assert_eq!(one.json()["sha"], COMMIT); | |
| 1503 | + let missing = send(&env.router, "GET", &format!("{base}/99"), &[], Vec::new()).await; | |
| 1504 | + assert_eq!(missing.status, 404); | |
| 1505 | + | |
| 1506 | + let request = topcoat::router::request::Request::builder() | |
| 1507 | + .uri(format!("{base}/{}/events", run.number)) | |
| 1508 | + .body(topcoat::router::Body::empty()) | |
| 1509 | + .unwrap(); | |
| 1510 | + let res = env.router.handle(request).await; | |
| 1511 | + assert_eq!(res.status().as_u16(), 200); | |
| 1512 | + let mut frames = std::pin::pin!(res.into_body().into_data_stream()); | |
| 1513 | + let first = crate::test_support::fixture::next_event(&mut frames) | |
| 1514 | + .await | |
| 1515 | + .unwrap(); | |
| 1516 | + let text = String::from_utf8(first).unwrap(); | |
| 1517 | + assert!(text.starts_with("event: run\n"), "{text}"); | |
| 1518 | + assert!(text.contains("\"state\":\"queued\""), "{text}"); | |
| 1519 | +} |
crates/forge-web-app/src/release_ops.rsmodified+49 -11
| @@ -234,17 +234,7 @@ pub async fn create( | ||
| 234 | 234 | let refs = refs_of(path.clone()).await?; |
| 235 | 235 | let target_oid = match tag_oid(&refs, &input.tag) { |
| 236 | 236 | Some(oid) => oid, |
| 237 | - None => { | |
| 238 | - let target = input | |
| 239 | - .target | |
| 240 | - .as_deref() | |
| 241 | - .filter(|t| !t.is_empty()) | |
| 242 | - .unwrap_or(&repo.default_branch); | |
| 243 | - let oid = resolve_target(&path, &refs, target).await?; | |
| 244 | - create_lightweight_tag(&state.git, &path, &input.tag, &oid).await?; | |
| 245 | - fire_tag_hook(state, repo, actor, &input.tag, &zero_oid(&oid), &oid).await; | |
| 246 | - oid | |
| 247 | - } | |
| 237 | + None => create_tag(state, repo, actor, &input.tag, input.target.as_deref()).await?, | |
| 248 | 238 | }; |
| 249 | 239 | let created = state |
| 250 | 240 | .store |
| @@ -266,6 +256,54 @@ pub async fn create( | ||
| 266 | 256 | Ok(created) |
| 267 | 257 | } |
| 268 | 258 | |
| 259 | +pub async fn create_tag( | |
| 260 | + state: &AppState, | |
| 261 | + repo: &Repo, | |
| 262 | + actor: &User, | |
| 263 | + tag: &str, | |
| 264 | + target: Option<&str>, | |
| 265 | +) -> Result<String, ReleaseError> { | |
| 266 | + check_tag_name(tag)?; | |
| 267 | + let path = path_of(state, repo)?; | |
| 268 | + let refs = refs_of(path.clone()).await?; | |
| 269 | + if tag_oid(&refs, tag).is_some() { | |
| 270 | + return Err(ReleaseError::Conflict("the tag already exists".to_owned())); | |
| 271 | + } | |
| 272 | + let target = target | |
| 273 | + .filter(|t| !t.is_empty()) | |
| 274 | + .unwrap_or(&repo.default_branch); | |
| 275 | + let oid = resolve_target(&path, &refs, target).await?; | |
| 276 | + if let Err(e) = create_lightweight_tag(&state.git, &path, tag, &oid).await { | |
| 277 | + return Err(match e { | |
| 278 | + forge_git::Error::Failed(_) => { | |
| 279 | + ReleaseError::Conflict("the tag already exists".to_owned()) | |
| 280 | + } | |
| 281 | + other => other.into(), | |
| 282 | + }); | |
| 283 | + } | |
| 284 | + fire_tag_hook(state, repo, actor, tag, &zero_oid(&oid), &oid).await; | |
| 285 | + Ok(oid) | |
| 286 | +} | |
| 287 | + | |
| 288 | +pub async fn list_tags( | |
| 289 | + state: &AppState, | |
| 290 | + repo: &Repo, | |
| 291 | + limit: usize, | |
| 292 | +) -> Result<Vec<RefInfo>, ReleaseError> { | |
| 293 | + let mut tags: Vec<RefInfo> = refs_of(path_of(state, repo)?) | |
| 294 | + .await? | |
| 295 | + .into_iter() | |
| 296 | + .filter(|r| r.kind == RefKind::Tag) | |
| 297 | + .collect(); | |
| 298 | + tags.sort_by(|a, b| { | |
| 299 | + b.committer_time | |
| 300 | + .cmp(&a.committer_time) | |
| 301 | + .then_with(|| b.name.cmp(&a.name)) | |
| 302 | + }); | |
| 303 | + tags.truncate(limit); | |
| 304 | + Ok(tags) | |
| 305 | +} | |
| 306 | + | |
| 269 | 307 | pub async fn update( |
| 270 | 308 | state: &AppState, |
| 271 | 309 | repo: &Repo, |
crates/forge-web-pages/src/pages/ci_job.rsmodified+7 -8
| @@ -348,7 +348,7 @@ pub fn job_status(job: &CiJob) -> &'static str { | ||
| 348 | 348 | } |
| 349 | 349 | } |
| 350 | 350 | |
| 351 | -async fn job_fingerprint_now(store: &Store, job_id: &str) -> Result<Option<String>> { | |
| 351 | +async fn job_fingerprint_now(store: &Store, job_id: &str) -> Result<Option<(String, bool)>> { | |
| 352 | 352 | let Some(job) = store.job_by_id(job_id).await? else { |
| 353 | 353 | return Ok(None); |
| 354 | 354 | }; |
| @@ -357,10 +357,9 @@ async fn job_fingerprint_now(store: &Store, job_id: &str) -> Result<Option<Strin | ||
| 357 | 357 | .iter() |
| 358 | 358 | .map(|artifact| artifact.id.as_str()) |
| 359 | 359 | .collect(); |
| 360 | - Ok(Some(job_fingerprint( | |
| 361 | - job_status(&job), | |
| 362 | - &ids, | |
| 363 | - job.log_bytes > 0, | |
| 360 | + Ok(Some(( | |
| 361 | + job_fingerprint(job_status(&job), &ids, job.log_bytes > 0), | |
| 362 | + job.state.is_terminal(), | |
| 364 | 363 | ))) |
| 365 | 364 | } |
| 366 | 365 | |
| @@ -639,8 +638,8 @@ fn job_stream(follow: JobFollow) -> impl Stream<Item = Result<Event>> + Send + ' | ||
| 639 | 638 | } |
| 640 | 639 | f.primed = true; |
| 641 | 640 | f.more = false; |
| 642 | - let fingerprint = match job_fingerprint_now(&f.store, &f.job_id).await { | |
| 643 | - Ok(Some(fingerprint)) => fingerprint, | |
| 641 | + let (fingerprint, finished) = match job_fingerprint_now(&f.store, &f.job_id).await { | |
| 642 | + Ok(Some(found)) => found, | |
| 644 | 643 | Ok(None) => return None, |
| 645 | 644 | Err(e) => { |
| 646 | 645 | tracing::error!(error = %e, "ci: job stream could not read the job"); |
| @@ -651,7 +650,7 @@ fn job_stream(follow: JobFollow) -> impl Stream<Item = Result<Event>> + Send + ' | ||
| 651 | 650 | f.fingerprint = Some(fingerprint.clone()); |
| 652 | 651 | f.pending_fingerprint = Some(fingerprint); |
| 653 | 652 | } |
| 654 | - match read_log(&f.path, f.offset, f.plain).await { | |
| 653 | + match read_log(&f.path, f.offset, f.plain && !finished).await { | |
| 655 | 654 | Ok(Some((text, end))) => { |
| 656 | 655 | f.offset = end; |
| 657 | 656 | f.more = true; |
crates/forge-web/src/routes.snapmodified+5 -0
| @@ -248,6 +248,9 @@ route /api/v1/ci/runners/register Only([POST]) | ||
| 248 | 248 | route /api/v1/ci/runners/self Only([DELETE]) |
| 249 | 249 | route /api/v1/ci/runners/stopped Only([POST]) |
| 250 | 250 | route /api/v1/repos/{owner}/{repo} Only([GET]) |
| 251 | +route /api/v1/repos/{owner}/{repo}/ci/runs Only([GET]) | |
| 252 | +route /api/v1/repos/{owner}/{repo}/ci/runs/{run_number} Only([GET]) | |
| 253 | +route /api/v1/repos/{owner}/{repo}/ci/runs/{run_number}/events Only([GET]) | |
| 251 | 254 | route /api/v1/repos/{owner}/{repo}/commits/{sha}/statuses Only([GET]) |
| 252 | 255 | route /api/v1/repos/{owner}/{repo}/issues Only([GET]) |
| 253 | 256 | route /api/v1/repos/{owner}/{repo}/issues/comments/{id}/reactions Only([GET]) |
| @@ -267,6 +270,8 @@ route /api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset} Only([DELETE]) | ||
| 267 | 270 | route /api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset} Only([GET]) |
| 268 | 271 | route /api/v1/repos/{owner}/{repo}/releases/{id}/assets/{asset} Only([PUT]) |
| 269 | 272 | route /api/v1/repos/{owner}/{repo}/statuses/{sha} Only([POST]) |
| 273 | +route /api/v1/repos/{owner}/{repo}/tags Only([GET]) | |
| 274 | +route /api/v1/repos/{owner}/{repo}/tags Only([POST]) | |
| 270 | 275 | route /api/v1/repos/{owner}/{repo}/topics Only([GET]) |
| 271 | 276 | route /api/v1/settings/api Only([GET]) |
| 272 | 277 | route /api/v1/version Only([GET]) |
docs/api.mdmodified+76 -0
| @@ -315,6 +315,82 @@ If the job runs on the tag itself, the tag already exists and `target` is ignore | ||
| 315 | 315 | alternative needs no script at all: a `[release]` table in `ci.toml` publishes the release from |
| 316 | 316 | a tag run and attaches the selected artifacts. See `docs/ci.md`, "Releases". |
| 317 | 317 | |
| 318 | +## Tags | |
| 319 | + | |
| 320 | +``` | |
| 321 | +POST /api/v1/repos/{owner}/{repo}/tags {"tag_name": "v0.5.0", "target": "main"} | |
| 322 | +GET /api/v1/repos/{owner}/{repo}/tags?limit=<n> | |
| 323 | +``` | |
| 324 | + | |
| 325 | +Creating needs write access: a token with `repo` scope from a user who can push. `target` is a | |
| 326 | +branch name or a full commit sha and defaults to the default branch. The tag is lightweight. The | |
| 327 | +answer is `201 {"name": "v0.5.0", "sha": "<commit>"}`, `409` when the tag exists, `422` for a bad | |
| 328 | +name or target. A tag made here runs the same post-update path as a `git push` of the tag, so CI | |
| 329 | +`[on] tags`, `[release]`, webhooks and push mirrors all fire. | |
| 330 | + | |
| 331 | +The list needs read access, is newest commit first, and gives `[{"name", "sha"}]`. `limit` | |
| 332 | +defaults to 30, at most 100. | |
| 333 | + | |
| 334 | +## CI runs | |
| 335 | + | |
| 336 | +Read-only. The same read access as the run page: anonymous on a public repository, a token with | |
| 337 | +`repo` scope otherwise. | |
| 338 | + | |
| 339 | +``` | |
| 340 | +GET /api/v1/repos/{owner}/{repo}/ci/runs?ref=<ref>&limit=<n> | |
| 341 | +GET /api/v1/repos/{owner}/{repo}/ci/runs/{run_number} | |
| 342 | +GET /api/v1/repos/{owner}/{repo}/ci/runs/{run_number}/events | |
| 343 | +``` | |
| 344 | + | |
| 345 | +The list is newest first. `ref` is optional and matches a full ref (`refs/tags/v1.2.0`) or a short | |
| 346 | +branch or tag name (`v1.2.0`). `limit` defaults to 20, at most 100. | |
| 347 | + | |
| 348 | +A run: | |
| 349 | + | |
| 350 | +```json | |
| 351 | +{ | |
| 352 | + "number": 42, | |
| 353 | + "ref": "refs/tags/v1.2.0", | |
| 354 | + "sha": "4f1c…", | |
| 355 | + "trigger": "push", | |
| 356 | + "state": "running", | |
| 357 | + "created_at": "2026-12-01T19:00:00Z", | |
| 358 | + "started_at": "2026-12-01T19:00:04Z", | |
| 359 | + "finished_at": null, | |
| 360 | + "jobs": [ | |
| 361 | + { | |
| 362 | + "id": "01k…", | |
| 363 | + "name": "build (x86_64-v3-linux)", | |
| 364 | + "state": "running", | |
| 365 | + "started_at": "2026-12-01T19:00:04Z", | |
| 366 | + "finished_at": null, | |
| 367 | + "exit_code": null, | |
| 368 | + "steps": [ | |
| 369 | + { "name": "fetch", "state": "success", "started_at": "…", "finished_at": "…" }, | |
| 370 | + { "name": "build", "state": "running", "started_at": "…", "finished_at": null } | |
| 371 | + ] | |
| 372 | + } | |
| 373 | + ] | |
| 374 | +} | |
| 375 | +``` | |
| 376 | + | |
| 377 | +Run states: `waiting_approval`, `queued`, `running`, `success`, `failure`, `cancelled`, `error`. | |
| 378 | +Job states: `blocked` (waiting on `needs`), `queued`, `running`, `success`, `failure`, `cancelled`, | |
| 379 | +`error`, `skipped`. Step states: `running`, `success`, `failure`, `cancelled`. Steps come from `::group::` | |
| 380 | +markers in the job log. `started_at` of the run is its first job's start. | |
| 381 | + | |
| 382 | +`events` is a server-sent event stream. It sends `event: run` with the whole run JSON on connect and | |
| 383 | +again whenever it changes, and ends after the run reaches a finished state. Close it then: a | |
| 384 | +browser `EventSource` would otherwise reconnect and get the final state again. | |
| 385 | + | |
| 386 | +A job's log streams from `GET /{owner}/{repo}/ci/jobs/{job_id}/events?plain=1`, with the same access | |
| 387 | +rules. `event: log` carries whole lines of plain text (ANSI codes stripped); its `id` is the byte | |
| 388 | +offset after the chunk, so reconnecting with `Last-Event-ID` (or `?from=<offset>`) resumes without | |
| 389 | +gaps or repeats. `event: changed` tells a browser to re-render the page and can be ignored by an API | |
| 390 | +client: job state comes from the run stream. The stream stays open after the job ends; close it | |
| 391 | +when the run JSON shows the job finished. `GET /{owner}/{repo}/ci/jobs/{job_id}/log.txt` returns the | |
| 392 | +whole log at once. | |
| 393 | + | |
| 318 | 394 | ## Moving to Forgejo or Gitea |
| 319 | 395 | |
| 320 | 396 | Forgejo and Gitea can pull a repo out of forge with its issues, comments, pull requests, reviews, |