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
49 changes: 49 additions & 0 deletions app/src/domain/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -966,6 +966,55 @@ pub async fn expire_abandoned(project_id: Option<i64>) -> laravel::Result<usize>
Ok(failed.len() + finished.len())
}

/// The error a build carries when the GitHub Actions run sending it ended without finalizing it. Its first clause,
/// up to ", so ", is the check's title.
#[must_use]
pub fn run_ended_error(conclusion: &str, run_url: &str) -> String {
let how = match conclusion {
"cancelled" => "was cancelled",
"timed_out" => "timed out",
_ => "failed",
};
format!(
"The CI run sending this build {how}, so VisualCI closed it before `visualci build finalize`: {run_url}. \
Re-run the job to send a new build."
)
}

/// Close the builds a GitHub Actions run was still sending when it ended without succeeding: CI builds of these
/// projects for `head_sha` that are still receiving and whose job link is that run (another workflow failing on the
/// same commit leaves them alone). They fail with [`run_ended_error`], as the sweep's abandoned builds do, and their
/// checks and pages follow. Returns how many it closed; safe to run twice.
///
/// # Errors
/// On a database or queue error.
pub async fn close_for_ended_run(
project_ids: &[i64],
head_sha: &str,
run_url: &str,
conclusion: &str,
) -> laravel::Result<usize> {
let error = run_ended_error(conclusion, run_url);
let (sha, url) = (head_sha.to_string(), run_url.trim_end_matches('/').to_lowercase());
let mut ids = Vec::new();
for &project_id in project_ids {
let rows = db::query!(
"UPDATE builds b SET state = 'failed', conclusion = 'failed', review_state = 'none', error = {error}, \
completed_at = now(), updated_at = now() \
WHERE b.project_id = {project_id} AND b.commit_sha = {sha} AND b.mode <> 'local' \
AND b.state = 'receiving' AND rtrim(lower(b.environment_info->>'job_url'), '/') = {url} \
RETURNING b.id"
)
.select()
.await?;
ids.extend(rows.iter().filter_map(|r| r.try_get::<i64>("id").ok()));
}
for id in &ids {
crate::events::BuildChanged { build_id: *id }.dispatch().await?;
}
Ok(ids.len())
}

/// Compare some of a build's snapshots now, before it's finalized: a local run checks each test's snapshots as the test
/// makes them. Snapshots whose files haven't arrived or whose PDFs are still rendering come back `pending`; ask again.
/// Finalizing compares everything again, so these results are never the final word.
Expand Down
32 changes: 31 additions & 1 deletion app/src/forge/webhooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
//! the domain as `forge::events`, once per linked project;
//! - installation changes attach or detach the App's installation on linked projects, so checks stop without errors,
//! and recheck the access of the people whose memberships those organizations' repositories decide;
//! - membership changes (collaborators, teams, organization members) recheck the people they name ([`RecheckAccess`]).
//! - membership changes (collaborators, teams, organization members) recheck the people they name ([`RecheckAccess`]);
//! - a GitHub Actions run that was cancelled, failed or timed out closes the builds it was still sending.
//!
//! Every event is safe to receive twice. GitLab's project hooks come with the self-managed instances' port.

Expand Down Expand Up @@ -63,6 +64,14 @@ pub enum ForgeEvent {
Moved {
repository: Repository,
},
/// A GitHub Actions run ended without succeeding (`cancelled`, `failure` or `timed_out`): builds it was still
/// sending are closed at once instead of after the hour the sweep waits.
RunEnded {
repository: Repository,
head_sha: String,
run_url: String,
conclusion: String,
},
Ignored,
}

Expand Down Expand Up @@ -194,6 +203,21 @@ pub fn read_event(kind: &str, event: &Value) -> Result<ForgeEvent, String> {
Some(installation) => ForgeEvent::AccessAll { installation },
None => ForgeEvent::Ignored,
},
// A workflow run that ended without succeeding: the builds it was still sending won't be finalized
("workflow_run", "completed") => {
let run = &event["workflow_run"];
match (repository(event), run["head_sha"].as_str(), run["html_url"].as_str(), run["conclusion"].as_str()) {
(Some(repository), Some(sha), Some(url), Some(c @ ("cancelled" | "failure" | "timed_out"))) => {
ForgeEvent::RunEnded {
repository,
head_sha: sha.to_string(),
run_url: url.to_string(),
conclusion: c.to_string(),
}
}
_ => ForgeEvent::Ignored,
}
}
_ => ForgeEvent::Ignored,
})
}
Expand Down Expand Up @@ -373,6 +397,12 @@ pub async fn handle(app: &GithubApp, event: ForgeEvent) -> laravel::Result<Value
recheck_organizations(orgs).await?;
json!({ "rechecking": "installation" })
}
ForgeEvent::RunEnded { repository, head_sha, run_url, conclusion } => {
let projects: Vec<i64> = linked(&repository).await?.iter().map(|p| p.id).collect();
let closed =
crate::domain::processing::close_for_ended_run(&projects, &head_sha, &run_url, &conclusion).await?;
json!({ "closed": closed })
}
ForgeEvent::Ignored => json!({ "ignored": true }),
})
}
Expand Down
62 changes: 62 additions & 0 deletions app/tests/webhooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,65 @@ async fn a_renamed_repository_moves_its_links_and_edits_say_whether_it_is_privat
assert_eq!(id.as_deref(), Some("77"));
Ok(())
}

/// A CI build of `project` for `commit`, still receiving, sent by the GitHub Actions run `run`.
async fn receiving(project_id: i64, commit: &str, run: u64) -> laravel::Result<i64> {
let project = app::models::Project::find_or_fail(project_id).await?;
let params: app::domain::builds::CreateParams = serde_json::from_value(json!({
"commit": commit, "branch": "feature", "mode": "ci",
"environment_info": { "provider": "github", "job_url": format!("https://github.com/acme/web/actions/runs/{run}") },
}))?;
let build = app::domain::builds::create(&project, &params, None)
.await
.map_err(|e| laravel::Error::msg(format!("{e:?}")))?;
Ok(build.id)
}

fn run_ended(commit: &str, run: u64, conclusion: &str) -> serde_json::Value {
json!({
"action": "completed", "repository": repository(),
"workflow_run": { "head_sha": commit, "conclusion": conclusion,
"html_url": format!("https://github.com/acme/web/actions/runs/{run}") },
})
}

#[laravel::test(app = github)]
async fn a_cancelled_or_failed_run_closes_the_builds_it_was_sending(app: Application) -> laravel::Result<()> {
let (_, project, _) = linked().await?;
let sending = receiving(project, "abc123", 9).await?;
let other_workflow = receiving(project, "abc123", 10).await?;
let finalized = receiving(project, "abc123", 9).await?;
db::query!("UPDATE builds SET state = 'processing', finalized_at = now() WHERE id = {finalized}").update().await?;
let timed_out = receiving(project, "def456", 11).await?;
// Closing a build posts its check and updates its pages (BuildChanged): faked here, there's no GitHub
let events = laravel::event::fake();

// A run that succeeded, or one still going, closes nothing
deliver(&app, "workflow_run", run_ended("abc123", 9, "success"))
.await
.assert_ok()
.assert_json_path("ignored", true);
let in_progress = json!({ "action": "in_progress", "repository": repository(),
"workflow_run": { "head_sha": "abc123", "html_url": "https://github.com/acme/web/actions/runs/9" } });
deliver(&app, "workflow_run", in_progress).await.assert_ok().assert_json_path("ignored", true);
assert_eq!(app::models::Build::find_or_fail(sending).await?.state, "receiving");

deliver(&app, "workflow_run", run_ended("abc123", 9, "cancelled")).await.assert_ok().assert_json_path("closed", 1);
let b = app::models::Build::find_or_fail(sending).await?;
assert_eq!((b.state.as_str(), b.conclusion.as_deref()), ("failed", Some("failed")));
let error = b.error.unwrap_or_default();
assert!(error.starts_with("The CI run sending this build was cancelled, so "), "{error}");
assert!(error.contains("https://github.com/acme/web/actions/runs/9"), "{error}");
// Another workflow's build on the same commit, and a build already finalized, are left alone
assert_eq!(app::models::Build::find_or_fail(other_workflow).await?.state, "receiving");
assert_eq!(app::models::Build::find_or_fail(finalized).await?.state, "processing");
// Delivered twice: nothing more to close
deliver(&app, "workflow_run", run_ended("abc123", 9, "cancelled")).await.assert_ok().assert_json_path("closed", 0);

deliver(&app, "workflow_run", run_ended("def456", 11, "timed_out")).await.assert_ok().assert_json_path("closed", 1);
let error = app::models::Build::find_or_fail(timed_out).await?.error.unwrap_or_default();
assert!(error.starts_with("The CI run sending this build timed out, so "), "{error}");
events.assert_dispatched_times::<app::events::BuildChanged>(2);
events.assert_dispatched_where::<app::events::BuildChanged>(|e| e.build_id == sending);
Ok(())
}
3 changes: 2 additions & 1 deletion docs/deploy.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,8 @@ GitLab is parked in app/: production sets none of its variables (`GITLAB_CLIENT_
- every five minutes, the builds sweep (`BUILDS_EXPIRE`, "VisualCI / Abandoned builds"): fails builds that received
nothing for an hour and concludes their checks, closes idle local builds and runs stuck ones again;
`oldest_receiving_seconds` on `/status` stays under two hours while it runs. A project's new build also expires
its own abandoned ones;
its own abandoned ones, and the GitHub App's `workflow_run` webhook closes a build at once when the GitHub Actions
run sending it (its `job_url`) is cancelled, fails or times out;
- hourly, the forge sync (`FORGE_SYNC`, "VisualCI / Forge access sync"): rechecks every GitHub-derived membership,
unlinks projects whose linker lost the repository and closes deleted branches; `oldest_forge_sync_seconds` on
`/status` also catches a person left unchecked;
Expand Down
Loading