| 1 | //! Reading: workflows, runs (any attempt), a run's jobs, a job's log and |
| 2 | //! its steps' summaries. |
| 3 | |
| 4 | use g1t_actions::workflow::{self, Severity}; |
| 5 | use g1t_contracts::access::Capability; |
| 6 | use g1t_contracts::checks::{ActionsChecksArgs, MAX_COMMITS}; |
| 7 | use g1t_contracts::actions::{ |
| 8 | Annotation, Job, JobLog, JobLogText, JobLogTextArgs, JobSummary, LogChunk, LogsArgs, MAX_RUN_LOG_BYTES, RunArgs, RunAttempt, RunDetail, |
| 9 | RunLogsArgs, RunsArgs, SetWorkflowEnabledArgs, StepState, StepSummary, SummariesArgs, Workflow, WorkflowNote, WorkflowRun, WorkflowsArgs, |
| 10 | }; |
| 11 | use g1t_contracts::{FailureCode, Outcome}; |
| 12 | use serde::Deserialize; |
| 13 | use worker::Result; |
| 14 | |
| 15 | use crate::plan::{JobRow, RunRow}; |
| 16 | use crate::sync::WorkflowRow; |
| 17 | use crate::{Actions, check, fail}; |
| 18 | |
| 19 | const RUNS_SHOWN: u32 = 50; |
| 20 | |
| 21 | fn notes(source: &str) -> Vec<WorkflowNote> { |
| 22 | workflow::parse(source) |
| 23 | .map(|w| { |
| 24 | w.notes |
| 25 | .into_iter() |
| 26 | .map(|note| WorkflowNote { |
| 27 | severity: match note.severity { |
| 28 | Severity::Info => "info", |
| 29 | Severity::Warning => "warning", |
| 30 | Severity::Unsupported => "unsupported", |
| 31 | } |
| 32 | .to_owned(), |
| 33 | job: note.job, |
| 34 | message: note.message, |
| 35 | }) |
| 36 | .collect() |
| 37 | }) |
| 38 | .unwrap_or_default() |
| 39 | } |
| 40 | |
| 41 | /// A job of an earlier attempt, as it ended (migration 0009). |
| 42 | #[derive(Clone, Deserialize)] |
| 43 | pub struct AttemptJobRow { |
| 44 | pub id: String, |
| 45 | pub run_id: String, |
| 46 | pub log_id: String, |
| 47 | pub key: String, |
| 48 | pub name: String, |
| 49 | pub needs: String, |
| 50 | pub status: String, |
| 51 | pub conclusion: Option<String>, |
| 52 | pub steps: String, |
| 53 | pub annotations: String, |
| 54 | pub reason: Option<String>, |
| 55 | pub environment: Option<String>, |
| 56 | pub labels: Option<String>, |
| 57 | pub runner_name: Option<String>, |
| 58 | pub started_at: Option<String>, |
| 59 | pub finished_at: Option<String>, |
| 60 | } |
| 61 | |
| 62 | fn attempt_job_view(row: AttemptJobRow) -> Job { |
| 63 | Job { |
| 64 | needs: serde_json::from_str(&row.needs).unwrap_or_default(), |
| 65 | id: row.id, |
| 66 | run_id: row.run_id, |
| 67 | key: row.key, |
| 68 | name: row.name, |
| 69 | status: row.status, |
| 70 | conclusion: row.conclusion, |
| 71 | steps: serde_json::from_str::<Vec<StepState>>(&row.steps).unwrap_or_default(), |
| 72 | annotations: serde_json::from_str::<Vec<Annotation>>(&row.annotations).unwrap_or_default(), |
| 73 | reason: row.reason, |
| 74 | started_at: row.started_at, |
| 75 | finished_at: row.finished_at, |
| 76 | environment: row.environment, |
| 77 | self_hosted: row.labels.is_some(), |
| 78 | runner: row.runner_name, |
| 79 | cancelling: false, |
| 80 | environment_url: None, |
| 81 | uses: None, |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | /// An earlier attempt of a run, as it ended. |
| 86 | #[derive(Clone, Deserialize)] |
| 87 | struct AttemptRow { |
| 88 | attempt: u64, |
| 89 | conclusion: Option<String>, |
| 90 | actor: Option<String>, |
| 91 | debug: u32, |
| 92 | started_at: Option<String>, |
| 93 | finished_at: Option<String>, |
| 94 | } |
| 95 | |
| 96 | /// One attempt's jobs, each with where its logs and summary are kept. |
| 97 | struct AttemptJobs { |
| 98 | jobs: Vec<Job>, |
| 99 | log_ids: Vec<String>, |
| 100 | } |
| 101 | |
| 102 | fn job_view(row: JobRow) -> Job { |
| 103 | let needs = row.needs(); |
| 104 | let cancelling = row.cancel_requested_at.is_some() && row.status != "completed"; |
| 105 | let uses = row.call().filter(|call| call["role"] == "caller").and_then(|call| call["path"].as_str().map(str::to_owned)); |
| 106 | Job { |
| 107 | uses, |
| 108 | environment_url: None, |
| 109 | cancelling, |
| 110 | id: row.id, |
| 111 | run_id: row.run_id, |
| 112 | key: row.key, |
| 113 | name: row.name, |
| 114 | needs, |
| 115 | status: row.status, |
| 116 | conclusion: row.conclusion, |
| 117 | steps: serde_json::from_str::<Vec<StepState>>(&row.steps).unwrap_or_default(), |
| 118 | annotations: serde_json::from_str::<Vec<Annotation>>(&row.annotations).unwrap_or_default(), |
| 119 | reason: row.reason, |
| 120 | started_at: row.started_at, |
| 121 | finished_at: row.finished_at, |
| 122 | environment: row.environment, |
| 123 | self_hosted: row.labels.is_some(), |
| 124 | runner: row.runner_name, |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | impl Actions { |
| 129 | async fn summary(&self, row: &WorkflowRow) -> Result<Workflow> { |
| 130 | let last_run = self |
| 131 | .db |
| 132 | .prepare("SELECT * FROM runs WHERE workflow_id = ? ORDER BY id DESC LIMIT 1") |
| 133 | .bind(&[row.id.as_str().into()])? |
| 134 | .first::<RunRow>(None) |
| 135 | .await? |
| 136 | .map(|run| run.summary()); |
| 137 | let parsed = workflow::parse(&row.source).ok(); |
| 138 | Ok(Workflow { |
| 139 | id: row.id.clone(), |
| 140 | path: row.path.clone(), |
| 141 | name: row.name.clone(), |
| 142 | events: serde_json::from_str(&row.events).unwrap_or_default(), |
| 143 | state: row.state.clone(), |
| 144 | error: row.error.clone(), |
| 145 | notes: notes(&row.source), |
| 146 | dispatch: parsed |
| 147 | .as_ref() |
| 148 | .filter(|_| row.error.is_none()) |
| 149 | .and_then(|w| w.trigger("workflow_dispatch")) |
| 150 | .map(|t| serde_json::Value::Object(t.inputs.clone())), |
| 151 | last_run, |
| 152 | }) |
| 153 | } |
| 154 | |
| 155 | pub async fn workflows(&self, a: WorkflowsArgs) -> Result<Outcome<Vec<Workflow>>> { |
| 156 | let Some(repo) = self.visible_repo(&a.repo, &a.viewer).await? else { |
| 157 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); |
| 158 | }; |
| 159 | if !self.synced(&repo.id).await? |
| 160 | && let Some(ws) = self.workspace_actor(&repo.namespace).await? |
| 161 | { |
| 162 | self.sync(&repo, &ws).await?; |
| 163 | } |
| 164 | // A file that is gone stays listed while it has runs, unless one in |
| 165 | // the folder now has its name: then it would read as a second copy. |
| 166 | // Files outside the folder are from before g1t stopped reading |
| 167 | // `.github`; their runs stay under All workflows. |
| 168 | let rows = self |
| 169 | .db |
| 170 | .prepare( |
| 171 | "SELECT * FROM workflows w WHERE w.repo_id = ?1 AND w.path LIKE ?2 |
| 172 | AND (w.error IS NULL OR w.error NOT LIKE 'Its file is%' |
| 173 | OR (w.id IN (SELECT workflow_id FROM runs WHERE repo_id = ?1) |
| 174 | AND NOT EXISTS (SELECT 1 FROM workflows o WHERE o.repo_id = ?1 AND o.id <> w.id |
| 175 | AND o.name = w.name AND (o.error IS NULL OR o.error NOT LIKE 'Its file is%')))) |
| 176 | ORDER BY w.name", |
| 177 | ) |
| 178 | .bind(&[repo.id.as_str().into(), format!("{}/%", g1t_actions::workflow::FOLDER).into()])? |
| 179 | .all() |
| 180 | .await? |
| 181 | .results::<WorkflowRow>()?; |
| 182 | let mut out = Vec::with_capacity(rows.len()); |
| 183 | for row in &rows { |
| 184 | out.push(self.summary(row).await?); |
| 185 | } |
| 186 | Ok(Outcome::Ok(out)) |
| 187 | } |
| 188 | |
| 189 | pub async fn runs(&self, a: RunsArgs) -> Result<Outcome<Vec<WorkflowRun>>> { |
| 190 | let Some(repo) = self.visible_repo(&a.repo, &a.viewer).await? else { |
| 191 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); |
| 192 | }; |
| 193 | let mut sql = "SELECT * FROM runs WHERE repo_id = ?".to_owned(); |
| 194 | let mut binds: Vec<worker::wasm_bindgen::JsValue> = vec![repo.id.as_str().into()]; |
| 195 | if let Some(workflow) = &a.workflow { |
| 196 | sql.push_str(" AND (workflow_id = ? OR path = ? OR path = ?)"); |
| 197 | binds.push(workflow.as_str().into()); |
| 198 | binds.push(workflow.as_str().into()); |
| 199 | binds.push(format!("{}/{workflow}", g1t_actions::workflow::FOLDER).into()); |
| 200 | } |
| 201 | if let Some(branch) = &a.branch { |
| 202 | sql.push_str(" AND (git_ref = ? OR json_extract(info, '$.headRef') = ?)"); |
| 203 | binds.push(format!("refs/heads/{branch}").into()); |
| 204 | binds.push(branch.as_str().into()); |
| 205 | } |
| 206 | if let Some(event) = &a.event { |
| 207 | sql.push_str(" AND event = ?"); |
| 208 | binds.push(event.as_str().into()); |
| 209 | } |
| 210 | if let Some(pull) = a.pull { |
| 211 | sql.push_str(" AND pull = ?"); |
| 212 | binds.push(pull.into()); |
| 213 | } |
| 214 | if let Some(sha) = &a.sha { |
| 215 | sql.push_str(" AND sha = ?"); |
| 216 | binds.push(sha.as_str().into()); |
| 217 | } |
| 218 | sql.push_str(" ORDER BY id DESC LIMIT ?"); |
| 219 | binds.push(a.limit.unwrap_or(RUNS_SHOWN).clamp(1, 100).into()); |
| 220 | let rows = self.db.prepare(sql).bind(&binds)?.all().await?.results::<RunRow>()?; |
| 221 | Ok(Outcome::Ok(rows.iter().map(RunRow::summary).collect())) |
| 222 | } |
| 223 | |
| 224 | /// Every attempt of a run, oldest first, the current one last. |
| 225 | async fn attempts_of(&self, run: &RunRow) -> Result<Vec<RunAttempt>> { |
| 226 | let mut attempts: Vec<RunAttempt> = self |
| 227 | .db |
| 228 | .prepare("SELECT attempt, conclusion, actor, debug, started_at, finished_at FROM run_attempts WHERE run_id = ? ORDER BY attempt") |
| 229 | .bind(&[run.id.as_str().into()])? |
| 230 | .all() |
| 231 | .await? |
| 232 | .results::<AttemptRow>()? |
| 233 | .into_iter() |
| 234 | .filter(|row| row.attempt < run.attempt) |
| 235 | .map(|row| RunAttempt { |
| 236 | attempt: row.attempt, |
| 237 | status: "completed".to_owned(), |
| 238 | conclusion: row.conclusion, |
| 239 | actor: row.actor, |
| 240 | debug: row.debug != 0, |
| 241 | started_at: row.started_at, |
| 242 | finished_at: row.finished_at, |
| 243 | }) |
| 244 | .collect(); |
| 245 | attempts.push(RunAttempt { |
| 246 | attempt: run.attempt, |
| 247 | status: run.status.clone(), |
| 248 | conclusion: run.conclusion.clone().filter(|_| run.status == "completed"), |
| 249 | actor: run.triggering_actor.clone().or_else(|| run.actor.clone()), |
| 250 | debug: run.debug != 0, |
| 251 | started_at: run.started_at.clone(), |
| 252 | finished_at: run.finished_at.clone(), |
| 253 | }); |
| 254 | Ok(attempts) |
| 255 | } |
| 256 | |
| 257 | /// The jobs of one attempt: the live ones for the current attempt, the |
| 258 | /// kept ones for an earlier attempt. None for an attempt it never had. |
| 259 | async fn attempt_jobs(&self, run: &RunRow, attempt: Option<u64>) -> Result<Option<AttemptJobs>> { |
| 260 | match attempt.filter(|n| *n != run.attempt) { |
| 261 | None => { |
| 262 | // A job that deploys: where to, as its `environment.url` reads. |
| 263 | let jobs: Vec<Job> = self |
| 264 | .job_rows(&run.id) |
| 265 | .await? |
| 266 | .into_iter() |
| 267 | .map(|row| { |
| 268 | let environment_url = row.environment.as_ref().and_then(|_| crate::plan::deploys_to(run, &row)).and_then(|env| env.url); |
| 269 | Job { environment_url, ..job_view(row) } |
| 270 | }) |
| 271 | .collect(); |
| 272 | let log_ids = jobs.iter().map(|job| job.id.clone()).collect(); |
| 273 | Ok(Some(AttemptJobs { jobs, log_ids })) |
| 274 | } |
| 275 | Some(n) if n == 0 || n > run.attempt => Ok(None), |
| 276 | Some(n) => { |
| 277 | let rows = self |
| 278 | .db |
| 279 | .prepare("SELECT * FROM job_attempts WHERE run_id = ? AND attempt = ? ORDER BY rowid") |
| 280 | .bind(&[run.id.as_str().into(), (n as f64).into()])? |
| 281 | .all() |
| 282 | .await? |
| 283 | .results::<AttemptJobRow>()?; |
| 284 | let log_ids = rows.iter().map(|row| row.log_id.clone()).collect(); |
| 285 | Ok(Some(AttemptJobs { jobs: rows.into_iter().map(attempt_job_view).collect(), log_ids })) |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | pub async fn run(&self, a: RunArgs) -> Result<Outcome<RunDetail>> { |
| 291 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { |
| 292 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); |
| 293 | } |
| 294 | let run = check!(self.run_in(&a.repo, &a.id).await?); |
| 295 | let Some(AttemptJobs { jobs, .. }) = self.attempt_jobs(&run, a.attempt).await? else { |
| 296 | return Ok(fail(FailureCode::NotFound, format!("This run has no attempt {}.", a.attempt.unwrap_or_default()))); |
| 297 | }; |
| 298 | let attempts = self.attempts_of(&run).await?; |
| 299 | let mut summary = run.summary(); |
| 300 | // An earlier attempt: as it ended, and nothing waits for it. |
| 301 | if let Some(earlier) = a.attempt.filter(|n| *n != run.attempt).and_then(|n| attempts.iter().find(|at| at.attempt == n)) { |
| 302 | summary.attempt = earlier.attempt; |
| 303 | summary.status = "completed".to_owned(); |
| 304 | summary.conclusion = earlier.conclusion.clone(); |
| 305 | summary.started_at = earlier.started_at.clone(); |
| 306 | summary.finished_at = earlier.finished_at.clone(); |
| 307 | return Ok(Outcome::Ok(RunDetail { |
| 308 | notes: notes(&run.source), |
| 309 | run: summary, |
| 310 | jobs, |
| 311 | approval: run.approval(), |
| 312 | pending_deployments: Vec::new(), |
| 313 | attempts, |
| 314 | })); |
| 315 | } |
| 316 | let pending_deployments = self.pending_for(&run, &a.viewer).await?; |
| 317 | // Jobs held at an environment's rules: the run waits, as on GitHub. |
| 318 | if matches!(summary.status.as_str(), "queued" | "in_progress") && jobs.iter().any(|job| job.status == "pending") { |
| 319 | summary.status = "waiting".to_owned(); |
| 320 | } |
| 321 | Ok(Outcome::Ok(RunDetail { |
| 322 | notes: notes(&run.source), |
| 323 | run: summary, |
| 324 | jobs, |
| 325 | approval: run.approval(), |
| 326 | pending_deployments, |
| 327 | attempts, |
| 328 | })) |
| 329 | } |
| 330 | |
| 331 | /// A job of the repository's runs by the id a run's page gives it: a |
| 332 | /// live job, or one of an earlier attempt. Its name, steps, where its |
| 333 | /// logs and summary are kept, and whether it has finished. |
| 334 | async fn job_for_log(&self, repo: &g1t_contracts::repos::RepoPath, id: &str) -> Result<Option<(Job, String, bool)>> { |
| 335 | let full = format!("{}/{}", repo.namespace, repo.name); |
| 336 | let live = self |
| 337 | .db |
| 338 | .prepare("SELECT jobs.* FROM jobs JOIN runs ON runs.id = jobs.run_id WHERE jobs.id = ? AND lower(runs.repo) = lower(?)") |
| 339 | .bind(&[id.into(), full.as_str().into()])? |
| 340 | .first::<JobRow>(None) |
| 341 | .await?; |
| 342 | if let Some(job) = live { |
| 343 | let done = job.status == "completed"; |
| 344 | let view = job_view(job); |
| 345 | let log_id = view.id.clone(); |
| 346 | return Ok(Some((view, log_id, done))); |
| 347 | } |
| 348 | let kept = self |
| 349 | .db |
| 350 | .prepare( |
| 351 | "SELECT job_attempts.* FROM job_attempts JOIN runs ON runs.id = job_attempts.run_id |
| 352 | WHERE job_attempts.id = ? AND lower(runs.repo) = lower(?)", |
| 353 | ) |
| 354 | .bind(&[id.into(), full.as_str().into()])? |
| 355 | .first::<AttemptJobRow>(None) |
| 356 | .await?; |
| 357 | Ok(kept.map(|row| { |
| 358 | let log_id = row.log_id.clone(); |
| 359 | (attempt_job_view(row), log_id, true) |
| 360 | })) |
| 361 | } |
| 362 | |
| 363 | async fn log_chunks(&self, log_id: &str, after: u64, limit: u32) -> Result<Vec<LogChunk>> { |
| 364 | #[derive(Deserialize)] |
| 365 | struct Row { |
| 366 | seq: u64, |
| 367 | step: u32, |
| 368 | text: String, |
| 369 | } |
| 370 | Ok(self |
| 371 | .db |
| 372 | .prepare("SELECT seq, step, text FROM logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?") |
| 373 | .bind(&[log_id.into(), (after as f64).into(), limit.into()])? |
| 374 | .all() |
| 375 | .await? |
| 376 | .results::<Row>()? |
| 377 | .into_iter() |
| 378 | .map(|row| LogChunk { seq: row.seq, step: row.step, text: row.text }) |
| 379 | .collect()) |
| 380 | } |
| 381 | |
| 382 | /// Every chunk of a job's log, a page at a time. |
| 383 | async fn whole_log(&self, log_id: &str) -> Result<Vec<LogChunk>> { |
| 384 | let mut chunks: Vec<LogChunk> = Vec::new(); |
| 385 | loop { |
| 386 | let after = chunks.last().map_or(0, |chunk| chunk.seq); |
| 387 | let page = self.log_chunks(log_id, after, 500).await?; |
| 388 | let more = page.len() == 500; |
| 389 | chunks.extend(page); |
| 390 | if !more { |
| 391 | return Ok(chunks); |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | pub async fn logs(&self, a: LogsArgs) -> Result<Outcome<JobLog>> { |
| 397 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { |
| 398 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); |
| 399 | } |
| 400 | let Some((_, log_id, done)) = self.job_for_log(&a.repo, &a.job).await? else { |
| 401 | return Ok(fail(FailureCode::NotFound, "No such job.")); |
| 402 | }; |
| 403 | let chunks = self.log_chunks(&log_id, a.after, 500).await?; |
| 404 | Ok(Outcome::Ok(JobLog { chunks, done })) |
| 405 | } |
| 406 | |
| 407 | /// `job_log_text`: a job's whole log, to download. |
| 408 | pub async fn job_log_text(&self, a: JobLogTextArgs) -> Result<Outcome<JobLogText>> { |
| 409 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { |
| 410 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); |
| 411 | } |
| 412 | let Some((job, log_id, done)) = self.job_for_log(&a.repo, &a.job).await? else { |
| 413 | return Ok(fail(FailureCode::NotFound, "No such job.")); |
| 414 | }; |
| 415 | let chunks = self.whole_log(&log_id).await?; |
| 416 | Ok(Outcome::Ok(JobLogText { job_id: job.id, name: job.name, steps: job.steps, chunks, done, omitted: false })) |
| 417 | } |
| 418 | |
| 419 | /// `run_logs`: every job's whole log for one attempt, to download as one |
| 420 | /// archive. |
| 421 | pub async fn run_logs(&self, a: RunLogsArgs) -> Result<Outcome<Vec<JobLogText>>> { |
| 422 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { |
| 423 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); |
| 424 | } |
| 425 | let run = check!(self.run_in(&a.repo, &a.id).await?); |
| 426 | let Some(AttemptJobs { jobs, log_ids }) = self.attempt_jobs(&run, a.attempt).await? else { |
| 427 | return Ok(fail(FailureCode::NotFound, format!("This run has no attempt {}.", a.attempt.unwrap_or_default()))); |
| 428 | }; |
| 429 | let mut out = Vec::with_capacity(jobs.len()); |
| 430 | let mut total = 0usize; |
| 431 | for (job, log_id) in jobs.into_iter().zip(log_ids) { |
| 432 | let done = job.status == "completed"; |
| 433 | let omitted = total >= MAX_RUN_LOG_BYTES; |
| 434 | let chunks = if omitted { Vec::new() } else { self.whole_log(&log_id).await? }; |
| 435 | total += chunks.iter().map(|chunk| chunk.text.len()).sum::<usize>(); |
| 436 | out.push(JobLogText { job_id: job.id, name: job.name, steps: job.steps, chunks, done, omitted }); |
| 437 | } |
| 438 | Ok(Outcome::Ok(out)) |
| 439 | } |
| 440 | |
| 441 | /// `summaries`: what each job's steps wrote to `$GITHUB_STEP_SUMMARY`. |
| 442 | pub async fn summaries(&self, a: SummariesArgs) -> Result<Outcome<Vec<JobSummary>>> { |
| 443 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { |
| 444 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); |
| 445 | } |
| 446 | let run = check!(self.run_in(&a.repo, &a.id).await?); |
| 447 | let Some(AttemptJobs { jobs, log_ids }) = self.attempt_jobs(&run, a.attempt).await? else { |
| 448 | return Ok(fail(FailureCode::NotFound, format!("This run has no attempt {}.", a.attempt.unwrap_or_default()))); |
| 449 | }; |
| 450 | #[derive(Deserialize)] |
| 451 | struct Row { |
| 452 | job_id: String, |
| 453 | step: u32, |
| 454 | markdown: String, |
| 455 | } |
| 456 | let rows = self |
| 457 | .db |
| 458 | .prepare("SELECT job_id, step, markdown FROM job_summaries WHERE job_id IN (SELECT value FROM json_each(?)) ORDER BY step") |
| 459 | .bind(&[serde_json::to_string(&log_ids)?.into()])? |
| 460 | .all() |
| 461 | .await? |
| 462 | .results::<Row>()?; |
| 463 | Ok(Outcome::Ok( |
| 464 | jobs.into_iter() |
| 465 | .zip(log_ids) |
| 466 | .filter_map(|(job, log_id)| { |
| 467 | let steps: Vec<StepSummary> = rows |
| 468 | .iter() |
| 469 | .filter(|row| row.job_id == log_id) |
| 470 | .map(|row| StepSummary { step: row.step, markdown: row.markdown.clone() }) |
| 471 | .collect(); |
| 472 | (!steps.is_empty()).then_some(JobSummary { job_id: job.id, name: job.name, steps }) |
| 473 | }) |
| 474 | .collect(), |
| 475 | )) |
| 476 | } |
| 477 | |
| 478 | pub async fn set_workflow_enabled(&self, a: SetWorkflowEnabledArgs) -> Result<Outcome<Workflow>> { |
| 479 | if let Outcome::Fail(refused) = self.may(&a.actor, &a.repo, Capability::ManageSettings).await? { |
| 480 | return Ok(Outcome::Fail(refused)); |
| 481 | } |
| 482 | let wanted = a.workflow.trim_start_matches(".g1t/workflows/"); |
| 483 | let row = self |
| 484 | .db |
| 485 | .prepare("SELECT * FROM workflows WHERE lower(repo) = lower(?) AND (id = ? OR path = ?)") |
| 486 | .bind(&[ |
| 487 | format!("{}/{}", a.repo.namespace, a.repo.name).into(), |
| 488 | a.workflow.as_str().into(), |
| 489 | format!("{}/{wanted}", g1t_actions::workflow::FOLDER).into(), |
| 490 | ])? |
| 491 | .first::<WorkflowRow>(None) |
| 492 | .await?; |
| 493 | let Some(row) = row else { |
| 494 | return Ok(fail(FailureCode::NotFound, "No such workflow.")); |
| 495 | }; |
| 496 | let state = if a.enabled { "active" } else { "disabled" }; |
| 497 | self.db.prepare("UPDATE workflows SET state = ? WHERE id = ?").bind(&[state.into(), row.id.as_str().into()])?.run().await?; |
| 498 | let row = WorkflowRow { state: state.to_owned(), ..row }; |
| 499 | Ok(Outcome::Ok(self.summary(&row).await?)) |
| 500 | } |
| 501 | |
| 502 | /// `check_runs`: workflow runs with their jobs, by commits, by a run's |
| 503 | /// id or by one of its jobs' ids, newest first, for the work service to |
| 504 | /// show as check suites and check runs. It decides who may see them. |
| 505 | pub async fn check_runs(&self, a: ActionsChecksArgs) -> Result<Vec<RunDetail>> { |
| 506 | let runs: Vec<RunRow> = if let Some(job) = &a.job_id { |
| 507 | self.db |
| 508 | .prepare("SELECT runs.* FROM runs JOIN jobs ON jobs.run_id = runs.id WHERE jobs.id = ? AND runs.repo_id = ?") |
| 509 | .bind(&[job.as_str().into(), a.repo_id.as_str().into()])? |
| 510 | .all() |
| 511 | .await? |
| 512 | .results::<RunRow>()? |
| 513 | } else if let Some(run) = &a.run_id { |
| 514 | self.db |
| 515 | .prepare("SELECT * FROM runs WHERE id = ? AND repo_id = ?") |
| 516 | .bind(&[run.as_str().into(), a.repo_id.as_str().into()])? |
| 517 | .all() |
| 518 | .await? |
| 519 | .results::<RunRow>()? |
| 520 | } else if a.shas.is_empty() { |
| 521 | Vec::new() |
| 522 | } else { |
| 523 | let shas: Vec<&String> = a.shas.iter().take(MAX_COMMITS).collect(); |
| 524 | let marks = vec!["?"; shas.len()].join(", "); |
| 525 | let mut binds: Vec<worker::wasm_bindgen::JsValue> = vec![a.repo_id.as_str().into()]; |
| 526 | binds.extend(shas.iter().map(|sha| sha.as_str().into())); |
| 527 | binds.push(CHECK_RUNS_LIMIT.into()); |
| 528 | self.db |
| 529 | .prepare(format!("SELECT * FROM runs WHERE repo_id = ? AND sha IN ({marks}) ORDER BY id DESC LIMIT ?")) |
| 530 | .bind(&binds)? |
| 531 | .all() |
| 532 | .await? |
| 533 | .results::<RunRow>()? |
| 534 | }; |
| 535 | if runs.is_empty() { |
| 536 | return Ok(Vec::new()); |
| 537 | } |
| 538 | let marks = vec!["?"; runs.len()].join(", "); |
| 539 | let ids: Vec<worker::wasm_bindgen::JsValue> = runs.iter().map(|run| run.id.as_str().into()).collect(); |
| 540 | let jobs = self |
| 541 | .db |
| 542 | .prepare(format!("SELECT * FROM jobs WHERE run_id IN ({marks}) ORDER BY rowid")) |
| 543 | .bind(&ids)? |
| 544 | .all() |
| 545 | .await? |
| 546 | .results::<JobRow>()?; |
| 547 | let mut by_run: std::collections::HashMap<String, Vec<Job>> = std::collections::HashMap::new(); |
| 548 | for job in jobs { |
| 549 | by_run.entry(job.run_id.clone()).or_default().push(job_view(job)); |
| 550 | } |
| 551 | Ok(runs |
| 552 | .iter() |
| 553 | .map(|run| RunDetail { |
| 554 | run: run.summary(), |
| 555 | jobs: by_run.remove(&run.id).unwrap_or_default(), |
| 556 | notes: Vec::new(), |
| 557 | approval: run.approval(), |
| 558 | pending_deployments: Vec::new(), |
| 559 | attempts: Vec::new(), |
| 560 | }) |
| 561 | .collect()) |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | /// The most runs `check_runs` reads for a set of commits. |
| 566 | const CHECK_RUNS_LIMIT: u32 = 200; |