Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
167 changes: 167 additions & 0 deletions app/src/forge/checks.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
//! A build's check on its forge (sc-8900, the forge side), ported from today's `workers::forge_check`: a GitHub check
//! run or a GitLab commit status per suite. It stays in progress while changes wait for review (a required check
//! blocks the merge) and completes when the build is approved, rejected or unchanged.
//!
//! `BuildChanged` queues [`ReportCheck`]. Dispatches for the same build within a few seconds are one post (the jobs
//! are debounced), so a build whose snapshots are reviewed one by one doesn't post once for each.

use laravel::queue::{Attempt, Queueable, job};

use super::report::{self, Check, RateLimited};
use crate::domain::build_settings::BuildSettings;
use crate::domain::builds::stats;
use crate::models::{Build, Organization, Project};

/// The check's name for a suite: "VisualCI" for the default build name, "VisualCI: pdf" for `--name pdf`. A
/// repository with several suites gets one check each, which branch protection can require by name.
#[must_use]
pub fn check_name(build_name: &str) -> String {
if build_name == "default" { "VisualCI".to_string() } else { format!("VisualCI: {build_name}") }
}

/// How to review a build whose check is waiting: over MCP for an agent, on the build's page for a person.
#[must_use]
pub fn review_hint(org: &str, project: &str, number: i32) -> String {
format!(
"**To review:** an agent with VisualCI's MCP server calls `get_build` (project `{org}/{project}`, build {number}), \
opens each change with `get_snapshot`, and approves the changes that were meant with `review`; for a change \
that wasn't, it fixes the code and pushes again. A person reviews on the build's page. This check turns green \
once the changes are approved."
)
}

/// The check's status, conclusion and title for a build. `superseded_by` is the number of the build whose review
/// covered this one's changes.
#[must_use]
pub fn check_state(build: &Build, project: &Project, superseded_by: Option<i32>) -> (String, Option<String>, String) {
let stats = stats(build);
let changes = stats.changes();
let done = |c: &str, t: String| ("completed".to_string(), Some(c.to_string()), t);
match (build.state.as_str(), build.conclusion.as_deref(), build.review_state.as_str()) {
// A build that failed as a whole (abandoned, out of credits, nothing sent) says why in its first sentence
("failed", _, _) | (_, Some("failed"), _) if stats.failed == 0 && build.error.is_some() => {
let why = build.error.as_deref().and_then(|e| e.split(", so ").next()).unwrap_or("Build failed");
done("failure", why.chars().take(120).collect())
}
("failed", _, _) | (_, Some("failed"), _) => {
let n = stats.failed.max(1);
done("failure", format!("{n} {} failed", if n == 1 { "snapshot" } else { "snapshots" }))
}
("completed", Some("unchanged"), _) => done("success", format!("{} snapshots unchanged", stats.total)),
("completed", _, "approved" | "auto_approved") => done("success", format!("{changes} changes approved")),
("completed", _, "rejected") => done("failure", format!("{changes} changes rejected")),
// A later build's review covered this one's changes
("completed", _, "superseded") => {
done("neutral", superseded_by.map_or_else(|| "Superseded".to_string(), |n| format!("Superseded by #{n}")))
}
// Its pull request was closed without merging, or its branch deleted
("completed", _, "closed") => done("neutral", "Closed without review".to_string()),
("completed", _, _) if build.mode == "local" => done("neutral", format!("{changes} changes (local run)")),
("completed", _, _) if BuildSettings::new(project, build).ci_mode() == "strict" => {
done("failure", format!("{changes} changes to review"))
}
("completed", _, _) => ("in_progress".to_string(), None, format!("{changes} changes waiting for review")),
_ => ("in_progress".to_string(), None, "Processing".to_string()),
}
}

/// The whole check for a CI build: its state, the counts, who reviewed it, what changed, and how to review it.
///
/// # Errors
/// On a database error.
pub async fn check_for(build: &Build, project: &Project, org: &Organization) -> laravel::Result<Check> {
let superseded_by = match build.superseded_by_build_id {
Some(id) => Build::find(id).await?.map(|b| b.number),
None => None,
};
let (status, conclusion, title) = check_state(build, project, superseded_by);
let stats = stats(build);
let url = crate::http::api::builds::BuildResponse::new(build, project, org).url;
let mut summary = format!(
"{} unchanged, {} changed, {} added, {} removed, {} ignored, {} failed.\n\n[Review build #{}]({url})",
stats.unchanged, stats.changed, stats.added, stats.removed, stats.ignored, stats.failed, build.number
);
// Who reviewed it: an agent for its person reads as the agent, never as the person's own review
if let Some(r) = crate::domain::reviews::shown(build.id, 1).await?.into_iter().next() {
let mut line = r.line();
if let Some(c) = line.get_mut(..1) {
c.make_ascii_uppercase();
}
summary.push_str(&format!("\n\n{line}."));
if let Some(note) = &r.note {
summary.push_str(&format!(" {note}"));
}
}
// What changed, from the comparison
if let Some(line) = crate::domain::summary::summary_line(build).await? {
summary = format!("{line}\n\n{summary}");
}
if status == "in_progress" && build.state == "completed" {
summary = format!("{summary}\n\n{}", review_hint(&org.slug, &project.slug, build.number));
}
Ok(Check {
name: check_name(&build.name),
head_sha: build.commit_sha.clone(),
status,
conclusion,
details_url: url,
title,
summary,
})
}

/// The advisory lock namespace for posting a build's check ("VCI2").
const LOCKS: i32 = 1_447_249_202;

/// Post a CI build's check to its project's forge, and remember the check's ID for the next update.
#[derive(Queueable)]
pub struct ReportCheck {
pub build_id: i64,
}

#[job(
name = "forge.check",
tries = 5,
backoff = [10.seconds(), 1.minutes(), 5.minutes()],
debounce_for = 3.seconds(),
max_wait = 30.seconds()
)]
impl ReportCheck {
async fn handle(self, attempt: &Attempt) -> laravel::Result<()> {
let build_id = self.build_id;
// One post at a time per build, from the build as it is once the lock is held: a slow post can't land after
// a newer one and leave the forge showing an older state
let posted = laravel::db::transaction(async |_| {
laravel::db::query!("SELECT pg_advisory_xact_lock({LOCKS}, ({build_id} % 2147483647)::int)")
.select()
.await?;
let Some(build) = Build::find(build_id).await? else { return Ok(()) };
if build.mode != "ci" {
return Ok(());
}
let project = Project::find_or_fail(build.project_id).await?;
let Some((target, repository)) = report::target(&project).await? else { return Ok(()) };
let org = Organization::find_or_fail(project.organization_id).await?;
let check = check_for(&build, &project, &org).await?;
let id = report::report_check(&target, &repository, build.forge_check_id.as_deref(), &check).await?;
if build.forge_check_id.as_deref() != Some(id.as_str()) {
laravel::db::query!("UPDATE builds SET forge_check_id = {id} WHERE id = {build_id}").update().await?;
}
Ok(())
})
.await;
match posted {
Err(e) if e.downcast_ref::<RateLimited>().is_some() => {
let wait = e.downcast_ref::<RateLimited>().map(|r| r.retry_in).unwrap_or_default();
tracing::warn!(build_id, error = %e, "the forge's rate limit: posting the check later");
attempt.release(wait);
Ok(())
}
other => other,
}
}

fn debounce_id(&self) -> i64 {
self.build_id
}
}
20 changes: 20 additions & 0 deletions app/src/forge/github_app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,26 @@ pub async fn installation_exists(app: &GithubApp, id: &str) -> laravel::Result<b
Ok(get(&app_jwt(app)?, &format!("/app/installations/{id}")).await?.is_some())
}

/// Where people install the App on their repositories.
pub const INSTALL_URL: &str = "https://github.com/apps/visualci-com/installations/new";

/// The App's installation that reaches a repository (`owner/name`), if it's installed there.
///
/// # Errors
/// When the App isn't configured, or GitHub can't be reached or refuses.
pub async fn installation_for(app: &GithubApp, repo: &str) -> laravel::Result<Option<String>> {
Ok(get(&app_jwt(app)?, &format!("/repos/{repo}/installation"))
.await?
.and_then(|v| v["id"].as_i64())
.map(|i| i.to_string()))
}

/// Whether the App is configured (its ID and private key).
#[must_use]
pub fn configured(app: &GithubApp) -> bool {
app.app_id.is_some() && app.private_key_base64.is_some()
}

/// Below this many API calls left in the hour, a recheck stops instead of using up what webhooks and checks need.
pub const RATE_LIMIT_RESERVE: i64 = 500;

Expand Down
77 changes: 77 additions & 0 deletions app/src/forge/gitlab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,3 +156,80 @@ fn level_of(project: &Value) -> i64 {
.max()
.unwrap_or(0)
}

/// VisualCI's bot user on the GitLab of [`GitlabConfig`] (`VISUALCI_GITLAB_BOT_TOKEN`, a personal access token with
/// the `api` scope). GitLab has no app installations: a project gives VisualCI access by adding the bot as a member,
/// and every server-side call about it (access checks, commit statuses, merge request notes) uses the bot's token.
#[derive(Clone, laravel::config::Section)]
pub struct GitlabBot {
#[env("VISUALCI_GITLAB_BOT_TOKEN")]
pub token: Option<String>,
/// The bot's username, for telling people whom to invite.
#[env("VISUALCI_GITLAB_BOT_USERNAME", default = "visualci")]
pub username: String,
}

/// The `installation` of a project VisualCI reaches through its bot.
pub const BOT: &str = "bot";

/// A project's ID for the API: its path, URL-encoded (`group%2Fsub%2Fproject`).
fn project_id(path: &str) -> String {
url::form_urlencoded::byte_serialize(path.as_bytes()).collect()
}

/// GET an API path (`/projects/...`) as JSON; `None` on 404.
async fn get(base: &str, token: &str, path: &str) -> laravel::Result<Option<Value>> {
let base = base.trim_end_matches('/');
let response = client::get(format!("{base}/api/v4{path}")).token(token).accept_json().await?;
if response.status() == 404 {
return Ok(None);
}
if !response.successful() {
return Err(laravel::Error::msg(format!("GitLab GET {path}: HTTP {}", response.status())));
}
Ok(Some(response.json()?))
}

/// The bot's access level on a project (`group/sub/project`), when it's a member.
///
/// # Errors
/// When GitLab can't be reached or refuses the bot's token.
pub async fn bot_level(base: &str, token: &str, path: &str) -> laravel::Result<Option<i64>> {
Ok(get(base, token, &format!("/projects/{}", project_id(path))).await?.map(|p| level_of(&p)).filter(|l| *l > 0))
}

/// The bot's access to a project as an installation: a Developer or higher can post statuses and notes.
///
/// # Errors
/// When GitLab can't be reached or refuses the bot's token.
pub async fn installation_for(base: &str, token: &str, path: &str) -> laravel::Result<Option<String>> {
Ok(bot_level(base, token, path).await?.filter(|l| *l >= 30).map(|_| BOT.to_string()))
}

/// A person's permission on a project, inherited access included, by their permanent GitLab user ID.
///
/// # Errors
/// When GitLab can't be reached or refuses the token.
pub async fn permission(base: &str, token: &str, path: &str, user_id: &str) -> laravel::Result<Option<Permission>> {
let Ok(user_id) = user_id.parse::<i64>() else { return Ok(None) };
let member = get(base, token, &format!("/projects/{}/members/all/{user_id}", project_id(path))).await?;
Ok(member.and_then(|m| m["access_level"].as_i64()).and_then(permission_from_level))
}

/// A project's permanent ID (`None` when the token can't see it).
///
/// # Errors
/// When GitLab can't be reached or refuses the token.
pub async fn repository_id(base: &str, token: &str, path: &str) -> laravel::Result<Option<String>> {
Ok(get(base, token, &format!("/projects/{}", project_id(path)))
.await?
.and_then(|p| p["id"].as_i64())
.map(|i| i.to_string()))
}

/// How a project gives VisualCI access: invite the bot as a Developer.
#[must_use]
pub fn install_hint(base: &str, bot: &str, path: &str) -> String {
let base = base.trim_end_matches('/');
format!("invite @{bot} to {path} as a Developer ({base}/{path}/-/project_members), then link it")
}
Loading
Loading