flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/services/actions/src/trigger.rs

870 lines39,145 bytesCodeBlame
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
5use g1t_actions::events::{RunInfo, github_events};
6use g1t_actions::workflow::{self, Trigger, Workflow};
7use g1t_contracts::access::{self, Capability};
8use g1t_contracts::actions::{DispatchArgs, WorkflowRun};
9use g1t_contracts::events::Event;
10use g1t_contracts::identity::{AGENT_ID, AGENT_NAME, UsernamesArgs};
11use g1t_contracts::repos::{Commit, CompareArgs, Comparison, LogArgs, Repo, RepoPath};
12use g1t_contracts::work::{IssueDetail, PullDetail, ViewArgs};
13use g1t_contracts::{FailureCode, Outcome, User, new_id};
14use g1t_kit::now_ms;
15use serde_json::{Map, Value, json};
16use worker::Result;
17
18use crate::plan::NewRun;
19use crate::sync::{Read, WorkflowRow};
20use crate::{API, Actions, SITE, check, fail, payload};
21
22/// What an event is about, worked out once for every workflow it starts.
23struct Subject {
24 /// Where the workflow files are read, and at which commit.
25 source: RepoPath,
26 source_ref: Option<String>,
27 git_ref: String,
28 sha: String,
29 head_ref: Option<String>,
30 base_ref: Option<String>,
31 pull: Option<u32>,
32 /// The branch or tag for `branches`/`tags` filters; for pull requests,
33 /// the branch they merge into.
34 filter_ref: String,
35 /// The files it changes, for `paths` filters; `None` until needed.
36 paths: Option<Vec<String>>,
37 /// For a push, what to compare to find the files.
38 compare: Option<(Option<String>, String)>,
39 payload: Value,
40 title: String,
41 trusted: bool,
42}
43
44/// Whether whoever a pull request is for is trusted without asking
45/// identity: g1t's agent in work nobody asked it for, or someone whose
46/// role here is known to allow pushing.
47fn trusted_outright(owner: &User, repo: &Repo) -> bool {
48 owner.id == AGENT_ID || access::can(Some(owner), repo, Capability::Push)
49}
50
51impl Actions {
52 async fn username(&self, id: Option<&str>) -> Result<Option<String>> {
53 let Some(id) = id else { return Ok(None) };
54 if id == AGENT_ID {
55 return Ok(Some(AGENT_NAME.to_owned()));
56 }
57 let names: std::collections::HashMap<String, String> =
58 g1t_kit::call(&self.identity, "usernames", &UsernamesArgs { ids: vec![id.to_owned()] }).await?;
59 Ok(names.get(id).cloned())
60 }
61
62 /// Whether whoever a pull request is for (Pull::owner: whoever asked
63 /// g1t for it, or its author) could push to the repository, so its
64 /// runs get the secrets and a token. Anyone else's, a reader's included
65 /// (who may open one on a private repository too), runs without them.
66 /// A change g1t made for someone is trusted as they are.
67 async fn insider(&self, owner: &User, repo: &Repo, ws: &User) -> Result<bool> {
68 if trusted_outright(owner, repo) {
69 return Ok(true);
70 }
71 // Stored authors carry no memberships or grants: ask identity, as
72 // the workspace (which may see anyone's permission).
73 let permission: Outcome<access::PermissionInfo> = g1t_kit::call(
74 &self.identity,
75 "collaborator_permission",
76 &access::CollaboratorPermissionArgs {
77 viewer: Some(ws.clone()),
78 path: RepoPath { namespace: repo.namespace.clone(), name: repo.name.clone() },
79 username: owner.username.clone(),
80 },
81 )
82 .await?;
83 Ok(permission
84 .into_result()
85 .ok()
86 .and_then(|info| info.role)
87 .is_some_and(|role| access::allows(role, Capability::Push)))
88 }
89
90 async fn commits(&self, repo: &Repo, actor: &User, after: &str, before: Option<&str>) -> Result<Vec<Commit>> {
91 let log: Outcome<Vec<Commit>> = g1t_kit::call(
92 &self.repos,
93 "log",
94 &LogArgs {
95 path: RepoPath {
96 namespace: repo.namespace.clone(),
97 name: repo.name.clone(),
98 },
99 viewer: Some(actor.clone()),
100 git_ref: Some(after.to_owned()),
101 limit: 20,
102 },
103 )
104 .await?;
105 let mut commits: Vec<Commit> = log.into_result().unwrap_or_default();
106 if let Some(before) = before
107 && let Some(at) = commits.iter().position(|commit| commit.hash == before)
108 {
109 commits.truncate(at);
110 }
111 // GitHub lists them oldest first, with the head commit last.
112 commits.reverse();
113 Ok(commits)
114 }
115
116 async fn changed_paths(&self, repo: &Repo, actor: &User, base: Option<String>, head: String) -> Result<Vec<String>> {
117 let compared: Outcome<Comparison> = g1t_kit::call(
118 &self.repos,
119 "compare",
120 &CompareArgs {
121 repo_id: repo.id.clone(),
122 viewer: Some(actor.clone()),
123 base,
124 head: Some(head),
125 },
126 )
127 .await?;
128 Ok(compared.into_result().map(|c| c.files.into_iter().map(|f| f.path).collect()).unwrap_or_default())
129 }
130
131 async fn default_head(&self, repo: &Repo) -> Result<Option<String>> {
132 g1t_kit::call(
133 &self.repos,
134 "head",
135 &g1t_contracts::repos::HeadArgs {
136 repo_id: repo.id.clone(),
137 branch: repo.default_branch.clone(),
138 },
139 )
140 .await
141 }
142
143 fn repo_path(repo: &Repo) -> RepoPath {
144 RepoPath {
145 namespace: repo.namespace.clone(),
146 name: repo.name.clone(),
147 }
148 }
149
150 /// The subject of an event of `kind`, as GitHub's `event_name`.
151 async fn subject(&self, event: &Event, event_name: &str, action: Option<&str>, repo: &Repo, ws: &User, sender: &str) -> Result<Option<Subject>> {
152 let path = Self::repo_path(repo);
153 let data = &event.data;
154 let on_default = |sha: String, payload: Value, title: String, pull: Option<u32>| Subject {
155 source: path.clone(),
156 source_ref: None,
157 git_ref: format!("refs/heads/{}", repo.default_branch),
158 sha,
159 head_ref: None,
160 base_ref: None,
161 pull,
162 filter_ref: format!("refs/heads/{}", repo.default_branch),
163 paths: None,
164 compare: None,
165 payload,
166 title,
167 trusted: true,
168 };
169 let view = |number: u32| ViewArgs {
170 repo: path.clone(),
171 number,
172 viewer: Some(ws.clone()),
173 after_seq: 0,
174 };
175 Ok(match event_name {
176 "push" => {
177 let (Some(git_ref), Some(after)) = (data["ref"].as_str(), data["after"].as_str()) else {
178 return Ok(None);
179 };
180 // The merge queue's states run merge_group workflows, not push ones.
181 if git_ref.starts_with("refs/heads/g1t-queue/") {
182 return Ok(None);
183 }
184 let before = data["before"].as_str();
185 let commits = self.commits(repo, ws, after, before).await?;
186 let title = commits.last().map(|c| c.message.lines().next().unwrap_or_default().to_owned()).unwrap_or_default();
187 let mut payload = payload::push(repo, git_ref, before, after, &commits, sender);
188 if let Some(head) = commits.last() {
189 payload["head_commit"] = payload::commit(repo, head);
190 }
191 Some(Subject {
192 source: path.clone(),
193 source_ref: Some(after.to_owned()),
194 git_ref: git_ref.to_owned(),
195 sha: after.to_owned(),
196 head_ref: None,
197 base_ref: None,
198 pull: None,
199 filter_ref: git_ref.to_owned(),
200 paths: None,
201 compare: Some((before.map(str::to_owned), after.to_owned())),
202 payload,
203 title,
204 trusted: true,
205 })
206 }
207 "pull_request" | "pull_request_target" | "pull_request_review" => {
208 let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) };
209 let detail: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?;
210 let Outcome::Ok(detail) = detail else { return Ok(None) };
211 let pull = &detail.pull;
212 let labels = detail.issue.as_ref().map(|i| i.labels.clone()).unwrap_or_default();
213 let mut payload = json!({
214 "action": action,
215 "number": pull.number,
216 "pull_request": payload::pull(repo, pull, &labels),
217 "repository": payload::repository(repo),
218 "sender": payload::user(sender),
219 });
220 if event_name == "pull_request_review" {
221 let review = detail.comments.iter().rev().find(|c| c.verdict.is_some());
222 payload["review"] = json!({
223 "state": review.and_then(|r| r.verdict).map(|v| format!("{v:?}").to_lowercase()),
224 "body": review.map(|r| r.body.clone()),
225 "user": review.map(|r| payload::user(&r.author.username)),
226 });
227 }
228 let trusted = self.insider(pull.owner(), repo, ws).await?;
229 let head_ref = payload::head_ref(pull);
230 if event_name == "pull_request_target" {
231 // In the base's context: its workflows, its head.
232 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
233 let mut subject = on_default(sha, payload, pull.title.clone(), Some(pull.number));
234 subject.head_ref = Some(head_ref);
235 subject.base_ref = Some(repo.default_branch.clone());
236 subject.paths = Some(pull.files.iter().map(|f| f.path.clone()).collect());
237 return Ok(Some(subject));
238 }
239 // A merged pull request's run is on the commit it landed as,
240 // in the repository; otherwise on its head, where that is.
241 let landed = match (action, data["commit"].as_str()) {
242 (Some("closed"), Some(commit)) => Some(commit.to_owned()),
243 _ => None,
244 };
245 let sha = match (&landed, data["commit"].as_str(), &pull.head_commit) {
246 (Some(commit), _, _) => commit.clone(),
247 (None, Some(commit), _) => commit.to_owned(),
248 (None, None, Some(head)) => head.clone(),
249 (None, None, None) => return Ok(None),
250 };
251 let source = match landed {
252 Some(_) => path.clone(),
253 None => pull.fork.clone().unwrap_or_else(|| path.clone()),
254 };
255 Some(Subject {
256 source,
257 source_ref: Some(sha.clone()),
258 git_ref: format!("refs/pull/{}/merge", pull.number),
259 sha,
260 head_ref: Some(head_ref),
261 base_ref: Some(repo.default_branch.clone()),
262 pull: Some(pull.number),
263 filter_ref: format!("refs/heads/{}", repo.default_branch),
264 paths: Some(pull.files.iter().map(|f| f.path.clone()).collect()),
265 compare: None,
266 payload,
267 title: pull.title.clone(),
268 trusted,
269 })
270 }
271 "workflow_run" => {
272 // A run of a workflow_run workflow does not start another,
273 // so two such workflows cannot set each other off.
274 if data["event"].as_str() == Some("workflow_run") {
275 return Ok(None);
276 }
277 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
278 let head_branch = data["ref"].as_str().unwrap_or_default().trim_start_matches("refs/heads/").to_owned();
279 let name = data["workflow"].as_str().unwrap_or_default();
280 let payload = json!({
281 "action": "completed",
282 "workflow_run": {
283 "id": data["runId"],
284 "name": name,
285 "path": data["path"],
286 "event": data["event"],
287 "status": "completed",
288 "conclusion": data["conclusion"],
289 "head_sha": data["sha"],
290 "head_branch": head_branch,
291 "run_number": data["number"],
292 "html_url": format!("{SITE}/{}/{}/actions/runs/{}", repo.namespace, repo.name, data["runId"].as_str().unwrap_or_default()),
293 "pull_requests": data["pull"].as_u64().map(|n| vec![json!({ "number": n })]).unwrap_or_default(),
294 },
295 "workflow": { "name": name, "path": data["path"] },
296 "repository": payload::repository(repo),
297 "sender": payload::user(sender),
298 });
299 let mut subject = on_default(sha, payload, format!("After {name}"), None);
300 // Branch filters apply to the branch the followed run was on.
301 subject.filter_ref = format!("refs/heads/{head_branch}");
302 Some(subject)
303 }
304 "issues" | "issue_comment" => {
305 let Some(number) = data["number"].as_u64().map(|n| n as u32) else { return Ok(None) };
306 let Some(sha) = self.default_head(repo).await? else { return Ok(None) };
307 let issue: Outcome<IssueDetail> = g1t_kit::call(&self.work, "get_issue", &view(number)).await?;
308 let (issue_json, comments, title, on_pull) = match issue {
309 Outcome::Ok(detail) => (payload::issue(repo, &detail.issue), detail.comments, detail.issue.title.clone(), false),
310 Outcome::Fail(_) => {
311 let pull: Outcome<PullDetail> = g1t_kit::call(&self.work, "get_pull", &view(number)).await?;
312 let Outcome::Ok(detail) = pull else { return Ok(None) };
313 let labels = detail.issue.as_ref().map(|i| i.labels.clone()).unwrap_or_default();
314 (payload::pull_as_issue(repo, &detail.pull, &labels), detail.comments, detail.pull.title.clone(), true)
315 }
316 };
317 let mut payload = json!({
318 "action": action,
319 "issue": issue_json,
320 "repository": payload::repository(repo),
321 "sender": payload::user(sender),
322 });
323 if event_name == "issue_comment" {
324 let comment_id = data["commentId"].as_str();
325 let comment = comments.iter().find(|c| Some(c.id.as_str()) == comment_id).or(comments.last());
326 match comment {
327 Some(comment) => payload["comment"] = payload::comment(repo, number, comment, on_pull),
328 None => return Ok(None),
329 }
330 }
331 Some(on_default(sha, payload, title, on_pull.then_some(number)))
332 }
333 _ => None,
334 })
335 }
336
337 pub async fn on_event(&self, event: &Event) -> Result<()> {
338 let Some(repo_id) = event.repo_id.as_deref() else { return Ok(()) };
339 let mapped = github_events(&event.kind);
340 let pushed_default = event.kind == "git.push" && event.data["defaultBranch"].as_bool() == Some(true);
341 if mapped.is_empty() && !pushed_default {
342 return Ok(());
343 }
344 let Some((repo, ws)) = self.repo_by_id(repo_id).await? else { return Ok(()) };
345 if pushed_default {
346 self.sync(&repo, &ws).await?;
347 }
348 let sender = self.username(event.actor.as_deref()).await?.unwrap_or_else(|| repo.namespace.clone());
349 for (event_name, action) in mapped {
350 let Some(mut subject) = self.subject(event, event_name, action, &repo, &ws, &sender).await? else {
351 continue;
352 };
353 let read = self.read_workflows(&subject.source, &ws, subject.source_ref.as_deref()).await?;
354 // A pull request's head runs each workflow once, however many
355 // events say it is there (marked ready, and pushed).
356 let key = match subject.pull {
357 Some(number) if event_name.starts_with("pull_request") && event_name != "pull_request_review" => {
358 let phase = if action == Some("closed") { "closed" } else { "open" };
359 format!("{event_name}:{number}:{}:{phase}", subject.sha)
360 }
361 _ => event.id.clone(),
362 };
363 self.start_matching(&repo, &ws, read, &mut subject, event_name, action, &key, event.actor.as_deref(), &sender)
364 .await?;
365 }
366 Ok(())
367 }
368
369 #[allow(clippy::too_many_arguments)]
370 async fn start_matching(
371 &self,
372 repo: &Repo,
373 ws: &User,
374 read: Read,
375 subject: &mut Subject,
376 event_name: &str,
377 action: Option<&str>,
378 event_key: &str,
379 actor_id: Option<&str>,
380 sender: &str,
381 ) -> Result<()> {
382 for file in read.files {
383 let parsed = workflow::parse(&file.source);
384 let workflow = match parsed {
385 Ok(workflow) => workflow,
386 Err(problem) => {
387 // A push shows a broken workflow as a failed run, as GitHub does.
388 if event_name == "push" && file.source.contains("on") {
389 self.record_invalid(repo, &file.path, &file.source, subject, event_key, actor_id, sender, &problem)
390 .await?;
391 }
392 continue;
393 }
394 };
395 let Some(trigger) = workflow.trigger(event_name) else { continue };
396 // workflow_run follows the workflows it names.
397 if event_name == "workflow_run" {
398 let followed = subject.payload["workflow_run"]["name"].as_str().unwrap_or_default();
399 if !trigger.workflows.iter().any(|name| name == followed) {
400 continue;
401 }
402 }
403 if !trigger.wants_type(action) || !self.passes(repo, ws, trigger, subject, event_name).await? {
404 continue;
405 }
406 if self.disabled(&repo.id, &file.path).await? {
407 continue;
408 }
409 self.create_run(NewRun {
410 repo: repo.clone(),
411 path: file.path,
412 source: file.source,
413 info: self.run_info(repo, &workflow, event_name, subject, sender, actor_id),
414 workflow,
415 action: action.map(str::to_owned),
416 pull: subject.pull,
417 title: subject.title.clone(),
418 inputs: Map::new(),
419 event_key: event_key.to_owned(),
420 actor_id: actor_id.map(str::to_owned),
421 actor: Some(sender.to_owned()),
422 trusted: subject.trusted,
423 })
424 .await?;
425 }
426 Ok(())
427 }
428
429 /// Whether the branch, tag and path filters let the event through.
430 async fn passes(&self, repo: &Repo, ws: &User, trigger: &Trigger, subject: &mut Subject, event_name: &str) -> Result<bool> {
431 let git_ref = subject.filter_ref.as_str();
432 if let Some(tag) = git_ref.strip_prefix("refs/tags/") {
433 // A tag push runs a workflow that filters tags, or filters nothing.
434 if trigger.tags.is_set() {
435 if !trigger.tags.allows(tag) {
436 return Ok(false);
437 }
438 } else if trigger.branches.is_set() {
439 return Ok(false);
440 }
441 // Paths are not checked for tags, as on GitHub.
442 return Ok(true);
443 }
444 let branch = git_ref.strip_prefix("refs/heads/").unwrap_or(git_ref);
445 if trigger.branches.is_set() {
446 if !trigger.branches.allows(branch) {
447 return Ok(false);
448 }
449 } else if event_name == "push" && trigger.tags.is_set() {
450 return Ok(false);
451 }
452 if trigger.paths.is_set() {
453 if subject.paths.is_none() {
454 let (base, head) = subject.compare.clone().unwrap_or((None, subject.sha.clone()));
455 subject.paths = Some(self.changed_paths(repo, ws, base, head).await?);
456 }
457 if !trigger.paths.allows_paths(subject.paths.as_deref().unwrap_or_default()) {
458 return Ok(false);
459 }
460 }
461 Ok(true)
462 }
463
464 async fn disabled(&self, repo_id: &str, path: &str) -> Result<bool> {
465 let row = self
466 .db
467 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND path = ?")
468 .bind(&[repo_id.into(), path.into()])?
469 .first::<WorkflowRow>(None)
470 .await?;
471 Ok(row.is_some_and(|row| row.state == "disabled"))
472 }
473
474 fn run_info(&self, repo: &Repo, workflow: &Workflow, event_name: &str, subject: &Subject, sender: &str, actor_id: Option<&str>) -> RunInfo {
475 RunInfo {
476 repository: format!("{}/{}", repo.namespace, repo.name),
477 repository_id: repo.id.clone(),
478 default_branch: repo.default_branch.clone(),
479 event_name: event_name.to_owned(),
480 event: subject.payload.clone(),
481 git_ref: subject.git_ref.clone(),
482 sha: subject.sha.clone(),
483 head_ref: subject.head_ref.clone(),
484 base_ref: subject.base_ref.clone(),
485 actor: sender.to_owned(),
486 actor_id: actor_id.unwrap_or_default().to_owned(),
487 triggering_actor: sender.to_owned(),
488 run_id: String::new(),
489 run_number: 0,
490 run_attempt: 1,
491 workflow: workflow.name.clone().unwrap_or_default(),
492 workflow_path: String::new(),
493 server_url: SITE.to_owned(),
494 api_url: API.to_owned(),
495 }
496 }
497
498 #[allow(clippy::too_many_arguments)]
499 async fn record_invalid(
500 &self,
501 repo: &Repo,
502 path: &str,
503 source: &str,
504 subject: &Subject,
505 event_key: &str,
506 actor_id: Option<&str>,
507 sender: &str,
508 problem: &str,
509 ) -> Result<()> {
510 let row = self.workflow_row(repo, path, path, source).await?;
511 self.record_failed_run(&row, subject.git_ref.as_str(), &subject.sha, event_key, actor_id, sender, problem).await
512 }
513
514 /// Scheduled workflows whose cron fires this minute, on the default branch.
515 pub async fn run_schedules(&self, minute: u64) -> Result<()> {
516 let rows = self
517 .db
518 .prepare("SELECT * FROM workflows WHERE state = 'active' AND crons != '[]' AND error IS NULL")
519 .all()
520 .await?
521 .results::<WorkflowRow>()?;
522 for row in rows {
523 let crons: Vec<String> = serde_json::from_str(&row.crons).unwrap_or_default();
524 let Some(cron) = crons.iter().find(|cron| g1t_actions::cron::Schedule::parse(cron).is_ok_and(|s| s.fires_at(minute))) else {
525 continue;
526 };
527 let Ok(workflow) = workflow::parse(&row.source) else { continue };
528 // Schedules wait while a repository is archived; a deleted one is not found.
529 let Some((repo, _ws)) = self.repo_by_id(&row.repo_id).await?.filter(|(repo, _)| !repo.archived()) else { continue };
530 let Some(sha) = self.default_head(&repo).await? else { continue };
531 let payload = json!({ "schedule": cron, "repository": payload::repository(&repo), "workflow": row.path });
532 let mut subject = Subject {
533 source: Self::repo_path(&repo),
534 source_ref: None,
535 git_ref: format!("refs/heads/{}", repo.default_branch),
536 sha,
537 head_ref: None,
538 base_ref: None,
539 pull: None,
540 filter_ref: String::new(),
541 paths: None,
542 compare: None,
543 payload,
544 title: format!("Scheduled: {cron}"),
545 trusted: true,
546 };
547 subject.filter_ref = subject.git_ref.clone();
548 let info = self.run_info(&repo, &workflow, "schedule", &subject, &repo.namespace, None);
549 self.create_run(NewRun {
550 repo: repo.clone(),
551 path: row.path.clone(),
552 source: row.source.clone(),
553 workflow,
554 info,
555 action: None,
556 pull: None,
557 title: subject.title.clone(),
558 inputs: Map::new(),
559 event_key: format!("schedule:{minute}"),
560 actor_id: None,
561 actor: None,
562 trusted: true,
563 })
564 .await?;
565 }
566 Ok(())
567 }
568
569 /// `dispatch`: someone with the Write role runs a workflow that has
570 /// `workflow_dispatch`.
571 pub async fn dispatch(&self, a: DispatchArgs) -> Result<Outcome<WorkflowRun>> {
572 let repo = check!(self.may(&a.actor, &a.repo, Capability::Run).await?);
573 if repo.archived() {
574 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
575 }
576 let Some(ws) = self.workspace_actor(&repo.namespace).await? else {
577 return Ok(fail(FailureCode::NotFound, "There is no such workspace."));
578 };
579 let git_ref = a.git_ref.clone().unwrap_or_else(|| repo.default_branch.clone());
580 let full_ref = if git_ref.starts_with("refs/") {
581 git_ref.clone()
582 } else {
583 // A branch if there is one by that name, otherwise a tag.
584 let branches: Outcome<Vec<g1t_contracts::repos::Branch>> = g1t_kit::call(
585 &self.repos,
586 "branches",
587 &g1t_contracts::repos::BranchesArgs {
588 path: Self::repo_path(&repo),
589 viewer: Some(ws.clone()),
590 },
591 )
592 .await?;
593 let is_branch = branches.into_result().unwrap_or_default().iter().any(|branch| branch.name == git_ref);
594 format!("refs/{}/{git_ref}", if is_branch { "heads" } else { "tags" })
595 };
596 let short = full_ref.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/").to_owned();
597 let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&short)).await?;
598 let Some(sha) = read.head.clone() else {
599 return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}.")));
600 };
601 // A workflow is named by its file (`build.yml`), its path, or its id
602 // (`wfl_…`), which stands for the path it was read from.
603 let by_id = if a.workflow.starts_with("wfl_") {
604 self.db
605 .prepare("SELECT * FROM workflows WHERE repo_id = ? AND id = ?")
606 .bind(&[repo.id.as_str().into(), a.workflow.as_str().into()])?
607 .first::<WorkflowRow>(None)
608 .await?
609 .map(|row| row.path)
610 } else {
611 None
612 };
613 let named = by_id.as_deref().unwrap_or(&a.workflow);
614 let wanted = named.trim_start_matches(".g1t/workflows/");
615 let Some(file) = read.files.iter().find(|file| {
616 file.path.rsplit('/').next() == Some(wanted) || file.path == named
617 }) else {
618 return Ok(fail(FailureCode::NotFound, format!("There is no workflow {wanted} on {short}.")));
619 };
620 let workflow = match workflow::parse(&file.source) {
621 Ok(workflow) => workflow,
622 Err(problem) => return Ok(fail(FailureCode::Invalid, format!("The workflow does not read: {problem}"))),
623 };
624 let Some(trigger) = workflow.trigger("workflow_dispatch") else {
625 return Ok(fail(FailureCode::Invalid, "That workflow cannot be run by hand: it has no `workflow_dispatch` trigger."));
626 };
627 let inputs = check!(dispatch_inputs(trigger, &a.inputs));
628 let payload = json!({
629 "inputs": inputs,
630 "ref": full_ref,
631 "repository": payload::repository(&repo),
632 "sender": payload::user(&a.actor.username),
633 "workflow": file.path,
634 });
635 let subject = Subject {
636 source: Self::repo_path(&repo),
637 source_ref: Some(sha.clone()),
638 git_ref: full_ref.clone(),
639 sha,
640 head_ref: None,
641 base_ref: None,
642 pull: None,
643 filter_ref: full_ref,
644 paths: None,
645 compare: None,
646 payload,
647 title: format!("{} run by {}", workflow.display_name(&file.path), a.actor.username),
648 trusted: true,
649 };
650 let info = self.run_info(&repo, &workflow, "workflow_dispatch", &subject, &a.actor.username, Some(&a.actor.id));
651 let created = self
652 .create_run(NewRun {
653 repo: repo.clone(),
654 path: file.path.clone(),
655 source: file.source.clone(),
656 workflow,
657 info,
658 action: None,
659 pull: None,
660 title: subject.title.clone(),
661 inputs,
662 event_key: format!("dispatch:{}", new_id("dsp", now_ms())),
663 actor_id: Some(a.actor.id.clone()),
664 actor: Some(a.actor.username.clone()),
665 trusted: true,
666 })
667 .await?;
668 match created {
669 Some(id) => self.run_summary(&id).await,
670 None => Ok(fail(FailureCode::Conflict, "It did not start.")),
671 }
672 }
673}
674
675#[derive(serde::Deserialize)]
676#[serde(rename_all = "camelCase")]
677pub struct MergeGroupArgs {
678 pub repo_id: String,
679 pub entry: String,
680 pub sha: String,
681 pub head_ref: String,
682 #[serde(default)]
683 pub base_sha: Option<String>,
684 pub number: u32,
685 #[serde(default)]
686 pub ahead: Vec<u32>,
687}
688
689impl Actions {
690 /// `merge_group`: the merge queue built a state and its checks passed.
691 /// Starts the workflows that run `on: merge_group` on it, as GitHub's
692 /// queue does, and says how many started; the queue waits for their
693 /// statuses on that commit.
694 pub async fn merge_group(&self, a: MergeGroupArgs) -> Result<Outcome<Value>> {
695 let Some((repo, ws)) = self.repo_by_id(&a.repo_id).await? else {
696 return Ok(Outcome::Ok(json!({ "runs": 0 })));
697 };
698 let read = self.read_workflows(&Self::repo_path(&repo), &ws, Some(&a.sha)).await?;
699 let head_commit = self.commits(&repo, &ws, &a.sha, None).await?.pop();
700 let payload = json!({
701 "action": "checks_requested",
702 "merge_group": {
703 "head_sha": a.sha,
704 "head_ref": a.head_ref,
705 "base_sha": a.base_sha,
706 "base_ref": format!("refs/heads/{}", repo.default_branch),
707 "head_commit": head_commit.as_ref().map(|c| payload::commit(&repo, c)),
708 },
709 "repository": payload::repository(&repo),
710 "sender": payload::user(&repo.namespace),
711 });
712 let mut started = 0u32;
713 for file in read.files {
714 let Ok(workflow) = workflow::parse(&file.source) else { continue };
715 let Some(trigger) = workflow.trigger("merge_group") else { continue };
716 if !trigger.wants_type(Some("checks_requested")) || self.disabled(&repo.id, &file.path).await? {
717 continue;
718 }
719 // Branch filters on merge_group name the branch it merges into.
720 if trigger.branches.is_set() && !trigger.branches.allows(&repo.default_branch) {
721 continue;
722 }
723 let ahead = if a.ahead.is_empty() {
724 String::new()
725 } else {
726 format!(" after {}", a.ahead.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(", "))
727 };
728 let subject = Subject {
729 source: Self::repo_path(&repo),
730 source_ref: Some(a.sha.clone()),
731 git_ref: a.head_ref.clone(),
732 sha: a.sha.clone(),
733 head_ref: None,
734 base_ref: Some(repo.default_branch.clone()),
735 pull: Some(a.number),
736 filter_ref: format!("refs/heads/{}", repo.default_branch),
737 paths: None,
738 compare: None,
739 payload: payload.clone(),
740 title: format!("Merge queue: #{}{ahead}", a.number),
741 trusted: true,
742 };
743 let info = self.run_info(&repo, &workflow, "merge_group", &subject, &repo.namespace, None);
744 let created = self
745 .create_run(NewRun {
746 repo: repo.clone(),
747 path: file.path.clone(),
748 source: file.source.clone(),
749 workflow,
750 info,
751 action: Some("checks_requested".to_owned()),
752 pull: Some(a.number),
753 title: subject.title.clone(),
754 inputs: Map::new(),
755 event_key: format!("merge_group:{}:{}", a.entry, a.sha),
756 actor_id: None,
757 actor: None,
758 trusted: true,
759 })
760 .await?;
761 if created.is_some() {
762 started += 1;
763 }
764 }
765 Ok(Outcome::Ok(json!({ "runs": started })))
766 }
767}
768
769/// The inputs of a manual run: what was given, checked against the
770/// workflow's declared inputs, with their defaults filled in.
771fn dispatch_inputs(trigger: &Trigger, given: &Map<String, Value>) -> Outcome<Map<String, Value>> {
772 let mut inputs = Map::new();
773 for (name, spec) in &trigger.inputs {
774 let kind = spec.get("type").and_then(Value::as_str).unwrap_or("string");
775 let value = given.get(name).cloned().or_else(|| spec.get("default").cloned());
776 let required = spec.get("required").and_then(Value::as_bool).unwrap_or(false);
777 let value = match value {
778 Some(Value::Null) | None if required => return fail(FailureCode::Invalid, format!("The input `{name}` is required.")),
779 Some(Value::Null) | None => match kind {
780 "boolean" => Value::Bool(false),
781 _ => Value::String(String::new()),
782 },
783 Some(value) => match kind {
784 "boolean" => Value::Bool(match &value {
785 Value::Bool(flag) => *flag,
786 Value::String(text) => text == "true",
787 _ => false,
788 }),
789 "number" => match &value {
790 Value::Number(_) => value,
791 Value::String(text) => match text.parse::<f64>().ok().and_then(serde_json::Number::from_f64) {
792 Some(number) => Value::Number(number),
793 None => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
794 },
795 _ => return fail(FailureCode::Invalid, format!("The input `{name}` is a number.")),
796 },
797 "choice" => {
798 let text = g1t_actions::expr::to_text(&value);
799 let options: Vec<String> =
800 spec.get("options").and_then(Value::as_array).map(|o| o.iter().map(g1t_actions::expr::to_text).collect()).unwrap_or_default();
801 if !options.is_empty() && !options.contains(&text) {
802 return fail(FailureCode::Invalid, format!("The input `{name}` is one of {}.", options.join(", ")));
803 }
804 Value::String(text)
805 }
806 _ => Value::String(g1t_actions::expr::to_text(&value)),
807 },
808 };
809 inputs.insert(name.clone(), value);
810 }
811 Outcome::Ok(inputs)
812}
813
814#[cfg(test)]
815mod tests {
816 use super::*;
817 use g1t_contracts::work::{Pull, g1t_author};
818 use g1t_contracts::{Membership, PrincipalKind};
819
820 fn repo() -> Repo {
821 serde_json::from_value(json!({
822 "id": "rep_1", "namespace": "acme", "name": "web", "description": null, "isPrivate": true,
823 "ownerId": "ws_1", "defaultBranch": "main", "forkOf": null, "createdAt": ""
824 }))
825 .unwrap()
826 }
827
828 fn person(id: &str, username: &str) -> User {
829 User { id: id.into(), username: username.into(), kind: PrincipalKind::User, ..User::default() }
830 }
831
832 fn made_for(asker: User) -> Pull {
833 serde_json::from_value(json!({
834 "id": "pr_1", "repoId": "rep_1", "number": 14, "issue": 12, "title": "Fix it", "body": null,
835 "agent": "g1t", "runtime": "hosted", "status": "open",
836 "fork": { "namespace": "pulls", "name": "pr_1" }, "forkRepoId": "rep_f",
837 "branch": null, "headCommit": "abc", "mergeBase": null, "mergedBy": null, "mergedAt": null,
838 "supersededBy": null, "checkStatus": null,
839 "author": g1t_author(), "requestedBy": asker,
840 "createdAt": "", "updatedAt": ""
841 }))
842 .unwrap()
843 }
844
845 #[test]
846 fn g1t_s_change_for_someone_is_trusted_as_they_are() {
847 // Stored people carry no memberships, so identity is asked about
848 // them; being g1t's change gives it nothing more.
849 let pull = made_for(person("usr_2", "ana"));
850 assert!(!trusted_outright(pull.owner(), &repo()));
851 // Someone known to be able to push is trusted at once.
852 let mut member = person("usr_1", "syntaqx");
853 member.workspaces.push(Membership::member("acme"));
854 let pull = made_for(member);
855 assert!(trusted_outright(pull.owner(), &repo()));
856 }
857
858 #[test]
859 fn the_payload_names_g1t_as_its_user_and_who_asked_for_it() {
860 let pull = made_for(person("usr_1", "syntaqx"));
861 let event = payload::pull(&repo(), &pull, &[]);
862 assert_eq!(event["user"]["login"], "g1t");
863 assert_eq!(event["user"]["type"], "Bot");
864 assert_eq!(event["requested_by"]["login"], "syntaqx");
865 assert_eq!(event["requested_by"]["type"], "User");
866 let as_issue = payload::pull_as_issue(&repo(), &pull, &[]);
867 assert_eq!(as_issue["user"]["login"], "g1t");
868 assert_eq!(as_issue["requested_by"]["login"], "syntaqx");
869 }
870}