forge
Explore
Log in

Don't you dare go Hollow

forge

Clone
★ 0

0 watching0 forksRustAGPL-3.07.1 MiB490f099Tahinli7 hours ago322 commits

schedule.rs1298 lines, 42.9 KiBHistoryRawDownload
1//! Turns pushes, tags, pull requests and manual requests into CI runs.
2//!
3//! Every entry point reads `.forge/ci.toml` at the commit it runs (64 KiB cap). No file means no
4//! run. A file that does not parse gives an Error run with the message in `config_error`, plus a
5//! `ci/config` status. A valid file gives one run whose jobs are created in dependency order.
6
7use forge_ci::config::{CiConfig, Event, parse_config};
8use forge_core::authz::{Action, authorize};
9use forge_core::ci::{CiRun, NewJob};
10use forge_core::store::commit_status::StatusState;
11use forge_core::{PullRequest, Repo};
12use forge_git::browse::{peel_to_commit, read_blob, resolve_commit};
13use tokio::io::AsyncWriteExt;
14
15use super::api::fit_to_cap;
16use super::{log_path, publish, sync_run_statuses};
17use crate::internal::is_zero_oid;
18use crate::state::AppState;
19
20/// The workflow file, relative to the repo root.
21pub const CONFIG_PATH: &str = ".forge/ci.toml";
22/// Largest workflow file read, in bytes.
23const MAX_CONFIG_BYTES: usize = 64 * 1024;
24/// Most config warnings written to each job log. The rest are only in the tracing output.
25const MAX_WARNING_LINES: usize = 20;
26const MIB: u64 = 1024 * 1024;
27
28/// A job ready to store: name, `JobSpec` as JSON, and its needs.
29type PlannedJob = (String, String, Vec<String>);
30
31/// What `.forge/ci.toml` held at one commit.
32pub(super) enum Loaded {
33 Missing,
34 Invalid(String),
35 Valid(CiConfig),
36}
37
38/// What a request should do with the loaded config.
39enum Plan {
40 /// No workflow file at this commit.
41 Missing,
42 /// The file is valid but this event does not trigger it.
43 NotTriggered,
44 /// Create a run with these jobs, or an Error run when `config_error` is set. `warnings` are the
45 /// config's ignored keys, written to the start of every job log.
46 Run {
47 jobs: Vec<PlannedJob>,
48 config_error: Option<String>,
49 warnings: Vec<String>,
50 /// `[on] cancel_superseded`: a push cancels the older live runs on its branch.
51 cancel_superseded: bool,
52 },
53}
54
55/// The inputs of one run to create.
56struct Request<'a> {
57 repo: &'a Repo,
58 trigger: &'static str,
59 git_ref: &'a str,
60 commit: &'a str,
61 pull_number: Option<i64>,
62 actor_id: &'a str,
63 needs_approval: bool,
64}
65
66/// A branch or tag update. Called from `post_update::after_ref_update` for every update of
67/// `refs/heads/*` or `refs/tags/*`, including pull mirror updates (with an empty actor). Deletions
68/// are ignored. Failures are logged; they never fail the push.
69pub async fn on_ref_update(
70 state: &AppState,
71 repo: &Repo,
72 actor_id: &str,
73 refname: &str,
74 new_oid: &str,
75) {
76 if !state.live().ci.enabled || is_zero_oid(new_oid) {
77 return;
78 }
79 let (trigger, event) = if let Some(branch) = refname.strip_prefix("refs/heads/") {
80 ("push", Event::Push { branch })
81 } else if let Some(tag) = refname.strip_prefix("refs/tags/") {
82 ("tag", Event::Tag { tag })
83 } else {
84 return;
85 };
86 let result = async {
87 // An annotated tag's ref names a tag object: the run, its statuses and any release are
88 // for the commit it points at.
89 let Some(commit) = peeled_commit(state, &repo.id, new_oid).await else {
90 return forge_core::Result::Ok(());
91 };
92 let new_oid = commit.as_str();
93 let loaded = load(state, &repo.id, new_oid).await;
94 if let Plan::Run {
95 jobs,
96 config_error,
97 warnings,
98 cancel_superseded,
99 } = plan_for(loaded, &event)?
100 {
101 let run = create(
102 state,
103 Request {
104 repo,
105 trigger,
106 git_ref: refname,
107 commit: new_oid,
108 pull_number: None,
109 actor_id,
110 needs_approval: false,
111 },
112 jobs,
113 config_error.as_deref(),
114 &warnings,
115 )
116 .await?;
117 if cancel_superseded && trigger == "push" {
118 cancel_superseded_runs(state, &run).await?;
119 }
120 }
121 forge_core::Result::Ok(())
122 }
123 .await;
124 if let Err(e) = result {
125 tracing::error!(error = %e, repo_id = %repo.id, refname, "ci: scheduling a push failed");
126 }
127}
128
129/// A pull request was opened, synchronized (its head moved) or reopened. The config is read at
130/// the head commit. A fork head, or an author without Write on the base repo, creates the run in
131/// WaitingApproval: its jobs wait until someone approves it.
132pub async fn on_pull_event(state: &AppState, repo: &Repo, pull: &PullRequest, actor_id: &str) {
133 if !state.live().ci.enabled {
134 return;
135 }
136 if let Err(e) = pull_run(state, repo, pull, actor_id).await {
137 tracing::error!(error = %e, repo_id = %repo.id, number = pull.issue.number, "ci: scheduling a pull request failed");
138 }
139}
140
141async fn pull_run(
142 state: &AppState,
143 repo: &Repo,
144 pull: &PullRequest,
145 actor_id: &str,
146) -> forge_core::Result<()> {
147 let loaded = load(state, &repo.id, &pull.head_oid).await;
148 let Plan::Run {
149 jobs,
150 config_error,
151 warnings,
152 ..
153 } = plan_for(loaded, &Event::PullRequest)?
154 else {
155 return Ok(());
156 };
157 let needs_approval = needs_approval(state, repo, pull).await?;
158 let git_ref = format!("refs/pull/{}/head", pull.issue.number);
159 create(
160 state,
161 Request {
162 repo,
163 trigger: "pull_request",
164 git_ref: &git_ref,
165 commit: &pull.head_oid,
166 pull_number: Some(pull.issue.number),
167 actor_id,
168 needs_approval,
169 },
170 jobs,
171 config_error.as_deref(),
172 &warnings,
173 )
174 .await?;
175 Ok(())
176}
177
178/// Starts a run for `branch` by hand. Fails when the branch does not exist, when there is no
179/// workflow file, or when the workflow does not allow manual runs. A file that does not parse
180/// gives an Error run, as a push does.
181pub async fn manual_run(
182 state: &AppState,
183 repo: &Repo,
184 branch: &str,
185 actor_id: &str,
186) -> forge_core::Result<CiRun> {
187 if !state.live().ci.enabled {
188 return Err(forge_core::Error::Invalid(
189 "CI is disabled on this instance".into(),
190 ));
191 }
192 let git_ref = format!("refs/heads/{branch}");
193 let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id)
194 .map_err(|e| forge_core::Error::Git(e.to_string()))?;
195 // `resolve_commit` takes the short branch name and looks under refs/heads/ first.
196 let short = branch.to_owned();
197 let Some(commit) = blocking(move || resolve_commit(&repo_dir, &short)).await? else {
198 return Err(forge_core::Error::NotFound);
199 };
200 let loaded = load(state, &repo.id, &commit).await;
201 match plan_for(loaded, &Event::Manual)? {
202 Plan::Run {
203 jobs,
204 config_error,
205 warnings,
206 ..
207 } => {
208 create(
209 state,
210 Request {
211 repo,
212 trigger: "manual",
213 git_ref: &git_ref,
214 commit: &commit,
215 pull_number: None,
216 actor_id,
217 needs_approval: false,
218 },
219 jobs,
220 config_error.as_deref(),
221 &warnings,
222 )
223 .await
224 }
225 Plan::NotTriggered => Err(forge_core::Error::Invalid(
226 "manual runs are not enabled in .forge/ci.toml".into(),
227 )),
228 Plan::Missing => Err(forge_core::Error::Invalid(
229 "this branch has no .forge/ci.toml".into(),
230 )),
231 }
232}
233
234/// The head commit of the repo's default branch and the workflow at it. `None` when the branch
235/// has no commits (or cannot be read, which is logged).
236pub(super) async fn default_head_config(state: &AppState, repo: &Repo) -> Option<(String, Loaded)> {
237 let repo_dir = forge_git::repo::repo_path(&state.git.data_dir, &repo.id).ok()?;
238 let short = repo.default_branch.clone();
239 let commit = match blocking(move || resolve_commit(&repo_dir, &short)).await {
240 Ok(commit) => commit?,
241 Err(e) => {
242 tracing::error!(error = %e, repo_id = %repo.id, "ci: resolving the default branch failed");
243 return None;
244 }
245 };
246 let loaded = load(state, &repo.id, &commit).await;
247 Some((commit, loaded))
248}
249
250/// The `[on] schedule` entries of the workflow on the repo's default branch. Empty when there is
251/// no valid workflow.
252pub async fn schedules_of(state: &AppState, repo: &Repo) -> Vec<String> {
253 match default_head_config(state, repo).await {
254 Some((_, Loaded::Valid(cfg))) => cfg.on.schedule,
255 _ => Vec::new(),
256 }
257}
258
259/// Queues a `schedule` run of `commit` on the default branch. A config that does not parse gives
260/// an Error run, as a push does. Nothing happens when the workflow has no schedule.
261pub(super) async fn scheduled_run(
262 state: &AppState,
263 repo: &Repo,
264 commit: &str,
265 loaded: Loaded,
266) -> forge_core::Result<Option<CiRun>> {
267 let Plan::Run {
268 jobs,
269 config_error,
270 warnings,
271 ..
272 } = plan_for(loaded, &Event::Schedule)?
273 else {
274 return Ok(None);
275 };
276 let git_ref = format!("refs/heads/{}", repo.default_branch);
277 let run = create(
278 state,
279 Request {
280 repo,
281 trigger: "schedule",
282 git_ref: &git_ref,
283 commit,
284 pull_number: None,
285 // The column needs a user; the repo owner stands in. The pages show no actor for these.
286 actor_id: &repo.owner_id,
287 needs_approval: false,
288 },
289 jobs,
290 config_error.as_deref(),
291 &warnings,
292 )
293 .await?;
294 Ok(Some(run))
295}
296
297/// Starts the run that tests a merge queue candidate `commit` of `branch`, named by the temporary
298/// ref `test_ref`. The workflow of the candidate decides: `[on] merge_queue`, or the `push` jobs of
299/// `branch`. `Ok(None)` when no run is wanted (no workflow, or it does not run for the candidate).
300pub async fn merge_queue_run(
301 state: &AppState,
302 repo: &Repo,
303 test_ref: &str,
304 branch: &str,
305 commit: &str,
306 actor_id: &str,
307 pull_number: i64,
308) -> forge_core::Result<Option<CiRun>> {
309 if !state.live().ci.enabled {
310 return Ok(None);
311 }
312 let loaded = load(state, &repo.id, commit).await;
313 let Plan::Run {
314 jobs,
315 config_error,
316 warnings,
317 ..
318 } = plan_for(loaded, &Event::MergeQueue { branch })?
319 else {
320 return Ok(None);
321 };
322 let run = create(
323 state,
324 Request {
325 repo,
326 trigger: "merge_queue",
327 git_ref: test_ref,
328 commit,
329 pull_number: Some(pull_number),
330 actor_id,
331 needs_approval: false,
332 },
333 jobs,
334 config_error.as_deref(),
335 &warnings,
336 )
337 .await?;
338 Ok(Some(run))
339}
340
341/// Creates the run, sets the statuses of its jobs (and `ci/config` for an error run), and wakes
342/// the runner claims when a job is queued.
343async fn create(
344 state: &AppState,
345 req: Request<'_>,
346 jobs: Vec<PlannedJob>,
347 config_error: Option<&str>,
348 warnings: &[String],
349) -> forge_core::Result<CiRun> {
350 let new_jobs: Vec<NewJob<'_>> = jobs
351 .iter()
352 .map(|(name, spec_json, needs)| NewJob {
353 name,
354 spec_json,
355 needs: needs.as_slice(),
356 })
357 .collect();
358 let run = state
359 .store
360 .create_run(
361 &req.repo.id,
362 req.trigger,
363 req.git_ref,
364 req.commit,
365 req.pull_number,
366 req.actor_id,
367 req.needs_approval,
368 &new_jobs,
369 config_error,
370 )
371 .await?;
372 state.ci_live.bump_repo(&run.repo_id);
373 state.store.set_run_warnings(&run.id, warnings).await?;
374 note_warnings(state, &run, warnings).await?;
375 if let Some(message) = config_error {
376 let url = format!(
377 "{}/{}/{}/ci/runs/{}",
378 state.config.base_url.trim_end_matches('/'),
379 req.repo.owner_name,
380 req.repo.name,
381 run.number
382 );
383 publish(
384 state,
385 req.repo,
386 &run,
387 "ci/config",
388 StatusState::Error,
389 message,
390 &url,
391 )
392 .await;
393 }
394 if sync_run_statuses(state, &run).await? {
395 state.ci_waker.notify_waiters();
396 }
397 Ok(run)
398}
399
400/// Cancels the queued and running push runs on the branch of `run` that are for older commits.
401/// Queued jobs are cancelled at once; running jobs stop at their next heartbeat.
402async fn cancel_superseded_runs(state: &AppState, run: &CiRun) -> forge_core::Result<()> {
403 let older = state
404 .store
405 .superseded_candidates(&run.repo_id, &run.git_ref, &run.commit_oid)
406 .await?;
407 for old in older.into_iter().filter(|old| old.number < run.number) {
408 let before = state.store.jobs_for_run(&old.id).await?;
409 state.store.request_cancel(&old.id).await?;
410 if let Err(e) = crate::ci::after_change(state, &old.id, &before).await {
411 tracing::error!(error = %e, run_id = %old.id, "ci: syncing a superseded run failed");
412 }
413 }
414 Ok(())
415}
416
417/// Writes the config warnings as `[forge] warning: ...` lines at the start of every job's log, and
418/// logs them. Runs before the runners are woken, so the lines come first. A failed write is logged
419/// and does not fail the run.
420async fn note_warnings(
421 state: &AppState,
422 run: &CiRun,
423 warnings: &[String],
424) -> forge_core::Result<()> {
425 if warnings.is_empty() {
426 return Ok(());
427 }
428 let mut text = String::new();
429 for warning in warnings {
430 tracing::warn!(run_id = %run.id, repo_id = %run.repo_id, "ci: {warning}");
431 }
432 for warning in warnings.iter().take(MAX_WARNING_LINES) {
433 text.push_str(&format!("[forge] warning: {warning}\n"));
434 }
435 let cap = state.live().ci.max_log_mb.saturating_mul(MIB);
436 for job in state.store.jobs_for_run(&run.id).await? {
437 let path = log_path(&state.config.data_dir, &job.id);
438 let current = match tokio::fs::metadata(&path).await {
439 Ok(meta) => meta.len(),
440 Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
441 Err(e) => {
442 tracing::error!(error = %e, job_id = %job.id, "ci: reading the job log failed");
443 continue;
444 }
445 };
446 let bytes = fit_to_cap(current, cap, text.as_bytes());
447 if bytes.is_empty() {
448 continue;
449 }
450 let written: std::io::Result<()> = async {
451 if let Some(parent) = path.parent() {
452 tokio::fs::create_dir_all(parent).await?;
453 }
454 let mut file = tokio::fs::OpenOptions::new()
455 .create(true)
456 .append(true)
457 .open(&path)
458 .await?;
459 file.write_all(&bytes).await?;
460 file.flush().await
461 }
462 .await;
463 if let Err(e) = written {
464 tracing::error!(error = %e, job_id = %job.id, "ci: writing the job log failed");
465 continue;
466 }
467 if let Err(e) = state.store.add_log_bytes(&job.id, bytes.len() as i64).await {
468 tracing::error!(error = %e, job_id = %job.id, "ci: counting the job log bytes failed");
469 continue;
470 }
471 state.ci_live.bump_job(&job.id);
472 }
473 Ok(())
474}
475
476/// Decides what a request does, given the loaded config and the event.
477fn plan_for(loaded: Loaded, event: &Event<'_>) -> forge_core::Result<Plan> {
478 match loaded {
479 Loaded::Missing => Ok(Plan::Missing),
480 Loaded::Invalid(message) => Ok(Plan::Run {
481 jobs: Vec::new(),
482 config_error: Some(message),
483 warnings: Vec::new(),
484 cancel_superseded: false,
485 }),
486 Loaded::Valid(cfg) => {
487 if !cfg.triggered_by(event) {
488 return Ok(Plan::NotTriggered);
489 }
490 Ok(Plan::Run {
491 jobs: plan_jobs(&cfg)?,
492 config_error: None,
493 warnings: cfg.warnings.clone(),
494 cancel_superseded: cfg.on.cancel_superseded,
495 })
496 }
497 }
498}
499
500/// The jobs of a valid config in dependency order, each with its spec as JSON.
501fn plan_jobs(cfg: &CiConfig) -> forge_core::Result<Vec<PlannedJob>> {
502 let mut jobs = Vec::new();
503 for name in cfg.job_order() {
504 let Some(spec) = cfg.jobs.get(name) else {
505 continue;
506 };
507 let spec_json =
508 serde_json::to_string(spec).map_err(|e| forge_core::Error::Invalid(e.to_string()))?;
509 jobs.push((name.to_owned(), spec_json, spec.needs.clone()));
510 }
511 Ok(jobs)
512}
513
514/// Reads and parses `.forge/ci.toml` at `commit` from the repo `repo_id`.
515/// The workflow at `commit`, when it is a valid file. Used by the release hook, which reads the
516/// config the run itself was made from.
517pub(super) async fn config_at(state: &AppState, repo_id: &str, commit: &str) -> Option<CiConfig> {
518 match load(state, repo_id, commit).await {
519 Loaded::Valid(config) => Some(config),
520 Loaded::Missing | Loaded::Invalid(_) => None,
521 }
522}
523
524/// The commit `oid` peels to, logging why when it names none.
525async fn peeled_commit(state: &AppState, repo_id: &str, oid: &str) -> Option<String> {
526 let dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) {
527 Ok(path) => path,
528 Err(e) => {
529 tracing::error!(error = %e, repo_id, "ci: bad repo path");
530 return None;
531 }
532 };
533 let rev = oid.to_owned();
534 match blocking(move || peel_to_commit(&dir, &rev)).await {
535 Ok(Some(commit)) => Some(commit),
536 Ok(None) => None, // a tag on a tree or blob: nothing to build
537 Err(e) => {
538 tracing::error!(error = %e, repo_id, oid, "ci: peeling the pushed ref failed");
539 None
540 }
541 }
542}
543
544async fn load(state: &AppState, repo_id: &str, commit: &str) -> Loaded {
545 let repo_dir = match forge_git::repo::repo_path(&state.git.data_dir, repo_id) {
546 Ok(path) => path,
547 Err(e) => {
548 tracing::error!(error = %e, repo_id, "ci: bad repo path");
549 return Loaded::Invalid(format!("could not read {CONFIG_PATH}"));
550 }
551 };
552 let (dir, rev) = (repo_dir, commit.to_owned());
553 let blob = match blocking(move || read_blob(&dir, &rev, CONFIG_PATH, MAX_CONFIG_BYTES)).await {
554 Ok(blob) => blob,
555 Err(e) => {
556 tracing::error!(error = %e, repo_id, commit, "ci: reading the workflow failed");
557 return Loaded::Invalid(format!("could not read {CONFIG_PATH}"));
558 }
559 };
560 let Some(blob) = blob else {
561 return Loaded::Missing;
562 };
563 if blob.truncated {
564 return Loaded::Invalid(format!("{CONFIG_PATH} is larger than 64 KiB"));
565 }
566 if blob.is_binary {
567 return Loaded::Invalid(format!("{CONFIG_PATH} is not text"));
568 }
569 let Ok(text) = String::from_utf8(blob.data) else {
570 return Loaded::Invalid(format!("{CONFIG_PATH} is not valid UTF-8"));
571 };
572 match parse_config(&text) {
573 Ok(cfg) => Loaded::Valid(cfg),
574 Err(e) => Loaded::Invalid(e.to_string()),
575 }
576}
577
578/// The trimmed workflow `name` in `.forge/ci.toml` at `commit`. `None` when the file is missing,
579/// does not parse, or has no name. Reads one git object, so the badge can call it per request.
580pub async fn workflow_name(state: &AppState, repo_id: &str, commit: &str) -> Option<String> {
581 match load(state, repo_id, commit).await {
582 Loaded::Valid(cfg) => cfg
583 .name
584 .map(|name| name.trim().to_owned())
585 .filter(|name| !name.is_empty()),
586 Loaded::Missing | Loaded::Invalid(_) => None,
587 }
588}
589
590/// Whether a pull request needs approval before its jobs run: a fork head, or an author who lacks
591/// Write on the base repo (or no longer exists).
592async fn needs_approval(
593 state: &AppState,
594 repo: &Repo,
595 pull: &PullRequest,
596) -> forge_core::Result<bool> {
597 if pull.head_repo_id.as_deref() != Some(repo.id.as_str()) {
598 return Ok(true);
599 }
600 let Some(author) = state.store.user_by_id(&pull.issue.author_id).await? else {
601 return Ok(true);
602 };
603 if author.is_org() {
604 return Ok(true);
605 }
606 let role = state.store.collaborator_role(&repo.id, &author.id).await?;
607 let org_role = state
608 .store
609 .org_repo_role(&repo.owner_id, &author.id, &repo.id)
610 .await?;
611 Ok(authorize(Some(&author), repo, role, org_role, Action::Write).is_err())
612}
613
614/// Runs blocking git work off the async runtime, mapping git and join errors to `forge_core`.
615async fn blocking<T, F>(work: F) -> forge_core::Result<T>
616where
617 F: FnOnce() -> forge_git::Result<T> + Send + 'static,
618 T: Send + 'static,
619{
620 match tokio::task::spawn_blocking(work).await {
621 Ok(Ok(value)) => Ok(value),
622 Ok(Err(e)) => Err(forge_core::Error::Git(e.to_string())),
623 Err(e) => Err(forge_core::Error::Git(format!("git task failed: {e}"))),
624 }
625}
626
627#[cfg(test)]
628pub(super) mod tests {
629 use std::path::{Path, PathBuf};
630 use std::time::Duration;
631
632 use forge_core::ci::{CiJob, CiRunner, JobState, RunState};
633 use forge_core::store::commit_status::{CommitStatus, StatusState};
634 use forge_core::time::stamp_after;
635 use forge_core::{User, Visibility};
636 use forge_git::repo::{init_bare, repo_path};
637 use tempfile::TempDir;
638
639 use super::*;
640 use crate::ci::log_path;
641 use crate::ci::reaper::{purge_once, reap_before};
642 use crate::post_update::after_ref_update;
643 use crate::test_support::test_state;
644
645 pub(in crate::ci) const ZERO: &str = "0000000000000000000000000000000000000000";
646
647 const CONFIG: &str = r#"
648[on]
649push = ["main"]
650pull_request = true
651
652[jobs.build]
653image = "alpine:3"
654run = "make"
655
656[jobs.test]
657image = "alpine:3"
658run = "make test"
659needs = ["build"]
660"#;
661
662 const CONFIG_GLOBS: &str = r#"
663[on]
664push = ["release/*"]
665
666[jobs.build]
667image = "alpine:3"
668run = "make"
669"#;
670
671 pub(in crate::ci) const CONFIG_TAGS: &str = r#"
672[on]
673push = []
674tags = ["v*"]
675
676[jobs.build]
677image = "alpine:3"
678run = "make"
679"#;
680
681 const CONFIG_ONE_JOB: &str = r#"
682[on]
683push = ["main"]
684
685[jobs.build]
686image = "alpine:3"
687run = "make"
688"#;
689
690 const CONFIG_NO_MANUAL: &str = r#"
691[on]
692push = ["main"]
693manual = false
694
695[jobs.build]
696image = "alpine:3"
697run = "make"
698"#;
699
700 pub(in crate::ci) fn git(dir: &Path, args: &[&str]) -> String {
701 let out = std::process::Command::new("git")
702 .arg("-C")
703 .arg(dir)
704 .args(args)
705 .env("GIT_AUTHOR_NAME", "test")
706 .env("GIT_AUTHOR_EMAIL", "test@example.com")
707 .env("GIT_COMMITTER_NAME", "test")
708 .env("GIT_COMMITTER_EMAIL", "test@example.com")
709 .output()
710 .expect("git runs");
711 assert!(
712 out.status.success(),
713 "git {args:?} failed: {}",
714 String::from_utf8_lossy(&out.stderr)
715 );
716 String::from_utf8_lossy(&out.stdout).trim().to_string()
717 }
718
719 pub(in crate::ci) struct Fixture {
720 pub(in crate::ci) _tmp: TempDir,
721 pub(in crate::ci) state: AppState,
722 pub(in crate::ci) repo: Repo,
723 pub(in crate::ci) owner: User,
724 pub(in crate::ci) bare: PathBuf,
725 pub(in crate::ci) work: PathBuf,
726 }
727
728 pub(in crate::ci) async fn fixture() -> Fixture {
729 let tmp = tempfile::tempdir().expect("tempdir");
730 let state = test_state(tmp.path()).await;
731 let owner = state
732 .store
733 .create_user("tahinli", None, "unused", false)
734 .await
735 .expect("user");
736 let repo = state
737 .store
738 .create_repo(&owner.id, "proj", "", Visibility::Private, "main")
739 .await
740 .expect("repo");
741 let bare = repo_path(&state.git.data_dir, &repo.id).expect("repo path");
742 init_bare(&state.git, &bare, "main")
743 .await
744 .expect("init bare");
745 let work = tmp.path().join("work");
746 git(tmp.path(), &["init", "-b", "main", "work"]);
747 Fixture {
748 _tmp: tmp,
749 state,
750 repo,
751 owner,
752 bare,
753 work,
754 }
755 }
756
757 /// Commits `files` in the work tree and returns the new commit.
758 pub(in crate::ci) fn commit(work: &Path, files: &[(&str, &str)]) -> String {
759 for (path, text) in files {
760 let full = work.join(path);
761 if let Some(parent) = full.parent() {
762 std::fs::create_dir_all(parent).expect("dirs");
763 }
764 std::fs::write(&full, text).expect("write");
765 git(work, &["add", path]);
766 }
767 git(work, &["commit", "--allow-empty", "-m", "change"]);
768 git(work, &["rev-parse", "HEAD"])
769 }
770
771 /// Makes `oid` the tip of `refname` in the bare repo. Fetch runs no hooks, unlike a push.
772 pub(in crate::ci) fn land(fx: &Fixture, oid: &str, refname: &str) {
773 let work = fx.work.to_str().expect("utf8 path");
774 git(
775 &fx.bare,
776 &["fetch", "--no-tags", work, &format!("+{oid}:{refname}")],
777 );
778 }
779
780 /// Commits `files`, lands them on `refname`, and runs the post-update hook for the update.
781 pub(in crate::ci) async fn push(fx: &Fixture, files: &[(&str, &str)], refname: &str) -> String {
782 let oid = commit(&fx.work, files);
783 land(fx, &oid, refname);
784 after_ref_update(&fx.state, &fx.repo, &fx.owner.id, refname, ZERO, &oid)
785 .await
786 .expect("post update");
787 oid
788 }
789
790 fn status<'a>(statuses: &'a [CommitStatus], context: &str) -> Option<&'a CommitStatus> {
791 statuses.iter().find(|s| s.context == context)
792 }
793
794 fn state_of(jobs: &[CiJob], name: &str) -> Option<JobState> {
795 jobs.iter().find(|j| j.name == name).map(|j| j.state)
796 }
797
798 pub(in crate::ci) async fn runs_total(fx: &Fixture) -> u64 {
799 fx.state
800 .store
801 .list_runs(&fx.repo.id, 1, 50)
802 .await
803 .expect("list runs")
804 .1
805 }
806
807 async fn runner(fx: &Fixture) -> CiRunner {
808 let token = fx
809 .state
810 .store
811 .create_registration_token(&fx.owner.id, 24)
812 .await
813 .expect("token");
814 let (runner, _secret) = fx
815 .state
816 .store
817 .register_runner(&token, "runner-1", &[])
818 .await
819 .expect("register");
820 runner
821 }
822
823 #[tokio::test]
824 async fn push_with_config_creates_run_and_pending_statuses() {
825 let fx = fixture().await;
826 let oid = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await;
827
828 let run = fx
829 .state
830 .store
831 .run_by_number(&fx.repo.id, 1)
832 .await
833 .expect("query")
834 .expect("run exists");
835 assert_eq!(run.trigger, "push");
836 assert_eq!(run.git_ref, "refs/heads/main");
837 assert_eq!(run.commit_oid, oid);
838 assert!(run.config_error.is_none());
839
840 let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs");
841 assert_eq!(state_of(&jobs, "build"), Some(JobState::Queued));
842 assert_eq!(state_of(&jobs, "test"), Some(JobState::Blocked));
843
844 let statuses = fx
845 .state
846 .store
847 .statuses_for(&fx.repo.id, &oid)
848 .await
849 .expect("statuses");
850 let build = status(&statuses, "ci/build").expect("ci/build status");
851 assert_eq!(build.state, StatusState::Pending);
852 let url = build.target_url.clone().unwrap_or_default();
853 let job = jobs.iter().find(|j| j.name == "build").expect("build job");
854 assert_eq!(
855 url,
856 format!("https://forge.test/tahinli/proj/ci/jobs/{}", job.id)
857 );
858 let test = status(&statuses, "ci/test").expect("ci/test status");
859 assert_eq!(test.state, StatusState::Pending);
860 }
861
862 #[tokio::test]
863 async fn unknown_config_keys_still_run_and_warn_in_each_job_log() {
864 let fx = fixture().await;
865 let text = format!("{CONFIG_ONE_JOB}\n[future]\nx = 1\n");
866 push(&fx, &[(CONFIG_PATH, text.as_str())], "refs/heads/main").await;
867
868 let run = fx
869 .state
870 .store
871 .run_by_number(&fx.repo.id, 1)
872 .await
873 .expect("query")
874 .expect("run exists");
875 assert!(run.config_error.is_none(), "unknown keys are not an error");
876 let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs");
877 assert_eq!(state_of(&jobs, "build"), Some(JobState::Queued));
878
879 for job in &jobs {
880 let log = std::fs::read_to_string(log_path(&fx.state.config.data_dir, &job.id))
881 .expect("job log");
882 assert!(
883 log.starts_with(
884 "[forge] warning: unknown key `future` ignored: this forge may be older than your ci.toml\n"
885 ),
886 "log was {log:?}"
887 );
888 }
889 }
890
891 #[tokio::test]
892 async fn no_file_means_no_run() {
893 let fx = fixture().await;
894 let oid = push(&fx, &[("README.md", "hello")], "refs/heads/main").await;
895 assert_eq!(runs_total(&fx).await, 0);
896 let statuses = fx
897 .state
898 .store
899 .statuses_for(&fx.repo.id, &oid)
900 .await
901 .expect("statuses");
902 assert!(statuses.is_empty());
903 }
904
905 #[tokio::test]
906 async fn bad_file_gives_error_run_and_config_status() {
907 let fx = fixture().await;
908 let oid = push(
909 &fx,
910 &[(CONFIG_PATH, "[jobs.build\nimage = ")],
911 "refs/heads/main",
912 )
913 .await;
914 let run = fx
915 .state
916 .store
917 .run_by_number(&fx.repo.id, 1)
918 .await
919 .expect("query")
920 .expect("run exists");
921 assert_eq!(run.state, RunState::Error);
922 assert!(run.config_error.is_some());
923 let jobs = fx.state.store.jobs_for_run(&run.id).await.expect("jobs");
924 assert!(jobs.is_empty());
925
926 let statuses = fx
927 .state
928 .store
929 .statuses_for(&fx.repo.id, &oid)
930 .await
931 .expect("statuses");
932 let config = status(&statuses, "ci/config").expect("ci/config status");
933 assert_eq!(config.state, StatusState::Error);
934 assert!(!config.description.as_deref().unwrap_or("").is_empty());
935 }
936
937 /// Branch globs pick the branches that run (scenario 1), and tag globs pick the tags (scenario 2).
938 #[tokio::test]
939 async fn branch_and_tag_globs_select_runs() {
940 let fx = fixture().await;
941 // Scenario 1: branches.
942 push(&fx, &[(CONFIG_PATH, CONFIG_GLOBS)], "refs/heads/main").await;
943 assert_eq!(runs_total(&fx).await, 0, "main is not in the globs");
944
945 push(
946 &fx,
947 &[(CONFIG_PATH, CONFIG_GLOBS)],
948 "refs/heads/release/1.0",
949 )
950 .await;
951 assert_eq!(runs_total(&fx).await, 1);
952 let run = fx
953 .state
954 .store
955 .run_by_number(&fx.repo.id, 1)
956 .await
957 .expect("query")
958 .expect("run");
959 assert_eq!(run.git_ref, "refs/heads/release/1.0");
960
961 // Scenario 2: tags.
962 push(&fx, &[(CONFIG_PATH, CONFIG_TAGS)], "refs/tags/nightly").await;
963 assert_eq!(runs_total(&fx).await, 1, "nightly does not match v*");
964
965 push(&fx, &[(CONFIG_PATH, CONFIG_TAGS)], "refs/tags/v1.0").await;
966 assert_eq!(runs_total(&fx).await, 2);
967 let run = fx
968 .state
969 .store
970 .run_by_number(&fx.repo.id, 2)
971 .await
972 .expect("query")
973 .expect("run");
974 assert_eq!(run.trigger, "tag");
975 assert_eq!(run.git_ref, "refs/tags/v1.0");
976
977 // An annotated tag's ref names a tag object; the run is for the commit under it.
978 let head = commit(&fx.work, &[(CONFIG_PATH, CONFIG_TAGS)]);
979 git(&fx.work, &["tag", "-a", "v2.0", "-m", "v2.0"]);
980 let tag_obj = git(&fx.work, &["rev-parse", "v2.0"]);
981 assert_ne!(tag_obj, head);
982 land(&fx, &tag_obj, "refs/tags/v2.0");
983 after_ref_update(
984 &fx.state,
985 &fx.repo,
986 &fx.owner.id,
987 "refs/tags/v2.0",
988 ZERO,
989 &tag_obj,
990 )
991 .await
992 .expect("post update");
993 assert_eq!(runs_total(&fx).await, 3);
994 let run = fx
995 .state
996 .store
997 .run_by_number(&fx.repo.id, 3)
998 .await
999 .expect("query")
1000 .expect("run");
1001 assert_eq!(run.commit_oid, head);
1002 }
1003
1004 /// Opens a pull request `author` -> `branch` whose head repo is `head_repo_id`, and runs the
1005 /// PR hook for it.
1006 async fn open_pull(
1007 fx: &Fixture,
1008 author_id: &str,
1009 head_repo_id: &str,
1010 branch: &str,
1011 head_oid: &str,
1012 ) -> PullRequest {
1013 let pr = fx
1014 .state
1015 .store
1016 .create_pull(
1017 &fx.repo.id,
1018 author_id,
1019 "Change",
1020 "",
1021 "main",
1022 head_repo_id,
1023 branch,
1024 head_oid,
1025 head_oid,
1026 )
1027 .await
1028 .expect("create pull");
1029 on_pull_event(&fx.state, &fx.repo, &pr, author_id).await;
1030 pr
1031 }
1032
1033 /// Pull requests wait for approval when the author is a fork (scenario 1) or cannot write to
1034 /// the repo (scenario 2). A writer's pull request runs at once (scenario 3). Each scenario has
1035 /// its own head branch, and its pull request run is number 1, 2 and 3.
1036 #[tokio::test]
1037 async fn pull_requests_wait_for_approval_unless_the_author_writes_the_repo() {
1038 let fx = fixture().await;
1039
1040 // Scenario 1: a fork's pull request.
1041 let fork_head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-fork").await;
1042 let bob = fx
1043 .state
1044 .store
1045 .create_user("bob", None, "unused", false)
1046 .await
1047 .expect("user");
1048 let fork = fx
1049 .state
1050 .store
1051 .create_repo(&bob.id, "proj", "", Visibility::Public, "main")
1052 .await
1053 .expect("fork");
1054 let pr = open_pull(&fx, &fx.owner.id, &fork.id, "feature-fork", &fork_head).await;
1055
1056 let run = fx
1057 .state
1058 .store
1059 .run_by_number(&fx.repo.id, 1)
1060 .await
1061 .expect("query")
1062 .expect("run");
1063 assert_eq!(run.trigger, "pull_request");
1064 assert_eq!(run.state, RunState::WaitingApproval, "fork");
1065 assert_eq!(run.pull_number, Some(pr.issue.number));
1066
1067 let statuses = fx
1068 .state
1069 .store
1070 .statuses_for(&fx.repo.id, &fork_head)
1071 .await
1072 .expect("statuses");
1073 let build = status(&statuses, "ci/build").expect("ci/build");
1074 assert_eq!(build.state, StatusState::Pending);
1075 assert_eq!(build.description.as_deref(), Some("Waiting for approval"));
1076
1077 // Scenario 2: a same-repo pull request from a user who cannot write to it.
1078 let carol = fx
1079 .state
1080 .store
1081 .create_user("carol", None, "unused", false)
1082 .await
1083 .expect("user");
1084 let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-carol").await;
1085 open_pull(&fx, &carol.id, &fx.repo.id, "feature-carol", &head).await;
1086 let run = fx
1087 .state
1088 .store
1089 .run_by_number(&fx.repo.id, 2)
1090 .await
1091 .expect("query")
1092 .expect("run");
1093 assert_eq!(run.state, RunState::WaitingApproval, "non-writer");
1094
1095 // Scenario 3: the owner's pull request runs at once.
1096 let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/feature-writer").await;
1097 open_pull(&fx, &fx.owner.id, &fx.repo.id, "feature-writer", &head).await;
1098 let run = fx
1099 .state
1100 .store
1101 .run_by_number(&fx.repo.id, 3)
1102 .await
1103 .expect("query")
1104 .expect("run");
1105 assert_ne!(run.state, RunState::WaitingApproval, "writer");
1106 }
1107
1108 /// Manual runs use the branch head (scenario 1). A missing branch is an error, and a branch
1109 /// whose config sets `manual = false` is refused (scenario 2).
1110 #[tokio::test]
1111 async fn manual_runs_use_the_branch_head_and_refuse_when_asked() {
1112 let fx = fixture().await;
1113 let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await;
1114 let before = runs_total(&fx).await;
1115 let run = manual_run(&fx.state, &fx.repo, "main", &fx.owner.id)
1116 .await
1117 .expect("manual run");
1118 assert_eq!(run.trigger, "manual");
1119 assert_eq!(run.git_ref, "refs/heads/main");
1120 assert_eq!(run.commit_oid, head);
1121 assert_eq!(runs_total(&fx).await, before + 1);
1122
1123 push(&fx, &[(CONFIG_PATH, CONFIG_NO_MANUAL)], "refs/heads/quiet").await;
1124 let before = runs_total(&fx).await;
1125 assert!(
1126 manual_run(&fx.state, &fx.repo, "nope", &fx.owner.id)
1127 .await
1128 .is_err()
1129 );
1130 let refused = manual_run(&fx.state, &fx.repo, "quiet", &fx.owner.id).await;
1131 assert!(matches!(refused, Err(forge_core::Error::Invalid(_))));
1132 assert_eq!(runs_total(&fx).await, before);
1133 }
1134
1135 #[tokio::test]
1136 async fn reaper_marks_lost_jobs_and_syncs_statuses() {
1137 let fx = fixture().await;
1138 let head = push(&fx, &[(CONFIG_PATH, CONFIG)], "refs/heads/main").await;
1139 let runner = runner(&fx).await;
1140 let (job, _run, _token) = fx
1141 .state
1142 .store
1143 .claim_job(&runner)
1144 .await
1145 .expect("claim")
1146 .expect("a queued job");
1147 assert_eq!(job.name, "build");
1148
1149 // A cutoff in the future makes every running job look silent.
1150 let reaped = reap_before(&fx.state, &stamp_after(Duration::from_secs(3600))).await;
1151 assert_eq!(reaped, 1);
1152
1153 let job = fx
1154 .state
1155 .store
1156 .job_by_id(&job.id)
1157 .await
1158 .expect("query")
1159 .expect("job");
1160 assert_eq!(job.state, JobState::Error);
1161 assert_eq!(job.message.as_deref(), Some("runner lost"));
1162
1163 let statuses = fx
1164 .state
1165 .store
1166 .statuses_for(&fx.repo.id, &head)
1167 .await
1168 .expect("statuses");
1169 let build = status(&statuses, "ci/build").expect("ci/build");
1170 assert_eq!(build.state, StatusState::Error);
1171 }
1172
1173 #[tokio::test]
1174 async fn purge_deletes_log_files() {
1175 let fx = fixture().await;
1176 push(&fx, &[(CONFIG_PATH, CONFIG_ONE_JOB)], "refs/heads/main").await;
1177 let runner = runner(&fx).await;
1178 let (job, _run, _token) = fx
1179 .state
1180 .store
1181 .claim_job(&runner)
1182 .await
1183 .expect("claim")
1184 .expect("a queued job");
1185 // Purge only takes jobs that wrote a log and whose run has finished.
1186 fx.state
1187 .store
1188 .add_log_bytes(&job.id, 12)
1189 .await
1190 .expect("log bytes");
1191 fx.state
1192 .store
1193 .finish_job(&job.id, JobState::Success, Some(0), None)
1194 .await
1195 .expect("finish");
1196
1197 let path = log_path(&fx.state.config.data_dir, &job.id);
1198 std::fs::create_dir_all(path.parent().expect("parent")).expect("log dir");
1199 std::fs::write(&path, "build output\n").expect("write log");
1200
1201 // Zero days of retention: everything finished before now is purged.
1202 let mut cfg = (*fx.state.config).clone();
1203 cfg.ci.log_retention_days = 0;
1204 let mut state = fx.state.clone();
1205 state.set_config(cfg);
1206 tokio::time::sleep(Duration::from_millis(1100)).await;
1207
1208 let (logs, _artifacts) = purge_once(&state).await;
1209 assert_eq!(logs, 1);
1210 assert!(!path.exists(), "log file is deleted");
1211 }
1212
1213 const CONFIG_SUPERSEDE: &str = r#"
1214[on]
1215push = ["main"]
1216cancel_superseded = true
1217
1218[jobs.build]
1219image = "alpine:3"
1220run = "make"
1221"#;
1222
1223 /// A newer push cancels the older live run on the same ref, unless the config keeps it. Each
1224 /// case has its own branch, since superseding only looks at one ref. The runs of a case are
1225 /// numbered `first` and `first + 1`, because every push on these branches starts one run.
1226 #[tokio::test]
1227 async fn a_newer_push_cancels_older_live_runs_unless_the_config_keeps_them() {
1228 let fx = fixture().await;
1229 // Each config triggers on its own branch, so its pushes make runs there.
1230 let on = |config: &str, branch: &str| {
1231 config.replace("push = [\"main\"]", &format!("push = [\"{branch}\"]"))
1232 };
1233 // (branch, config, the older run is cancelled, number of the older run)
1234 let cases: [(&str, String, bool, i64); 3] = [
1235 ("default", on(CONFIG_ONE_JOB, "default"), true, 1),
1236 ("asked", on(CONFIG_SUPERSEDE, "asked"), true, 3),
1237 (
1238 "kept",
1239 on(
1240 &CONFIG_SUPERSEDE
1241 .replace("cancel_superseded = true", "cancel_superseded = false"),
1242 "kept",
1243 ),
1244 false,
1245 5,
1246 ),
1247 ];
1248 for (branch, config, cancelled, first_number) in cases {
1249 let git_ref = format!("refs/heads/{branch}");
1250 let case = format!("case {branch}");
1251 push(&fx, &[(CONFIG_PATH, config.as_str())], &git_ref).await;
1252 push(&fx, &[("a.txt", "a")], &git_ref).await;
1253 let store = &fx.state.store;
1254 let first = store
1255 .run_by_number(&fx.repo.id, first_number)
1256 .await
1257 .unwrap()
1258 .unwrap();
1259 let second = store
1260 .run_by_number(&fx.repo.id, first_number + 1)
1261 .await
1262 .unwrap()
1263 .unwrap();
1264 let want = if cancelled {
1265 RunState::Cancelled
1266 } else {
1267 RunState::Queued
1268 };
1269 assert_eq!(first.state, want, "{case}: the older run");
1270 assert_eq!(second.state, RunState::Queued, "{case}: the newest run");
1271 if cancelled {
1272 let jobs = store.jobs_for_run(&first.id).await.unwrap();
1273 assert_eq!(
1274 state_of(&jobs, "build"),
1275 Some(JobState::Cancelled),
1276 "{case}"
1277 );
1278 }
1279 }
1280 }
1281
1282 #[tokio::test]
1283 async fn ignored_config_keys_are_stored_as_run_warnings() {
1284 let fx = fixture().await;
1285 let config = "[on]\npush = [\"main\"]\nwebhook = true\n\n[jobs.build]\nimage = \"alpine:3\"\nrun = \"make\"\n";
1286 push(&fx, &[(CONFIG_PATH, config)], "refs/heads/main").await;
1287 let run = fx
1288 .state
1289 .store
1290 .run_by_number(&fx.repo.id, 1)
1291 .await
1292 .unwrap()
1293 .unwrap();
1294 let warnings = fx.state.store.run_warnings(&run.id).await.unwrap();
1295 assert_eq!(warnings.len(), 1);
1296 assert!(warnings[0].contains("`on.webhook`"), "{warnings:?}");
1297 }
1298}