| 1 | //! What starts a run: an event on the bus, a schedule, or someone running a |
| 2 | //! workflow by hand. Each finds the workflows that want it, at the commit |
| 3 | //! the event is about, and checks their filters. |
| 4 | |
| 5 | use g1t_actions::events::{RunInfo, github_events}; |
| 6 | use g1t_actions::workflow::{self, Trigger, Workflow}; |
| 7 | use g1t_contracts::access::{self, Capability}; |
| 8 | use g1t_contracts::actions::{DispatchArgs, RepositoryDispatchArgs, WorkflowRun}; |
| 9 | use g1t_contracts::events::{Event, caused_by_job}; |
| 10 | use g1t_contracts::identity::{AGENT_ID, AGENT_NAME, UsernamesArgs}; |
| 11 | use g1t_contracts::repos::{Commit, CompareArgs, Comparison, LogArgs, Repo, RepoPath}; |
| 12 | use g1t_contracts::work::{IssueDetail, PullDetail, ViewArgs}; |
| 13 | use g1t_contracts::{FailureCode, Outcome, User, new_id}; |
| 14 | use g1t_contracts::time::rfc3339; |
| 15 | use g1t_kit::now_ms; |
| 16 | use serde_json::{Map, Value, json}; |
| 17 | use worker::Result; |
| 18 | |
| 19 | use crate::plan::NewRun; |
| 20 | use crate::sync::{Read, WorkflowRow}; |
| 21 | use crate::{API, Actions, SITE, check, fail, payload}; |
| 22 | |
| 23 | /// What an event is about, worked out once for every workflow it starts. |
| 24 | struct Subject { |
| 25 | /// Where the workflow files are read, and at which commit. |
| 26 | source: RepoPath, |
| 27 | source_ref: Option<String>, |
| 28 | git_ref: String, |
| 29 | sha: String, |
| 30 | head_ref: Option<String>, |
| 31 | base_ref: Option<String>, |
| 32 | pull: Option<u32>, |
| 33 | /// The branch or tag for `branches`/`tags` filters; for pull requests, |
| 34 | /// the branch they merge into. |
| 35 | filter_ref: String, |
| 36 | /// The files it changes, for `paths` filters; `None` until needed. |
| 37 | paths: Option<Vec<String>>, |
| 38 | /// For a push, what to compare to find the files. |
| 39 | compare: Option<(Option<String>, String)>, |
| 40 | payload: Value, |
| 41 | title: String, |
| 42 | trusted: bool, |
| 43 | /// Why its runs wait for approval first: a pull request from outside, |
| 44 | /// by the repository's approval policy (protection.rs). |
| 45 | approval: Option<String>, |
| 46 | } |
| 47 | |
| 48 | /// Whether a deployment's `ref` is a commit's full hash rather than a |
| 49 | /// branch or tag. |
| 50 | fn is_commit(name: &str) -> bool { |
| 51 | name.len() == 40 && name.chars().all(|c| c.is_ascii_hexdigit()) |
| 52 | } |
| 53 | |
| 54 | /// Whether whoever a pull request is for is trusted without asking |
| 55 | /// identity: g1t's agent in work nobody asked it for, or someone whose |
| 56 | /// role here is known to allow pushing. |
| 57 | fn trusted_outright(owner: &User, repo: &Repo) -> bool { |
| 58 | owner.id == AGENT_ID || access::can(Some(owner), repo, Capability::Push) |
| 59 | } |
| 60 | |
| 61 | impl Actions { |
| 62 | async fn username(&self, id: Option<&str>) -> Result<Option<String>> { |
| 63 | let Some(id) = id else { return Ok(None) }; |
| 64 | if id == AGENT_ID { |
| 65 | return Ok(Some(AGENT_NAME.to_owned())); |
| 66 | } |
| 67 | let names: std::collections::HashMap<String, String> = |
| 68 | g1t_kit::call(&self.identity, "usernames", &UsernamesArgs { ids: vec![id.to_owned()] }).await?; |
| 69 | Ok(names.get(id).cloned()) |
| 70 | } |
| 71 | |
| 72 | /// Whether whoever a pull request is for (Pull::owner: whoever asked |
| 73 | /// g1t for it, or its author) could push to the repository, so its |
| 74 | /// runs get the secrets and a token. Anyone else's, a reader's included |
| 75 | /// (who may open one on a private repository too), runs without them. |
| 76 | /// A change g1t made for someone is trusted as they are. |
| 77 | async fn insider(&self, owner: &User, repo: &Repo, ws: &User) -> Result<bool> { |
| 78 | if trusted_outright(owner, repo) { |
| 79 | return Ok(true); |
| 80 | } |
| 81 | // Stored authors carry no memberships or grants: ask identity, as |
| 82 | // the workspace (which may see anyone's permission). |
| 83 | let permission: Outcome<access::PermissionInfo> = g1t_kit::call( |
| 84 | &self.identity, |
| 85 | "collaborator_permission", |
| 86 | &access::CollaboratorPermissionArgs { |
| 87 | viewer: Some(ws.clone()), |
| 88 | path: RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() }, |
| 89 | username: owner.username.clone(), |
| 90 | }, |
| 91 | ) |
| 92 | .await?; |
| 93 | Ok(permission |
| 94 | .into_result() |
| 95 | .ok() |
| 96 | .and_then(|info| info.role) |
| 97 | .is_some_and(|role| access::allows(role, Capability::Push))) |
| 98 | } |
| 99 | |
| 100 | async fn commits(&self, repo: &Repo, actor: &User, after: &str, before: Option<&str>) -> Result<Vec<Commit>> { |
| 101 | let log: Outcome<Vec<Commit>> = g1t_kit::call( |
| 102 | &self.repos, |
| 103 | "log", |
| 104 | &LogArgs { |
| 105 | path: RepoPath { |
| 106 | namespace: repo.namespace.clone(), |
| 107 | name: repo.name.clone(), |
| 108 | }, |
| 109 | viewer: Some(actor.clone()), |
| 110 | git_ref: Some(after.to_owned()), |
| 111 | limit: 20, |
| 112 | }, |
| 113 | ) |
| 114 | .await?; |
| 115 | let mut commits: Vec<Commit> = log.into_result().unwrap_or_default(); |
| 116 | if let Some(before) = before |
| 117 | && let Some(at) = commits.iter().position(|commit| commit.hash == before) |
| 118 | { |
| 119 | commits.truncate(at); |
| 120 | } |
| 121 | // GitHub lists them oldest first, with the head commit last. |
| 122 | commits.reverse(); |
| 123 | Ok(commits) |
| 124 | } |
| 125 | |
| 126 | async fn changed_paths(&self, repo: &Repo, actor: &User, base: Option<String>, head: String) -> Result<Vec<String>> { |
| 127 | let compared: Outcome<Comparison> = g1t_kit::call( |
| 128 | &self.repos, |
| 129 | "compare", |
| 130 | &CompareArgs { |
| 131 | repo_id: repo.id.clone(), |
| 132 | viewer: Some(actor.clone()), |
| 133 | base, |
| 134 | head: Some(head), |
| 135 | base_branch: None, |
| 136 | }, |
| 137 | ) |
| 138 | .await?; |
| 139 | Ok(compared.into_result().map(|c| c.files.into_iter().map(|f| f.path).collect()).unwrap_or_default()) |
| 140 | } |
| 141 | |
| 142 | async fn default_head(&self, repo: &Repo) -> Result<Option<String>> { |
| 143 | g1t_kit::call( |
| 144 | &self.repos, |
| 145 | "head", |
| 146 | &g1t_contracts::repos::HeadArgs { |
| 147 | repo_id: repo.id.clone(), |
| 148 | branch: repo.default_branch.clone(), |
| 149 | }, |
| 150 | ) |
| 151 | .await |
| 152 | } |
| 153 | |
| 154 | /// Whether `name` is one of the repository's branches. |
| 155 | async fn is_branch(&self, repo: &Repo, ws: &User, name: &str) -> Result<bool> { |
| 156 | let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call( |
| 157 | &self.repos, |
| 158 | "branches", |
| 159 | &g1t_contracts::repos::BranchesArgs { |
| 160 | path: Self::repo_path(repo), |
| 161 | viewer: Some(ws.clone()), |
| 162 | }, |
| 163 | ) |
| 164 | .await?; |
| 165 | Ok(branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == name)) |
| 166 | } |
| 167 | |
| 168 | fn repo_path(repo: &Repo) -> RepoPath { |
| 169 | RepoPath { |
| 170 | namespace: repo.namespace.clone(), |
| 171 | name: repo.name.clone(), |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | /// The subject of an event of `kind`, as GitHub's `event_name`. |
| 176 | async fn subject(&self, event: &Event, event_name: &str, action: Option<&str>, repo: &Repo, ws: &User, sender: &str) -> Result<Option<Subject>> { |
| 177 | let path = Self::repo_path(repo); |
| 178 | let data = &event.data; |
| 179 | let on_default = |sha: String, payload: Value, title: String, pull: Option<u32>| Subject { |
| 180 | source: path.clone(), |
| 181 | source_ref: None, |
| 182 | git_ref: format!("refs/heads/{}", repo.default_branch), |
| 183 | sha, |
| 184 | head_ref: None, |
| 185 | base_ref: None, |
| 186 | pull, |
| 187 | filter_ref: format!("refs/heads/{}", repo.default_branch), |
| 188 | paths: None, |
| 189 | compare: None, |
| 190 | payload, |
| 191 | title, |
| 192 | trusted: true, |
| 193 | approval: None, |
| 194 | }; |
| 195 | let view = |number: u32| ViewArgs { |
| 196 | repo: path.clone(), |
| 197 | number, |
| 198 | viewer: Some(ws.clone()), |
| 199 | after_seq: 0, |
| 200 | }; |
| 201 | Ok(match event_name { |
| 202 | "push" => { |
| 203 | let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else { |
| 204 | return Ok(None); |
| 205 | }; |
| 206 | // The merge queue's states run merge_group workflows, not push ones. |
| 207 | if git_ref.starts_with("refs/heads/g1t-queue/") { |
| 208 | return Ok(None); |
| 209 | } |
| 210 | let before = data["before"].as_str(); |
| 211 | let commits = self.commits(repo, ws, after, before).await?; |
| 212 | let title = commits.last().map(|c| c.message.lines().next().unwrap_or_default().to_owned()).unwrap_or_default(); |
| 213 | let mut payload = payload::push(repo, git_ref, before, after, &commits, sender); |
| 214 | if let Some(head) = commits.last() { |
| 215 | payload["head_commit"] = payload::commit(repo, head); |
| 216 | } |
| 217 | Some(Subject { |
| 218 | source: path.clone(), |
| 219 | source_ref: Some(after.to_owned()), |
| 220 | git_ref: git_ref.to_owned(), |
| 221 | sha: after.to_owned(), |
| 222 | head_ref: None, |
| 223 | base_ref: None, |
| 224 | pull: None, |
| 225 | filter_ref: git_ref.to_owned(), |
| 226 | paths: None, |
| 227 | compare: Some((before.map(str::to_owned), after.to_owned())), |
| 228 | payload, |
| 229 | title, |
| 230 | trusted: true, |
| 231 | approval: None, |
| 232 | }) |
| 233 | } |
| 234 | // A branch or tag was made: its own commit, as on GitHub. |
| 235 | "create" => { |
| 236 | let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else { |
| 237 | return Ok(None); |
| 238 | }; |
| 239 | if git_ref.starts_with("refs/heads/g1t-queue/") || !data["before"].is_null() { |
| 240 | return Ok(None); |
| 241 | } |
| 242 | let (ref_type, name) = match (git_ref.strip_prefix("refs/heads/"), git_ref.strip_prefix("refs/tags/")) { |
| 243 | (Some(branch), _) => ("branch", branch), |
| 244 | (_, Some(tag)) => ("tag", tag), |
| 245 | _ => return Ok(None), |
| 246 | }; |
| 247 | let payload = json!({ |
| 248 | "ref": name, |
| 249 | "ref_type": ref_type, |
| 250 | "master_branch": repo.default_branch, |
| 251 | "description": repo.description, |
| 252 | "pusher_type": "user", |
| 253 | "repository": payload::repository(repo), |
| 254 | "sender": payload::user(sender), |
| 255 | }); |
| 256 | Some(Subject { |
| 257 | source: path.clone(), |
| 258 | source_ref: Some(after.to_owned()), |
| 259 | git_ref: git_ref.to_owned(), |
| 260 | sha: after.to_owned(), |
| 261 | head_ref: None, |
| 262 | base_ref: None, |
| 263 | pull: None, |
| 264 | filter_ref: git_ref.to_owned(), |
| 265 | paths: None, |
| 266 | compare: None, |
| 267 | payload, |
| 268 | title: format!("Created {ref_type} {name}"), |
| 269 | trusted: true, |
| 270 | approval: None, |
| 271 | }) |
| 272 | } |
| 273 | "pull_request" | "pull_request_target" | "pull_request_review" => { |
| 274 | let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) }; |
| 275 | let detail: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?; |
| 276 | let Outcome::Ok(detail) = detail else { return Ok(None) }; |
| 277 | let pull = &detail.pull; |
| 278 | let base_ref = pull.base_branch(&repo.default_branch).to_owned(); |
| 279 | let mut payload = json!({ |
| 280 | "action": action, |
| 281 | "number": pull.number, |
| 282 | "pull_request": payload::pull(repo, pull), |
| 283 | "repository": payload::repository(repo), |
| 284 | "sender": payload::user(sender), |
| 285 | }); |
| 286 | payload::changed(&mut payload, data); |
| 287 | if event_name == "pull_request_review" { |
| 288 | let review = detail.comments.iter().rev().find(|c| c.verdict.is_some()); |
| 289 | payload["review"] = json!({ |
| 290 | "state": review.and_then(|r| r.verdict).map(|v| format!("{v:?}").to_lowercase()), |
| 291 | "body": review.map(|r| r.body.clone()), |
| 292 | "user": review.map(|r| payload::user(&r.author.username)), |
| 293 | }); |
| 294 | } |
| 295 | let trusted = self.insider(pull.owner(), repo, ws).await?; |
| 296 | // A pull request from outside may wait for approval before |
| 297 | // its head's code runs. `pull_request_target` runs the |
| 298 | // base's code, and a merged one's run the commit it landed |
| 299 | // as, so neither waits. |
| 300 | let approval = if event_name != "pull_request_target" && action != Some("closed") { |
| 301 | self.approval_needed(repo, pull.owner(), ws).await? |
| 302 | } else { |
| 303 | None |
| 304 | }; |
| 305 | let head_ref = payload::head_ref(pull); |
| 306 | if event_name == "pull_request_target" { |
| 307 | // In the base's context: its workflows, its head. |
| 308 | let Some(sha) = self.default_head(repo).await? else { return Ok(None) }; |
| 309 | let mut subject = on_default(sha, payload, pull.title.clone(), Some(pull.number)); |
| 310 | subject.head_ref = Some(head_ref); |
| 311 | subject.base_ref = Some(base_ref.clone()); |
| 312 | subject.filter_ref = format!("refs/heads/{base_ref}"); |
| 313 | subject.paths = Some(pull.files.iter().map(|f| f.path.clone()).collect()); |
| 314 | return Ok(Some(subject)); |
| 315 | } |
| 316 | // A merged pull request's run is on the commit it landed as, |
| 317 | // in the repository; otherwise on its head, where that is. |
| 318 | let landed = match (action, data["commit"].as_str()) { |
| 319 | (Some("closed"), Some(commit)) => Some(commit.to_owned()), |
| 320 | _ => None, |
| 321 | }; |
| 322 | let sha = match (&landed, data["commit"].as_str(), &pull.head_commit) { |
| 323 | (Some(commit), _, _) => commit.clone(), |
| 324 | (None, Some(commit), _) => commit.to_owned(), |
| 325 | (None, None, Some(head)) => head.clone(), |
| 326 | (None, None, None) => return Ok(None), |
| 327 | }; |
| 328 | let source = match landed { |
| 329 | Some(_) => path.clone(), |
| 330 | None => pull.fork.clone().unwrap_or_else(|| path.clone()), |
| 331 | }; |
| 332 | Some(Subject { |
| 333 | source, |
| 334 | source_ref: Some(sha.clone()), |
| 335 | git_ref: format!("refs/pull/{}/merge", pull.number), |
| 336 | sha, |
| 337 | head_ref: Some(head_ref), |
| 338 | base_ref: Some(base_ref.clone()), |
| 339 | pull: Some(pull.number), |
| 340 | // `branches` filters on pull requests name the base. |
| 341 | filter_ref: format!("refs/heads/{base_ref}"), |
| 342 | paths: Some(pull.files.iter().map(|f| f.path.clone()).collect()), |
| 343 | compare: None, |
| 344 | payload, |
| 345 | title: pull.title.clone(), |
| 346 | trusted, |
| 347 | approval, |
| 348 | }) |
| 349 | } |
| 350 | "workflow_run" => { |
| 351 | // A run of a workflow_run workflow does not start another, |
| 352 | // so two such workflows cannot set each other off. |
| 353 | if data["event"].as_str() == Some("workflow_run") { |
| 354 | return Ok(None); |
| 355 | } |
| 356 | let Some(sha) = self.default_head(repo).await? else { return Ok(None) }; |
| 357 | let head_branch = data["ref"].as_str().unwrap_or_default().trim_start_matches("refs/heads/").to_owned(); |
| 358 | let name = data["workflow"].as_str().unwrap_or_default(); |
| 359 | let payload = json!({ |
| 360 | "action": "completed", |
| 361 | "workflow_run": { |
| 362 | "id": data["runId"], |
| 363 | "name": name, |
| 364 | "path": data["path"], |
| 365 | "event": data["event"], |
| 366 | "status": "completed", |
| 367 | "conclusion": data["conclusion"], |
| 368 | "head_sha": data["sha"], |
| 369 | "head_branch": head_branch, |
| 370 | "run_number": data["number"], |
| 371 | "html_url": format!("{SITE}/{}/{}/actions/runs/{}", repo.namespace, repo.name, data["runId"].as_str().unwrap_or_default()), |
| 372 | "pull_requests": data["pull"].as_u64().map(|n| vec![json!({ "number": n })]).unwrap_or_default(), |
| 373 | }, |
| 374 | "workflow": { "name": name, "path": data["path"] }, |
| 375 | "repository": payload::repository(repo), |
| 376 | "sender": payload::user(sender), |
| 377 | }); |
| 378 | let mut subject = on_default(sha, payload, format!("After {name}"), None); |
| 379 | // Branch filters apply to the branch the followed run was on. |
| 380 | subject.filter_ref = format!("refs/heads/{head_branch}"); |
| 381 | Some(subject) |
| 382 | } |
| 383 | "issues" | "issue_comment" => { |
| 384 | let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) }; |
| 385 | let Some(sha) = self.default_head(repo).await? else { return Ok(None) }; |
| 386 | let issue: Outcome<IssueDetail> = g1t_kit::call(&self.work, "get_issue", &view(number)).await?; |
| 387 | let (issue_json, comments, title, on_pull) = match issue { |
| 388 | Outcome::Ok(detail) => (payload::issue(repo, &detail.issue), detail.comments, detail.issue.title.clone(), false), |
| 389 | Outcome::Fail(_) => { |
| 390 | let pull: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?; |
| 391 | let Outcome::Ok(detail) = pull else { return Ok(None) }; |
| 392 | (payload::pull_as_issue(repo, &detail.pull), detail.comments, detail.pull.title.clone(), true) |
| 393 | } |
| 394 | }; |
| 395 | let mut payload = json!({ |
| 396 | "action": action, |
| 397 | "issue": issue_json, |
| 398 | "repository": payload::repository(repo), |
| 399 | "sender": payload::user(sender), |
| 400 | }); |
| 401 | payload::changed(&mut payload, data); |
| 402 | if event_name == "issue_comment" { |
| 403 | let comment_id = data["commentId"].as_str(); |
| 404 | if action == Some("deleted") { |
| 405 | // Gone by now: as the event kept it. |
| 406 | match data.get("comment").filter(|kept| kept.is_object()) { |
| 407 | Some(kept) => payload["comment"] = payload::deleted_comment(repo, number, kept, on_pull), |
| 408 | None => return Ok(None), |
| 409 | } |
| 410 | } else { |
| 411 | let comment = comments.iter().find(|c| Some(c.id.as_str()) == comment_id); |
| 412 | // A new comment is the newest; an edited one must be found. |
| 413 | let comment = if action == Some("created") { comment.or(comments.last()) } else { comment }; |
| 414 | match comment { |
| 415 | Some(comment) => payload["comment"] = payload::comment(repo, number, comment, on_pull), |
| 416 | None => return Ok(None), |
| 417 | } |
| 418 | } |
| 419 | // `edited`: what the body was before. |
| 420 | if let Some(changes) = data.get("changes").filter(|changes| changes.is_object()) { |
| 421 | payload["changes"] = changes.clone(); |
| 422 | } |
| 423 | } |
| 424 | Some(on_default(sha, payload, title, on_pull.then_some(number))) |
| 425 | } |
| 426 | // A release: on its tag, at the commit the tag named. |
| 427 | "release" => { |
| 428 | let release = &data["release"]; |
| 429 | let Some(tag) = data["tagName"].as_str().or_else(|| release["tagName"].as_str()) else { return Ok(None) }; |
| 430 | let sha = match release["target"].as_str().filter(|target| !target.is_empty()) { |
| 431 | Some(target) => target.to_owned(), |
| 432 | None => match self.default_head(repo).await? { |
| 433 | Some(head) => head, |
| 434 | None => return Ok(None), |
| 435 | }, |
| 436 | }; |
| 437 | let git_ref = format!("refs/tags/{tag}"); |
| 438 | let mut payload = json!({ |
| 439 | "action": action, |
| 440 | "release": payload::release(repo, release), |
| 441 | "repository": payload::repository(repo), |
| 442 | "sender": payload::user(sender), |
| 443 | }); |
| 444 | if let Some(changes) = data.get("changes").filter(|changes| changes.is_object()) { |
| 445 | payload["changes"] = changes.clone(); |
| 446 | } |
| 447 | let name = release["name"].as_str().filter(|name| !name.is_empty()).unwrap_or(tag); |
| 448 | Some(Subject { |
| 449 | source: path.clone(), |
| 450 | source_ref: Some(sha.clone()), |
| 451 | git_ref: git_ref.clone(), |
| 452 | sha, |
| 453 | head_ref: None, |
| 454 | base_ref: None, |
| 455 | pull: None, |
| 456 | filter_ref: git_ref, |
| 457 | paths: None, |
| 458 | compare: None, |
| 459 | payload, |
| 460 | title: format!("Release {name} {}", action.unwrap_or("changed")), |
| 461 | trusted: true, |
| 462 | approval: None, |
| 463 | }) |
| 464 | } |
| 465 | // A deployment, or a new status of one: at the commit deployed, |
| 466 | // on the branch or tag it names (none for a bare commit). |
| 467 | "deployment" | "deployment_status" => { |
| 468 | let deployment = &data["deployment"]; |
| 469 | let Some(sha) = deployment["sha"].as_str().filter(|sha| !sha.is_empty()).map(str::to_owned) else { return Ok(None) }; |
| 470 | let named = deployment["ref"].as_str().unwrap_or_default(); |
| 471 | let git_ref = if named.is_empty() || named == sha || is_commit(named) { |
| 472 | String::new() |
| 473 | } else if named.starts_with("refs/") { |
| 474 | named.to_owned() |
| 475 | } else if self.is_branch(repo, ws, named).await? { |
| 476 | format!("refs/heads/{named}") |
| 477 | } else { |
| 478 | format!("refs/tags/{named}") |
| 479 | }; |
| 480 | let environment = deployment["environment"].as_str().unwrap_or_default(); |
| 481 | let mut payload = json!({ |
| 482 | "action": "created", |
| 483 | "deployment": payload::deployment(repo, deployment), |
| 484 | "repository": payload::repository(repo), |
| 485 | "sender": payload::user(sender), |
| 486 | }); |
| 487 | let title = if event_name == "deployment_status" { |
| 488 | let status = &data["deploymentStatus"]; |
| 489 | payload["deployment_status"] = payload::deployment_status(repo, status, deployment); |
| 490 | format!("Deployment to {environment}: {}", status["state"].as_str().unwrap_or("changed")) |
| 491 | } else { |
| 492 | format!("Deployment to {environment}") |
| 493 | }; |
| 494 | Some(Subject { |
| 495 | source: path.clone(), |
| 496 | source_ref: Some(sha.clone()), |
| 497 | filter_ref: git_ref.clone(), |
| 498 | git_ref, |
| 499 | sha, |
| 500 | head_ref: None, |
| 501 | base_ref: None, |
| 502 | pull: None, |
| 503 | paths: None, |
| 504 | compare: None, |
| 505 | payload, |
| 506 | title, |
| 507 | trusted: true, |
| 508 | approval: None, |
| 509 | }) |
| 510 | } |
| 511 | _ => None, |
| 512 | }) |
| 513 | } |
| 514 | |
| 515 | /// A push keeps the repository's schedules going (`run_schedules`). |
| 516 | /// Written at most once a day, and only on scheduled workflows. |
| 517 | async fn note_push(&self, repo_id: &str) -> Result<()> { |
| 518 | let at = now_ms(); |
| 519 | self.db |
| 520 | .prepare("UPDATE workflows SET pushed_at = ? WHERE repo_id = ? AND crons != '[]' AND (pushed_at IS NULL OR pushed_at < ?)") |
| 521 | .bind(&[rfc3339(at).into(), repo_id.into(), rfc3339(at.saturating_sub(24 * 60 * 60 * 1000)).into()])? |
| 522 | .run() |
| 523 | .await?; |
| 524 | Ok(()) |
| 525 | } |
| 526 | |
| 527 | pub async fn on_event(&self, event: &Event) -> Result<()> { |
| 528 | let Some(repo_id) = event.repo_id.as_deref() else { return Ok(()) }; |
| 529 | let mut mapped = github_events(&event.kind); |
| 530 | // A new branch or tag is also `create`. |
| 531 | if event.kind == "git.push" && event.data["before"].is_null() { |
| 532 | mapped.push(("create", None)); |
| 533 | } |
| 534 | let pushed_default = event.kind == "git.push" && event.data["defaultBranch"].as_bool() == Some(true); |
| 535 | if event.kind == "git.push" { |
| 536 | self.note_push(repo_id).await?; |
| 537 | } |
| 538 | if mapped.is_empty() && !pushed_default { |
| 539 | return Ok(()); |
| 540 | } |
| 541 | let Some((repo, ws)) = self.repo_by_id(repo_id).await? else { return Ok(()) }; |
| 542 | if pushed_default { |
| 543 | self.sync(&repo, &ws).await?; |
| 544 | } |
| 545 | // What a workflow job's own token did starts no workflows, as on |
| 546 | // GitHub, so a workflow cannot set itself off; only |
| 547 | // `workflow_dispatch` and `repository_dispatch` do. |
| 548 | if let Some(run) = caused_by_job(&event.data) { |
| 549 | worker::console_log!("actions: {} {} came from run {run}'s token; no workflows start for it", event.kind, event.id); |
| 550 | return Ok(()); |
| 551 | } |
| 552 | let sender = self.username(event.actor.as_deref()).await?.unwrap_or_else(|| repo.namespace.clone()); |
| 553 | for (event_name, action) in mapped { |
| 554 | // Issues and comments start the default branch's workflows, |
| 555 | // which the synced table lists: when none listens, nothing is |
| 556 | // read from git. Agents make many of these events. |
| 557 | // Deployments' statuses are as frequent (every g1t.page build |
| 558 | // reports several), so they look there first too. |
| 559 | if matches!(event_name, "issues" | "issue_comment" | "deployment" | "deployment_status") |
| 560 | && self.listens(repo_id, event_name).await? == Some(false) |
| 561 | { |
| 562 | continue; |
| 563 | } |
| 564 | let Some(mut subject) = self.subject(event, event_name, action, &repo, &ws, &sender).await? else { |
| 565 | continue; |
| 566 | }; |
| 567 | let read = self.read_workflows(&subject.source, &ws, subject.source_ref.as_deref()).await?; |
| 568 | // A pull request's head runs each workflow once, however many |
| 569 | // events say it is there (marked ready, and pushed). |
| 570 | let key = match subject.pull { |
| 571 | Some(number) if event_name.starts_with("pull_request") && event_name != "pull_request_review" => { |
| 572 | // Reopened or made a draft again runs anew, at a head |
| 573 | // that may have run before. |
| 574 | let phase = match action { |
| 575 | Some("closed") => "closed".to_owned(), |
| 576 | Some(again @ ("reopened" | "converted_to_draft")) => format!("{again}:{}", event.id), |
| 577 | _ => "open".to_owned(), |
| 578 | }; |
| 579 | format!("{event_name}:{number}:{}:{phase}", subject.sha) |
| 580 | } |
| 581 | _ if event_name == "create" => format!("{}:create", event.id), |
| 582 | _ => event.id.clone(), |
| 583 | }; |
| 584 | self.start_matching(&repo, &ws, read, &mut subject, event_name, action, &key, event.actor.as_deref(), &sender) |
| 585 | .await?; |
| 586 | } |
| 587 | Ok(()) |
| 588 | } |
| 589 | |
| 590 | #[allow(clippy::too_many_arguments)] |
| 591 | async fn start_matching( |
| 592 | &self, |
| 593 | repo: &Repo, |
| 594 | ws: &User, |
| 595 | read: Read, |
| 596 | subject: &mut Subject, |
| 597 | event_name: &str, |
| 598 | action: Option<&str>, |
| 599 | event_key: &str, |
| 600 | actor_id: Option<&str>, |
| 601 | sender: &str, |
| 602 | ) -> Result<()> { |
| 603 | for file in read.files { |
| 604 | let parsed = workflow::parse(&file.source); |
| 605 | let workflow = match parsed { |
| 606 | Ok(workflow) => workflow, |
| 607 | Err(problem) => { |
| 608 | // A push shows a broken workflow as a failed run, as GitHub does. |
| 609 | if event_name == "push" && file.source.contains("on") { |
| 610 | self.record_invalid(repo, &file.path, &file.source, subject, event_key, actor_id, sender, &problem) |
| 611 | .await?; |
| 612 | } |
| 613 | continue; |
| 614 | } |
| 615 | }; |
| 616 | let Some(trigger) = workflow.trigger(event_name) else { continue }; |
| 617 | // workflow_run follows the workflows it names. |
| 618 | if event_name == "workflow_run" { |
| 619 | let followed = subject.payload["workflow_run"]["name"].as_str().unwrap_or_default(); |
| 620 | if !trigger.workflows.iter().any(|name| name == followed) { |
| 621 | continue; |
| 622 | } |
| 623 | } |
| 624 | if !trigger.wants_type(action) || !self.passes(repo, ws, trigger, subject, event_name).await? { |
| 625 | continue; |
| 626 | } |
| 627 | if self.disabled(&repo.id, &file.path).await? { |
| 628 | continue; |
| 629 | } |
| 630 | self.create_run(NewRun { |
| 631 | repo: repo.clone(), |
| 632 | path: file.path, |
| 633 | source: file.source, |
| 634 | info: self.run_info(repo, &workflow, event_name, subject, sender, actor_id), |
| 635 | workflow, |
| 636 | action: action.map(str::to_owned), |
| 637 | pull: subject.pull, |
| 638 | title: subject.title.clone(), |
| 639 | inputs: Map::new(), |
| 640 | event_key: event_key.to_owned(), |
| 641 | actor_id: actor_id.map(str::to_owned), |
| 642 | actor: Some(sender.to_owned()), |
| 643 | trusted: subject.trusted, |
| 644 | approval: subject.approval.clone(), |
| 645 | }) |
| 646 | .await?; |
| 647 | } |
| 648 | Ok(()) |
| 649 | } |
| 650 | |
| 651 | /// Whether the branch, tag and path filters let the event through. |
| 652 | async fn passes(&self, repo: &Repo, ws: &User, trigger: &Trigger, subject: &mut Subject, event_name: &str) -> Result<bool> { |
| 653 | let git_ref = subject.filter_ref.as_str(); |
| 654 | if let Some(tag) = git_ref.strip_prefix("refs/tags/") { |
| 655 | // A tag push runs a workflow that filters tags, or filters nothing. |
| 656 | if trigger.tags.is_set() { |
| 657 | if !trigger.tags.allows(tag) { |
| 658 | return Ok(false); |
| 659 | } |
| 660 | } else if trigger.branches.is_set() { |
| 661 | return Ok(false); |
| 662 | } |
| 663 | // Paths are not checked for tags, as on GitHub. |
| 664 | return Ok(true); |
| 665 | } |
| 666 | let branch = git_ref.strip_prefix("refs/heads/").unwrap_or(git_ref); |
| 667 | if trigger.branches.is_set() { |
| 668 | if !trigger.branches.allows(branch) { |
| 669 | return Ok(false); |
| 670 | } |
| 671 | } else if event_name == "push" && trigger.tags.is_set() { |
| 672 | return Ok(false); |
| 673 | } |
| 674 | if trigger.paths.is_set() { |
| 675 | if subject.paths.is_none() { |
| 676 | let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone())); |
| 677 | subject.paths = Some(self.changed_paths(repo, ws, base, head).await?); |
| 678 | } |
| 679 | if !trigger.paths.allows_paths(subject.paths.as_deref().unwrap_or_default()) { |
| 680 | return Ok(false); |
| 681 | } |
| 682 | } |
| 683 | Ok(true) |
| 684 | } |
| 685 | |
| 686 | async fn disabled(&self, repo_id: &str, path: &str) -> Result<bool> { |
| 687 | let row = self |
| 688 | .db |
| 689 | .prepare("SELECT * FROM workflows WHERE repo_id = ? AND path = ?") |
| 690 | .bind(&[repo_id.into(), path.into()])? |
| 691 | .first::<WorkflowRow>(None) |
| 692 | .await?; |
| 693 | Ok(row.is_some_and(|row| row.state == "disabled")) |
| 694 | } |
| 695 | |
| 696 | fn run_info(&self, repo: &Repo, workflow: &Workflow, event_name: &str, subject: &Subject, sender: &str, actor_id: Option<&str>) -> RunInfo { |
| 697 | RunInfo { |
| 698 | repository: format!("{}/{}", repo.namespace, repo.name), |
| 699 | repository_id: repo.id.clone(), |
| 700 | default_branch: repo.default_branch.clone(), |
| 701 | event_name: event_name.to_owned(), |
| 702 | event: subject.payload.clone(), |
| 703 | git_ref: subject.git_ref.clone(), |
| 704 | sha: subject.sha.clone(), |
| 705 | head_ref: subject.head_ref.clone(), |
| 706 | base_ref: subject.base_ref.clone(), |
| 707 | actor: sender.to_owned(), |
| 708 | actor_id: actor_id.unwrap_or_default().to_owned(), |
| 709 | triggering_actor: sender.to_owned(), |
| 710 | run_id: String::new(), |
| 711 | run_number: 0, |
| 712 | run_attempt: 1, |
| 713 | workflow: workflow.name.clone().unwrap_or_default(), |
| 714 | workflow_path: String::new(), |
| 715 | server_url: SITE.to_owned(), |
| 716 | api_url: API.to_owned(), |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | #[allow(clippy::too_many_arguments)] |
| 721 | async fn record_invalid( |
| 722 | &self, |
| 723 | repo: &Repo, |
| 724 | path: &str, |
| 725 | source: &str, |
| 726 | subject: &Subject, |
| 727 | event_key: &str, |
| 728 | actor_id: Option<&str>, |
| 729 | sender: &str, |
| 730 | problem: &str, |
| 731 | ) -> Result<()> { |
| 732 | let row = self.workflow_row(repo, path, path, source).await?; |
| 733 | self.record_failed_run(&row, subject.git_ref.as_str(), &subject.sha, event_key, actor_id, sender, problem).await |
| 734 | } |
| 735 | |
| 736 | /// Scheduled workflows that run this minute, on the default branch: at |
| 737 | /// most every five minutes (`cron::Schedule::runs_at`). Not in a |
| 738 | /// repository with no push for [`crate::SCHEDULE_IDLE_MS`], nor for an |
| 739 | /// hour after billing refused one of the workflow's scheduled jobs |
| 740 | /// ([`crate::SCHEDULE_REFUSED_MS`]): no run is made only to be refused. |
| 741 | pub async fn run_schedules(&self, minute: u64) -> Result<()> { |
| 742 | let rows = self |
| 743 | .db |
| 744 | .prepare( |
| 745 | "SELECT * FROM workflows WHERE state = 'active' AND crons != '[]' AND error IS NULL |
| 746 | AND COALESCE(pushed_at, updated_at) >= ? AND (schedule_refused_until IS NULL OR schedule_refused_until <= ?)", |
| 747 | ) |
| 748 | .bind(&[rfc3339(minute.saturating_sub(crate::SCHEDULE_IDLE_MS)).into(), rfc3339(minute).into()])? |
| 749 | .all() |
| 750 | .await? |
| 751 | .results::<WorkflowRow>()?; |
| 752 | for row in rows { |
| 753 | let crons: Vec<String> = serde_json::from_str(&row.crons).unwrap_or_default(); |
| 754 | let Some(cron) = crons.iter().find(|cron| g1t_actions::cron::Schedule::parse(cron).is_ok_and(|s| s.runs_at(minute))) else { |
| 755 | continue; |
| 756 | }; |
| 757 | let Ok(workflow) = workflow::parse(&row.source) else { continue }; |
| 758 | // Schedules wait while a repository is archived; a deleted one is not found. |
| 759 | let Some((repo, _ws)) = self.repo_by_id(&row.repo_id).await?.filter(|(repo, _)| !repo.archived()) else { continue }; |
| 760 | let Some(sha) = self.default_head(&repo).await? else { continue }; |
| 761 | let payload = json!({ "schedule": cron, "repository": payload::repository(&repo), "workflow": row.path }); |
| 762 | let mut subject = Subject { |
| 763 | source: Self::repo_path(&repo), |
| 764 | source_ref: None, |
| 765 | git_ref: format!("refs/heads/{}", repo.default_branch), |
| 766 | sha, |
| 767 | head_ref: None, |
| 768 | base_ref: None, |
| 769 | pull: None, |
| 770 | filter_ref: String::new(), |
| 771 | paths: None, |
| 772 | compare: None, |
| 773 | payload, |
| 774 | title: format!("Scheduled: {cron}"), |
| 775 | trusted: true, |
| 776 | approval: None, |
| 777 | }; |
| 778 | subject.filter_ref = subject.git_ref.clone(); |
| 779 | let info = self.run_info(&repo, &workflow, "schedule", &subject, &repo.namespace, None); |
| 780 | self.create_run(NewRun { |
| 781 | repo: repo.clone(), |
| 782 | path: row.path.clone(), |
| 783 | source: row.source.clone(), |
| 784 | workflow, |
| 785 | info, |
| 786 | action: None, |
| 787 | pull: None, |
| 788 | title: subject.title.clone(), |
| 789 | inputs: Map::new(), |
| 790 | event_key: format!("schedule:{minute}"), |
| 791 | actor_id: None, |
| 792 | actor: None, |
| 793 | trusted: true, |
| 794 | approval: None, |
| 795 | }) |
| 796 | .await?; |
| 797 | } |
| 798 | Ok(()) |
| 799 | } |
| 800 | |
| 801 | /// `dispatch`: someone with the Write role runs a workflow that has |
| 802 | /// `workflow_dispatch`. |
| 803 | pub async fn dispatch(&self, a: DispatchArgs) -> Result<Outcome<WorkflowRun>> { |
| 804 | let repo = check!(self.may(&a.actor, &a.repo, Capability::Run).await?); |
| 805 | if repo.archived() { |
| 806 | return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name))); |
| 807 | } |
| 808 | let Some(ws) = self.workspace_actor(&repo.namespace).await? else { |
| 809 | return Ok(fail(FailureCode::NotFound, "There is no such workspace.")); |
| 810 | }; |
| 811 | let git_ref = a.git_ref.clone().unwrap_or_else(|| repo.default_branch.clone()); |
| 812 | let full_ref = if git_ref.starts_with("refs/") { |
| 813 | git_ref.clone() |
| 814 | } else { |
| 815 | // A branch if there is one by that name, otherwise a tag. |
| 816 | let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call( |
| 817 | &self.repos, |
| 818 | "branches", |
| 819 | &g1t_contracts::repos::BranchesArgs { |
| 820 | path: Self::repo_path(&repo), |
| 821 | viewer: Some(ws.clone()), |
| 822 | }, |
| 823 | ) |
| 824 | .await?; |
| 825 | let is_branch = branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == git_ref); |
| 826 | format!("refs/{}/{git_ref}", if is_branch { "heads" } else { "tags" }) |
| 827 | }; |
| 828 | let short = full_ref.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/").to_owned(); |
| 829 | let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&short)).await?; |
| 830 | let Some(sha) = read.head.clone() else { |
| 831 | return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}."))); |
| 832 | }; |
| 833 | // A workflow is named by its file (`build.yml`), its path, or its id |
| 834 | // (`wfl_…`), which stands for the path it was read from. |
| 835 | let by_id = if a.workflow.starts_with("wfl_") { |
| 836 | self.db |
| 837 | .prepare("SELECT * FROM workflows WHERE repo_id = ? AND id = ?") |
| 838 | .bind(&[repo.id.as_str().into(), a.workflow.as_str().into()])? |
| 839 | .first::<WorkflowRow>(None) |
| 840 | .await? |
| 841 | .map(|row| row.path) |
| 842 | } else { |
| 843 | None |
| 844 | }; |
| 845 | let named = by_id.as_deref().unwrap_or(&a.workflow); |
| 846 | let wanted = named.trim_start_matches(".g1t/workflows/"); |
| 847 | let Some(file) = read.files.iter().find(|file| { |
| 848 | file.path.rsplit('/').next() == Some(wanted) || file.path == named |
| 849 | }) else { |
| 850 | return Ok(fail(FailureCode::NotFound, format!("There is no workflow {wanted} on {short}."))); |
| 851 | }; |
| 852 | let workflow = match workflow::parse(&file.source) { |
| 853 | Ok(workflow) => workflow, |
| 854 | Err(problem) => return Ok(fail(FailureCode::Invalid, format!("The workflow does not read: {problem}"))), |
| 855 | }; |
| 856 | let Some(trigger) = workflow.trigger("workflow_dispatch") else { |
| 857 | return Ok(fail(FailureCode::Invalid, "That workflow cannot be run by hand: it has no `workflow_dispatch` trigger.")); |
| 858 | }; |
| 859 | let inputs = check!(dispatch_inputs(trigger, &a.inputs)); |
| 860 | let payload = json!({ |
| 861 | "inputs": inputs, |
| 862 | "ref": full_ref, |
| 863 | "repository": payload::repository(&repo), |
| 864 | "sender": payload::user(&a.actor.username), |
| 865 | "workflow": file.path, |
| 866 | }); |
| 867 | let subject = Subject { |
| 868 | source: Self::repo_path(&repo), |
| 869 | source_ref: Some(sha.clone()), |
| 870 | git_ref: full_ref.clone(), |
| 871 | sha, |
| 872 | head_ref: None, |
| 873 | base_ref: None, |
| 874 | pull: None, |
| 875 | filter_ref: full_ref, |
| 876 | paths: None, |
| 877 | compare: None, |
| 878 | payload, |
| 879 | title: format!("{} run by {}", workflow.display_name(&file.path), a.actor.username), |
| 880 | trusted: true, |
| 881 | approval: None, |
| 882 | }; |
| 883 | let info = self.run_info(&repo, &workflow, "workflow_dispatch", &subject, &a.actor.username, Some(&a.actor.id)); |
| 884 | let created = self |
| 885 | .create_run(NewRun { |
| 886 | repo: repo.clone(), |
| 887 | path: file.path.clone(), |
| 888 | source: file.source.clone(), |
| 889 | workflow, |
| 890 | info, |
| 891 | action: None, |
| 892 | pull: None, |
| 893 | title: subject.title.clone(), |
| 894 | inputs, |
| 895 | event_key: format!("dispatch:{}", new_id("dsp", now_ms())), |
| 896 | actor_id: Some(a.actor.id.clone()), |
| 897 | actor: Some(a.actor.username.clone()), |
| 898 | trusted: true, |
| 899 | approval: None, |
| 900 | }) |
| 901 | .await?; |
| 902 | match created { |
| 903 | Some(id) => self.run_summary(&id).await, |
| 904 | None => Ok(fail(FailureCode::Conflict, "It did not start.")), |
| 905 | } |
| 906 | } |
| 907 | |
| 908 | /// `repository_dispatch`: an outside event, by name, starts the default |
| 909 | /// branch's workflows that run `on: repository_dispatch` with that type |
| 910 | /// (or with no `types`). A workflow job's token may send one: this, |
| 911 | /// with `workflow_dispatch`, is how a workflow starts another. |
| 912 | pub async fn repository_dispatch(&self, a: RepositoryDispatchArgs) -> Result<Outcome<u32>> { |
| 913 | let repo = check!(self.may(&a.actor, &a.repo, Capability::Push).await?); |
| 914 | if repo.archived() { |
| 915 | return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name))); |
| 916 | } |
| 917 | let event_type = a.event_type.trim().to_owned(); |
| 918 | if event_type.is_empty() || event_type.chars().count() > 100 { |
| 919 | return Ok(fail(FailureCode::Invalid, "event_type is 1 to 100 characters.")); |
| 920 | } |
| 921 | let client_payload = match a.client_payload { |
| 922 | Value::Null => json!({}), |
| 923 | Value::Object(map) if map.len() <= 10 => Value::Object(map), |
| 924 | Value::Object(_) => return Ok(fail(FailureCode::Invalid, "client_payload has at most 10 top-level properties.")), |
| 925 | _ => return Ok(fail(FailureCode::Invalid, "client_payload is a JSON object.")), |
| 926 | }; |
| 927 | if serde_json::to_string(&client_payload).map_or(0, |text| text.len()) > 64 * 1024 { |
| 928 | return Ok(fail(FailureCode::Invalid, "client_payload is at most 64 KB.")); |
| 929 | } |
| 930 | let Some(ws) = self.workspace_actor(&repo.namespace).await? else { |
| 931 | return Ok(fail(FailureCode::NotFound, "There is no such workspace.")); |
| 932 | }; |
| 933 | let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&repo.default_branch)).await?; |
| 934 | let Some(sha) = read.head.clone() else { |
| 935 | return Ok(fail(FailureCode::NotFound, "The repository has no default branch to run on yet.")); |
| 936 | }; |
| 937 | let git_ref = format!("refs/heads/{}", repo.default_branch); |
| 938 | let payload = json!({ |
| 939 | "action": event_type, |
| 940 | "branch": repo.default_branch, |
| 941 | "client_payload": client_payload, |
| 942 | "repository": payload::repository(&repo), |
| 943 | "sender": payload::user(&a.actor.username), |
| 944 | }); |
| 945 | let key = format!("repository_dispatch:{}", new_id("dsp", now_ms())); |
| 946 | let mut started = 0u32; |
| 947 | for file in read.files { |
| 948 | let Ok(workflow) = workflow::parse(&file.source) else { continue }; |
| 949 | let Some(trigger) = workflow.trigger("repository_dispatch") else { continue }; |
| 950 | if !trigger.wants_type(Some(&event_type)) || self.disabled(&repo.id, &file.path).await? { |
| 951 | continue; |
| 952 | } |
| 953 | let subject = Subject { |
| 954 | source: Self::repo_path(&repo), |
| 955 | source_ref: Some(sha.clone()), |
| 956 | git_ref: git_ref.clone(), |
| 957 | sha: sha.clone(), |
| 958 | head_ref: None, |
| 959 | base_ref: None, |
| 960 | pull: None, |
| 961 | filter_ref: git_ref.clone(), |
| 962 | paths: None, |
| 963 | compare: None, |
| 964 | payload: payload.clone(), |
| 965 | title: event_type.clone(), |
| 966 | trusted: true, |
| 967 | approval: None, |
| 968 | }; |
| 969 | let info = self.run_info(&repo, &workflow, "repository_dispatch", &subject, &a.actor.username, Some(&a.actor.id)); |
| 970 | let created = self |
| 971 | .create_run(NewRun { |
| 972 | repo: repo.clone(), |
| 973 | path: file.path.clone(), |
| 974 | source: file.source.clone(), |
| 975 | workflow, |
| 976 | info, |
| 977 | action: Some(event_type.clone()), |
| 978 | pull: None, |
| 979 | title: subject.title.clone(), |
| 980 | inputs: Map::new(), |
| 981 | event_key: key.clone(), |
| 982 | actor_id: Some(a.actor.id.clone()), |
| 983 | actor: Some(a.actor.username.clone()), |
| 984 | trusted: true, |
| 985 | approval: None, |
| 986 | }) |
| 987 | .await?; |
| 988 | if created.is_some() { |
| 989 | started += 1; |
| 990 | } |
| 991 | } |
| 992 | Ok(Outcome::Ok(started)) |
| 993 | } |
| 994 | } |
| 995 | |
| 996 | #[derive(serde::Deserialize)] |
| 997 | #[serde(rename_all = "camelCase")] |
| 998 | pub struct MergeGroupArgs { |
| 999 | pub repo_id: String, |
| 1000 | pub entry: String, |
| 1001 | pub sha: String, |
| 1002 | pub head_ref: String, |
| 1003 | #[serde(default)] |
| 1004 | pub base_sha: Option<String>, |
| 1005 | pub number: u32, |
| 1006 | #[serde(default)] |
| 1007 | pub ahead: Vec<u32>, |
| 1008 | } |
| 1009 | |
| 1010 | impl Actions { |
| 1011 | /// `merge_group`: the merge queue built a state and its checks passed. |
| 1012 | /// Starts the workflows that run `on: merge_group` on it, as GitHub's |
| 1013 | /// queue does, and says how many started; the queue waits for their |
| 1014 | /// statuses on that commit. |
| 1015 | pub async fn merge_group(&self, a: MergeGroupArgs) -> Result<Outcome<Value>> { |
| 1016 | let Some((repo, ws)) = self.repo_by_id(&a.repo_id).await? else { |
| 1017 | return Ok(Outcome::Ok(json!({ "runs": 0 }))); |
| 1018 | }; |
| 1019 | let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&a.sha)).await?; |
| 1020 | let head_commit = self.commits(&repo, &ws, &a.sha, None).await?.pop(); |
| 1021 | let payload = json!({ |
| 1022 | "action": "checks_requested", |
| 1023 | "merge_group": { |
| 1024 | "head_sha": a.sha, |
| 1025 | "head_ref": a.head_ref, |
| 1026 | "base_sha": a.base_sha, |
| 1027 | "base_ref": format!("refs/heads/{}", repo.default_branch), |
| 1028 | "head_commit": head_commit.as_ref().map(|c| payload::commit(&repo, c)), |
| 1029 | }, |
| 1030 | "repository": payload::repository(&repo), |
| 1031 | "sender": payload::user(&repo.namespace), |
| 1032 | }); |
| 1033 | let mut started = 0u32; |
| 1034 | for file in read.files { |
| 1035 | let Ok(workflow) = workflow::parse(&file.source) else { continue }; |
| 1036 | let Some(trigger) = workflow.trigger("merge_group") else { continue }; |
| 1037 | if !trigger.wants_type(Some("checks_requested")) || self.disabled(&repo.id, &file.path).await? { |
| 1038 | continue; |
| 1039 | } |
| 1040 | // Branch filters on merge_group name the branch it merges into. |
| 1041 | if trigger.branches.is_set() && !trigger.branches.allows(&repo.default_branch) { |
| 1042 | continue; |
| 1043 | } |
| 1044 | let ahead = if a.ahead.is_empty() { |
| 1045 | String::new() |
| 1046 | } else { |
| 1047 | format!(" after {}", a.ahead.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", ")) |
| 1048 | }; |
| 1049 | let subject = Subject { |
| 1050 | source: Self::repo_path(&repo), |
| 1051 | source_ref: Some(a.sha.clone()), |
| 1052 | git_ref: a.head_ref.clone(), |
| 1053 | sha: a.sha.clone(), |
| 1054 | head_ref: None, |
| 1055 | base_ref: Some(repo.default_branch.clone()), |
| 1056 | pull: Some(a.number), |
| 1057 | filter_ref: format!("refs/heads/{}", repo.default_branch), |
| 1058 | paths: None, |
| 1059 | compare: None, |
| 1060 | payload: payload.clone(), |
| 1061 | title: format!("Merge queue: #{}{ahead}", a.number), |
| 1062 | trusted: true, |
| 1063 | approval: None, |
| 1064 | }; |
| 1065 | let info = self.run_info(&repo, &workflow, "merge_group", &subject, &repo.namespace, None); |
| 1066 | let created = self |
| 1067 | .create_run(NewRun { |
| 1068 | repo: repo.clone(), |
| 1069 | path: file.path.clone(), |
| 1070 | source: file.source.clone(), |
| 1071 | workflow, |
| 1072 | info, |
| 1073 | action: Some("checks_requested".to_owned()), |
| 1074 | pull: Some(a.number), |
| 1075 | title: subject.title.clone(), |
| 1076 | inputs: Map::new(), |
| 1077 | event_key: format!("merge_group:{}:{}", a.entry, a.sha), |
| 1078 | actor_id: None, |
| 1079 | actor: None, |
| 1080 | trusted: true, |
| 1081 | approval: None, |
| 1082 | }) |
| 1083 | .await?; |
| 1084 | if created.is_some() { |
| 1085 | started += 1; |
| 1086 | } |
| 1087 | } |
| 1088 | Ok(Outcome::Ok(json!({ "runs": started }))) |
| 1089 | } |
| 1090 | } |
| 1091 | |
| 1092 | /// The inputs of a manual run: what was given, checked against the |
| 1093 | /// workflow's declared inputs, with their defaults filled in. |
| 1094 | fn dispatch_inputs(trigger: &Trigger, given: &Map<String, Value>) -> Outcome<Map<String, Value>> { |
| 1095 | let mut inputs = Map::new(); |
| 1096 | for (name, spec) in &trigger.inputs { |
| 1097 | let kind = spec.get("type").and_then(Value::as_str).unwrap_or("string"); |
| 1098 | let value = given.get(name).cloned().or_else(|| spec.get("default").cloned()); |
| 1099 | let required = spec.get("required").and_then(Value::as_bool).unwrap_or(false); |
| 1100 | let value = match value { |
| 1101 | Some(Value::Null) | None if required => return fail(FailureCode::Invalid, format!("The input `{name}` is required.")), |
| 1102 | Some(Value::Null) | None => match kind { |
| 1103 | "boolean" => Value::Bool(false), |
| 1104 | _ => Value::String(String::new()), |
| 1105 | }, |
| 1106 | Some(value) => match kind { |
| 1107 | "boolean" => Value::Bool(match &value { |
| 1108 | Value::Bool(flag) => *flag, |
| 1109 | Value::String(text) => text == "true", |
| 1110 | _ => false, |
| 1111 | }), |
| 1112 | "number" => match &value { |
| 1113 | Value::Number(_) => value, |
| 1114 | Value::String(text) => match text.parse::<f64>().ok().and_then(serde_json::Number::from_f64) { |
| 1115 | Some(number) => Value::Number(number), |
| 1116 | None => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")), |
| 1117 | }, |
| 1118 | _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")), |
| 1119 | }, |
| 1120 | "choice" => { |
| 1121 | let text = g1t_actions::expr::to_text(&value); |
| 1122 | let options: Vec<String> = |
| 1123 | spec.get("options").and_then(Value::as_array).map(|o| o.iter().map(g1t_actions::expr::to_text).collect()).unwrap_or_default(); |
| 1124 | if !options.is_empty() && !options.contains(&text) { |
| 1125 | return fail(FailureCode::Invalid, format!("The input `{name}` is one of {}.", options.join(", "))); |
| 1126 | } |
| 1127 | Value::String(text) |
| 1128 | } |
| 1129 | _ => Value::String(g1t_actions::expr::to_text(&value)), |
| 1130 | }, |
| 1131 | }; |
| 1132 | inputs.insert(name.clone(), value); |
| 1133 | } |
| 1134 | Outcome::Ok(inputs) |
| 1135 | } |
| 1136 | |
| 1137 | #[cfg(test)] |
| 1138 | mod tests { |
| 1139 | use super::*; |
| 1140 | use g1t_contracts::work::{Pull, g1t_author}; |
| 1141 | |
| 1142 | #[test] |
| 1143 | fn every_event_a_workflow_runs_on_is_sent_to_this_queue() { |
| 1144 | for kind in g1t_contracts::webhooks::EVENT_TYPES { |
| 1145 | if !github_events(kind).is_empty() { |
| 1146 | assert!( |
| 1147 | g1t_contracts::subscribers::routed("SUBSCRIBER_ACTIONS", kind), |
| 1148 | "{kind} starts workflows but is not routed to actions (g1t_contracts::subscribers)" |
| 1149 | ); |
| 1150 | } |
| 1151 | } |
| 1152 | } |
| 1153 | use g1t_contracts::{Membership, PrincipalKind}; |
| 1154 | |
| 1155 | fn repo() -> Repo { |
| 1156 | serde_json::from_value(json!({ |
| 1157 | "id": "rep_1", "namespace": "acme", "name": "web", "description": null, "isPrivate": true, |
| 1158 | "ownerId": "ws_1", "defaultBranch": "main", "forkOf": null, "createdAt": "" |
| 1159 | })) |
| 1160 | .unwrap() |
| 1161 | } |
| 1162 | |
| 1163 | fn person(id: &str, username: &str) -> User { |
| 1164 | User { id: id.into(), username: username.into(), kind: PrincipalKind::User, ..User::default() } |
| 1165 | } |
| 1166 | |
| 1167 | fn made_for(asker: User) -> Pull { |
| 1168 | serde_json::from_value(json!({ |
| 1169 | "id": "pr_1", "repoId": "rep_1", "number": 14, "issue": 12, "title": "Fix it", "body": null, |
| 1170 | "agent": "g1t", "runtime": "hosted", "status": "open", |
| 1171 | "fork": { "namespace": "pulls", "name": "pr_1" }, "forkRepoId": "rep_f", |
| 1172 | "branch": null, "headCommit": "abc", "mergeBase": null, "mergedBy": null, "mergedAt": null, |
| 1173 | "supersededBy": null, "checkStatus": null, |
| 1174 | "author": g1t_author(), "requestedBy": asker, |
| 1175 | "createdAt": "", "updatedAt": "" |
| 1176 | })) |
| 1177 | .unwrap() |
| 1178 | } |
| 1179 | |
| 1180 | #[test] |
| 1181 | fn g1t_s_change_for_someone_is_trusted_as_they_are() { |
| 1182 | // Stored people carry no memberships, so identity is asked about |
| 1183 | // them; being g1t's change gives it nothing more. |
| 1184 | let pull = made_for(person("usr_2", "ana")); |
| 1185 | assert!(!trusted_outright(pull.owner(), &repo())); |
| 1186 | // Someone known to be able to push is trusted at once. |
| 1187 | let mut member = person("usr_1", "syntaqx"); |
| 1188 | member.workspaces.push(Membership::member("acme")); |
| 1189 | let pull = made_for(member); |
| 1190 | assert!(trusted_outright(pull.owner(), &repo())); |
| 1191 | } |
| 1192 | |
| 1193 | #[test] |
| 1194 | fn the_payload_names_g1t_as_its_user_and_who_asked_for_it() { |
| 1195 | let pull = made_for(person("usr_1", "syntaqx")); |
| 1196 | let event = payload::pull(&repo(), &pull); |
| 1197 | assert_eq!(event["user"]["login"], "g1t"); |
| 1198 | assert_eq!(event["user"]["type"], "Bot"); |
| 1199 | assert_eq!(event["requested_by"]["login"], "syntaqx"); |
| 1200 | assert_eq!(event["requested_by"]["type"], "User"); |
| 1201 | let as_issue = payload::pull_as_issue(&repo(), &pull); |
| 1202 | assert_eq!(as_issue["user"]["login"], "g1t"); |
| 1203 | assert_eq!(as_issue["requested_by"]["login"], "syntaqx"); |
| 1204 | } |
| 1205 | |
| 1206 | #[test] |
| 1207 | fn releases_deployments_and_deleted_comments_read_as_githubs() { |
| 1208 | let release = payload::release( |
| 1209 | &repo(), |
| 1210 | &json!({ "id": "rel_1", "tagName": "v1.2.0", "target": "abc", "name": null, "body": "Notes", "draft": false, |
| 1211 | "prerelease": true, "author": "ana", "createdAt": "2026-10-08T00:00:00Z", "publishedAt": "2026-10-08T00:00:00Z" }), |
| 1212 | ); |
| 1213 | assert_eq!(release["tag_name"], "v1.2.0"); |
| 1214 | assert_eq!(release["name"], "v1.2.0"); |
| 1215 | assert_eq!(release["prerelease"], true); |
| 1216 | assert_eq!(release["author"]["login"], "ana"); |
| 1217 | assert_eq!(release["html_url"], "https://g1t.sh/acme/web/releases/tag/v1.2.0"); |
| 1218 | let deployment = json!({ "id": "dep_1", "sha": "abc", "ref": "main", "environment": "staging", "creator": "ana", |
| 1219 | "production_environment": false, "created_at": "t", "updated_at": "t" }); |
| 1220 | let status = payload::deployment_status(&repo(), &json!({ "id": "dst_1", "state": "success", "environment_url": "https://s.example", "log_url": null, "creator": "g1t", "created_at": "t" }), &deployment); |
| 1221 | assert_eq!(status["state"], "success"); |
| 1222 | assert_eq!(status["environment"], "staging"); |
| 1223 | assert_eq!(status["environment_url"], "https://s.example"); |
| 1224 | assert_eq!(payload::deployment(&repo(), &deployment)["payload"], json!({})); |
| 1225 | let gone = payload::deleted_comment(&repo(), 7, &json!({ "id": "cmt_1", "body": "hi", "author": { "id": "usr_1", "username": "bo" }, "createdAt": "t" }), true); |
| 1226 | assert_eq!(gone["user"]["login"], "bo"); |
| 1227 | assert_eq!(gone["html_url"], "https://g1t.sh/acme/web/pull/7#cmt_1"); |
| 1228 | assert!(is_commit("0123456789abcdef0123456789abcdef01234567")); |
| 1229 | assert!(!is_commit("main")); |
| 1230 | } |
| 1231 | |
| 1232 | #[test] |
| 1233 | fn a_pull_request_names_its_own_base_labels_and_milestone() { |
| 1234 | let mut pull = made_for(person("usr_1", "syntaqx")); |
| 1235 | let event = payload::pull(&repo(), &pull); |
| 1236 | assert_eq!(event["base"]["ref"], repo().default_branch); |
| 1237 | pull.base = Some("release/1.x".into()); |
| 1238 | pull.labels = vec!["bug".into()]; |
| 1239 | pull.milestone = Some(g1t_contracts::work::MilestoneRef { number: 2, title: "1.1".into() }); |
| 1240 | let event = payload::pull(&repo(), &pull); |
| 1241 | assert_eq!(event["base"]["ref"], "release/1.x"); |
| 1242 | assert_eq!(event["labels"], serde_json::json!([{ "name": "bug" }])); |
| 1243 | assert_eq!(event["milestone"]["title"], "1.1"); |
| 1244 | let mut labeled = serde_json::json!({ "action": "labeled" }); |
| 1245 | payload::changed(&mut labeled, &serde_json::json!({ "label": { "name": "bug", "color": "d73a4a" } })); |
| 1246 | assert_eq!(labeled["label"]["color"], "d73a4a"); |
| 1247 | } |
| 1248 | } |