Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 1 | //! Reading: workflows, runs (any attempt), a run's jobs, a job's log and |
| 2 | //! its steps' summaries. | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 3 | |
| 4 | use g1t_actions::workflow::{self, Severity}; | |
| 5 | use g1t_contracts::access::Capability; | |
| Merge checks: statuses and check runs on every commit | 6 | use g1t_contracts::checks::{ActionsChecksArgs, MAX_COMMITS}; |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 7 | use g1t_contracts::actions::{ |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 8 | Annotation, Job, JobLog, JobLogText, JobLogTextArgs, JobSummary, LogChunk, LogsArgs, MAX_RUN_LOG_BYTES, RunArgs, RunAttempt, RunDetail, |
| Merge branch 'worktree-agent-a4db4b523bb973765' | 9 | RunLogsArgs, RunsArgs, SetWorkflowEnabledArgs, StepState, StepSummary, SummariesArgs, Workflow, WorkflowArgs, WorkflowDetail, WorkflowNote, WorkflowRun, |
| 10 | WorkflowsArgs, | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 11 | }; |
| 12 | use g1t_contracts::{FailureCode, Outcome}; | |
| 13 | use serde::Deserialize; | |
| 14 | use worker::Result; | |
| 15 | ||
| 16 | use crate::plan::{JobRow, RunRow}; | |
| 17 | use crate::sync::WorkflowRow; | |
| 18 | use crate::{Actions, check, fail}; | |
| 19 | ||
| 20 | const RUNS_SHOWN: u32 = 50; | |
| 21 | ||
| 22 | fn notes(source: &str) -> Vec<WorkflowNote> { | |
| 23 | workflow::parse(source) | |
| 24 | .map(|w| { | |
| 25 | w.notes | |
| 26 | .into_iter() | |
| 27 | .map(|note| WorkflowNote { | |
| 28 | severity: match note.severity { | |
| 29 | Severity::Info => "info", | |
| 30 | Severity::Warning => "warning", | |
| 31 | Severity::Unsupported => "unsupported", | |
| 32 | } | |
| 33 | .to_owned(), | |
| 34 | job: note.job, | |
| 35 | message: note.message, | |
| 36 | }) | |
| 37 | .collect() | |
| 38 | }) | |
| 39 | .unwrap_or_default() | |
| 40 | } | |
| 41 | ||
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 42 | /// A job of an earlier attempt, as it ended (migration 0009). |
| 43 | #[derive(Clone, Deserialize)] | |
| 44 | pub struct AttemptJobRow { | |
| 45 | pub id: String, | |
| 46 | pub run_id: String, | |
| 47 | pub log_id: String, | |
| 48 | pub key: String, | |
| 49 | pub name: String, | |
| 50 | pub needs: String, | |
| 51 | pub status: String, | |
| 52 | pub conclusion: Option<String>, | |
| 53 | pub steps: String, | |
| 54 | pub annotations: String, | |
| 55 | pub reason: Option<String>, | |
| 56 | pub environment: Option<String>, | |
| 57 | pub labels: Option<String>, | |
| 58 | pub runner_name: Option<String>, | |
| 59 | pub started_at: Option<String>, | |
| 60 | pub finished_at: Option<String>, | |
| 61 | } | |
| 62 | ||
| 63 | fn attempt_job_view(row: AttemptJobRow) -> Job { | |
| 64 | Job { | |
| 65 | needs: serde_json::from_str(&row.needs).unwrap_or_default(), | |
| 66 | id: row.id, | |
| 67 | run_id: row.run_id, | |
| 68 | key: row.key, | |
| 69 | name: row.name, | |
| 70 | status: row.status, | |
| 71 | conclusion: row.conclusion, | |
| 72 | steps: serde_json::from_str::<Vec<StepState>>(&row.steps).unwrap_or_default(), | |
| 73 | annotations: serde_json::from_str::<Vec<Annotation>>(&row.annotations).unwrap_or_default(), | |
| 74 | reason: row.reason, | |
| 75 | started_at: row.started_at, | |
| 76 | finished_at: row.finished_at, | |
| 77 | environment: row.environment, | |
| 78 | self_hosted: row.labels.is_some(), | |
| 79 | runner: row.runner_name, | |
| 80 | cancelling: false, | |
| A run opens on its summary: what triggered it, its status, duration and artifacts, a graph of its jobs (what needs what, matrices folded, called workflows boxed, deploys with their address), annotations, and each job's summary; the job list groups the same way | 81 | environment_url: None, |
| 82 | uses: None, | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 83 | } |
| 84 | } | |
| 85 | ||
| 86 | /// An earlier attempt of a run, as it ended. | |
| 87 | #[derive(Clone, Deserialize)] | |
| 88 | struct AttemptRow { | |
| 89 | attempt: u64, | |
| 90 | conclusion: Option<String>, | |
| 91 | actor: Option<String>, | |
| 92 | debug: u32, | |
| 93 | started_at: Option<String>, | |
| 94 | finished_at: Option<String>, | |
| 95 | } | |
| 96 | ||
| 97 | /// One attempt's jobs, each with where its logs and summary are kept. | |
| 98 | struct AttemptJobs { | |
| 99 | jobs: Vec<Job>, | |
| 100 | log_ids: Vec<String>, | |
| 101 | } | |
| 102 | ||
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 103 | fn job_view(row: JobRow) -> Job { |
| 104 | let needs = row.needs(); | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 105 | let cancelling = row.cancel_requested_at.is_some() && row.status != "completed"; |
| A run opens on its summary: what triggered it, its status, duration and artifacts, a graph of its jobs (what needs what, matrices folded, called workflows boxed, deploys with their address), annotations, and each job's summary; the job list groups the same way | 106 | let uses = row.call().filter(|call| call["role"] == "caller").and_then(|call| call["path"].as_str().map(str::to_owned)); |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 107 | Job { |
| A run opens on its summary: what triggered it, its status, duration and artifacts, a graph of its jobs (what needs what, matrices folded, called workflows boxed, deploys with their address), annotations, and each job's summary; the job list groups the same way | 108 | uses, |
| 109 | environment_url: None, | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 110 | cancelling, |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 111 | id: row.id, |
| 112 | run_id: row.run_id, | |
| 113 | key: row.key, | |
| 114 | name: row.name, | |
| 115 | needs, | |
| 116 | status: row.status, | |
| 117 | conclusion: row.conclusion, | |
| 118 | steps: serde_json::from_str::<Vec<StepState>>(&row.steps).unwrap_or_default(), | |
| 119 | annotations: serde_json::from_str::<Vec<Annotation>>(&row.annotations).unwrap_or_default(), | |
| 120 | reason: row.reason, | |
| 121 | started_at: row.started_at, | |
| 122 | finished_at: row.finished_at, | |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 123 | environment: row.environment, |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 124 | self_hosted: row.labels.is_some(), |
| 125 | runner: row.runner_name, | |
| 126 | } | |
| 127 | } | |
| 128 | ||
| Merge branch 'worktree-agent-a4db4b523bb973765' | 129 | /// The workflow `wanted` names: its id, its path, its file name, or its |
| 130 | /// name (any case), in that order of preference. | |
| 131 | fn pick_workflow<'a>(rows: &'a [WorkflowRow], wanted: &str) -> Option<&'a WorkflowRow> { | |
| 132 | let wanted = wanted.trim(); | |
| 133 | let file = wanted.trim_start_matches(".g1t/workflows/"); | |
| 134 | rows.iter() | |
| 135 | .find(|row| row.id == wanted || row.path == wanted) | |
| 136 | .or_else(|| rows.iter().find(|row| row.path == format!("{}/{file}", workflow::FOLDER))) | |
| 137 | .or_else(|| rows.iter().find(|row| row.path.rsplit('/').next() == Some(file))) | |
| 138 | .or_else(|| rows.iter().find(|row| row.name.eq_ignore_ascii_case(wanted))) | |
| 139 | } | |
| 140 | ||
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 141 | impl Actions { |
| 142 | async fn summary(&self, row: &WorkflowRow) -> Result<Workflow> { | |
| 143 | let last_run = self | |
| 144 | .db | |
| 145 | .prepare("SELECT * FROM runs WHERE workflow_id = ? ORDER BY id DESC LIMIT 1") | |
| 146 | .bind(&[row.id.as_str().into()])? | |
| 147 | .first::<RunRow>(None) | |
| 148 | .await? | |
| 149 | .map(|run| run.summary()); | |
| 150 | let parsed = workflow::parse(&row.source).ok(); | |
| Merge GitHub pull request #8 (claude/cool-newton-7nm8r9): Docker deployments on g1t.page behind a switch that stays off until Cloudflare's container APIs are checked live, workflows a workspace manages in its repositories, tarball and zipball downloads, refs/pull/* kept to g1t alone, framework detection for g1t.page builds, and a workflow's event payload matching GitHub's. | 151 | let managed_by = if g1t_actions::managed::is_managed(&row.path) { |
| 152 | let workspace = row.repo.split_once('/').map_or(row.repo.as_str(), |(workspace, _)| workspace); | |
| 153 | self.managed_by(workspace, &row.path, &row.source).await? | |
| 154 | } else { | |
| 155 | None | |
| 156 | }; | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 157 | Ok(Workflow { |
| 158 | id: row.id.clone(), | |
| 159 | path: row.path.clone(), | |
| 160 | name: row.name.clone(), | |
| 161 | events: serde_json::from_str(&row.events).unwrap_or_default(), | |
| 162 | state: row.state.clone(), | |
| 163 | error: row.error.clone(), | |
| 164 | notes: notes(&row.source), | |
| 165 | dispatch: parsed | |
| 166 | .as_ref() | |
| 167 | .filter(|_| row.error.is_none()) | |
| 168 | .and_then(|w| w.trigger("workflow_dispatch")) | |
| 169 | .map(|t| serde_json::Value::Object(t.inputs.clone())), | |
| 170 | last_run, | |
| Merge GitHub pull request #8 (claude/cool-newton-7nm8r9): Docker deployments on g1t.page behind a switch that stays off until Cloudflare's container APIs are checked live, workflows a workspace manages in its repositories, tarball and zipball downloads, refs/pull/* kept to g1t alone, framework detection for g1t.page builds, and a workflow's event payload matching GitHub's. | 171 | managed_by, |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 172 | }) |
| 173 | } | |
| 174 | ||
| 175 | pub async fn workflows(&self, a: WorkflowsArgs) -> Result<Outcome<Vec<Workflow>>> { | |
| 176 | let Some(repo) = self.visible_repo(&a.repo, &a.viewer).await? else { | |
| 177 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); | |
| 178 | }; | |
| 179 | if !self.synced(&repo.id).await? | |
| 180 | && let Some(ws) = self.workspace_actor(&repo.namespace).await? | |
| 181 | { | |
| 182 | self.sync(&repo, &ws).await?; | |
| 183 | } | |
| 184 | // A file that is gone stays listed while it has runs, unless one in | |
| 185 | // the folder now has its name: then it would read as a second copy. | |
| 186 | // Files outside the folder are from before g1t stopped reading | |
| Merge GitHub pull request #8 (claude/cool-newton-7nm8r9): Docker deployments on g1t.page behind a switch that stays off until Cloudflare's container APIs are checked live, workflows a workspace manages in its repositories, tarball and zipball downloads, refs/pull/* kept to g1t alone, framework detection for g1t.page builds, and a workflow's event payload matching GitHub's. | 187 | // `.github`; their runs stay under All workflows. Managed |
| 188 | // workflows (managed.rs) are listed with the folder's. | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 189 | let rows = self |
| 190 | .db | |
| 191 | .prepare( | |
| Merge GitHub pull request #8 (claude/cool-newton-7nm8r9): Docker deployments on g1t.page behind a switch that stays off until Cloudflare's container APIs are checked live, workflows a workspace manages in its repositories, tarball and zipball downloads, refs/pull/* kept to g1t alone, framework detection for g1t.page builds, and a workflow's event payload matching GitHub's. | 192 | "SELECT * FROM workflows w WHERE w.repo_id = ?1 AND (w.path LIKE ?2 OR w.path LIKE 'managed/%') |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 193 | AND (w.error IS NULL OR w.error NOT LIKE 'Its file is%' |
| 194 | OR (w.id IN (SELECT workflow_id FROM runs WHERE repo_id = ?1) | |
| 195 | AND NOT EXISTS (SELECT 1 FROM workflows o WHERE o.repo_id = ?1 AND o.id <> w.id | |
| 196 | AND o.name = w.name AND (o.error IS NULL OR o.error NOT LIKE 'Its file is%')))) | |
| 197 | ORDER BY w.name", | |
| 198 | ) | |
| 199 | .bind(&[repo.id.as_str().into(), format!("{}/%", g1t_actions::workflow::FOLDER).into()])? | |
| 200 | .all() | |
| 201 | .await? | |
| 202 | .results::<WorkflowRow>()?; | |
| 203 | let mut out = Vec::with_capacity(rows.len()); | |
| 204 | for row in &rows { | |
| 205 | out.push(self.summary(row).await?); | |
| 206 | } | |
| 207 | Ok(Outcome::Ok(out)) | |
| 208 | } | |
| 209 | ||
| Merge branch 'worktree-agent-a4db4b523bb973765' | 210 | /// `workflow`: one workflow, by its id, file name, path or name, with its |
| 211 | /// file as of a branch or tag. | |
| 212 | pub async fn workflow(&self, a: WorkflowArgs) -> Result<Outcome<WorkflowDetail>> { | |
| 213 | let Some(repo) = self.visible_repo(&a.repo, &a.viewer).await? else { | |
| 214 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); | |
| 215 | }; | |
| 216 | let ws = self.workspace_actor(&repo.namespace).await?; | |
| 217 | if !self.synced(&repo.id).await? | |
| 218 | && let Some(ws) = &ws | |
| 219 | { | |
| 220 | self.sync(&repo, ws).await?; | |
| 221 | } | |
| 222 | let rows = self | |
| 223 | .db | |
| 224 | .prepare("SELECT * FROM workflows WHERE repo_id = ? ORDER BY name") | |
| 225 | .bind(&[repo.id.as_str().into()])? | |
| 226 | .all() | |
| 227 | .await? | |
| 228 | .results::<WorkflowRow>()?; | |
| 229 | let Some(row) = pick_workflow(&rows, &a.workflow) else { | |
| 230 | return Ok(fail(FailureCode::NotFound, format!("There is no workflow {} in {}/{}.", a.workflow.trim(), repo.namespace, repo.name))); | |
| 231 | }; | |
| 232 | let workflow = self.summary(row).await?; | |
| 233 | let (git_ref, source) = match a.git_ref.as_deref().map(str::trim).filter(|r| !r.is_empty()) { | |
| 234 | None => (repo.default_branch.clone(), row.source.clone()), | |
| 235 | Some(wanted) => { | |
| 236 | let Some(ws) = &ws else { | |
| 237 | return Ok(fail(FailureCode::NotFound, "There is no such workspace.")); | |
| 238 | }; | |
| 239 | let short = wanted.trim_start_matches("refs/heads/").trim_start_matches("refs/tags/"); | |
| 240 | let read = self.read_for(&repo, ws, Some(short)).await?; | |
| 241 | if read.head.is_none() { | |
| 242 | return Ok(fail(FailureCode::NotFound, format!("There is no branch or tag called {short}."))); | |
| 243 | } | |
| 244 | let Some(file) = read.files.into_iter().find(|file| file.path == row.path) else { | |
| 245 | return Ok(fail(FailureCode::NotFound, format!("{} is not on {short}.", row.path))); | |
| 246 | }; | |
| 247 | (short.to_owned(), file.source) | |
| 248 | } | |
| 249 | }; | |
| 250 | Ok(Outcome::Ok(WorkflowDetail { workflow, git_ref, source })) | |
| 251 | } | |
| 252 | ||
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 253 | pub async fn runs(&self, a: RunsArgs) -> Result<Outcome<Vec<WorkflowRun>>> { |
| 254 | let Some(repo) = self.visible_repo(&a.repo, &a.viewer).await? else { | |
| 255 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); | |
| 256 | }; | |
| 257 | let mut sql = "SELECT * FROM runs WHERE repo_id = ?".to_owned(); | |
| 258 | let mut binds: Vec<worker::wasm_bindgen::JsValue> = vec![repo.id.as_str().into()]; | |
| 259 | if let Some(workflow) = &a.workflow { | |
| 260 | sql.push_str(" AND (workflow_id = ? OR path = ? OR path = ?)"); | |
| 261 | binds.push(workflow.as_str().into()); | |
| 262 | binds.push(workflow.as_str().into()); | |
| 263 | binds.push(format!("{}/{workflow}", g1t_actions::workflow::FOLDER).into()); | |
| 264 | } | |
| 265 | if let Some(branch) = &a.branch { | |
| 266 | sql.push_str(" AND (git_ref = ? OR json_extract(info, '$.headRef') = ?)"); | |
| 267 | binds.push(format!("refs/heads/{branch}").into()); | |
| 268 | binds.push(branch.as_str().into()); | |
| 269 | } | |
| 270 | if let Some(event) = &a.event { | |
| 271 | sql.push_str(" AND event = ?"); | |
| 272 | binds.push(event.as_str().into()); | |
| 273 | } | |
| 274 | if let Some(pull) = a.pull { | |
| 275 | sql.push_str(" AND pull = ?"); | |
| 276 | binds.push(pull.into()); | |
| 277 | } | |
| 278 | if let Some(sha) = &a.sha { | |
| 279 | sql.push_str(" AND sha = ?"); | |
| 280 | binds.push(sha.as_str().into()); | |
| 281 | } | |
| 282 | sql.push_str(" ORDER BY id DESC LIMIT ?"); | |
| 283 | binds.push(a.limit.unwrap_or(RUNS_SHOWN).clamp(1, 100).into()); | |
| 284 | let rows = self.db.prepare(sql).bind(&binds)?.all().await?.results::<RunRow>()?; | |
| 285 | Ok(Outcome::Ok(rows.iter().map(RunRow::summary).collect())) | |
| 286 | } | |
| 287 | ||
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 288 | /// Every attempt of a run, oldest first, the current one last. |
| 289 | async fn attempts_of(&self, run: &RunRow) -> Result<Vec<RunAttempt>> { | |
| 290 | let mut attempts: Vec<RunAttempt> = self | |
| 291 | .db | |
| 292 | .prepare("SELECT attempt, conclusion, actor, debug, started_at, finished_at FROM run_attempts WHERE run_id = ? ORDER BY attempt") | |
| 293 | .bind(&[run.id.as_str().into()])? | |
| 294 | .all() | |
| 295 | .await? | |
| 296 | .results::<AttemptRow>()? | |
| 297 | .into_iter() | |
| 298 | .filter(|row| row.attempt < run.attempt) | |
| 299 | .map(|row| RunAttempt { | |
| 300 | attempt: row.attempt, | |
| 301 | status: "completed".to_owned(), | |
| 302 | conclusion: row.conclusion, | |
| 303 | actor: row.actor, | |
| 304 | debug: row.debug != 0, | |
| 305 | started_at: row.started_at, | |
| 306 | finished_at: row.finished_at, | |
| 307 | }) | |
| 308 | .collect(); | |
| 309 | attempts.push(RunAttempt { | |
| 310 | attempt: run.attempt, | |
| 311 | status: run.status.clone(), | |
| 312 | conclusion: run.conclusion.clone().filter(|_| run.status == "completed"), | |
| 313 | actor: run.triggering_actor.clone().or_else(|| run.actor.clone()), | |
| 314 | debug: run.debug != 0, | |
| 315 | started_at: run.started_at.clone(), | |
| 316 | finished_at: run.finished_at.clone(), | |
| 317 | }); | |
| 318 | Ok(attempts) | |
| 319 | } | |
| 320 | ||
| 321 | /// The jobs of one attempt: the live ones for the current attempt, the | |
| 322 | /// kept ones for an earlier attempt. None for an attempt it never had. | |
| 323 | async fn attempt_jobs(&self, run: &RunRow, attempt: Option<u64>) -> Result<Option<AttemptJobs>> { | |
| 324 | match attempt.filter(|n| *n != run.attempt) { | |
| 325 | None => { | |
| A run opens on its summary: what triggered it, its status, duration and artifacts, a graph of its jobs (what needs what, matrices folded, called workflows boxed, deploys with their address), annotations, and each job's summary; the job list groups the same way | 326 | // A job that deploys: where to, as its `environment.url` reads. |
| 327 | let jobs: Vec<Job> = self | |
| 328 | .job_rows(&run.id) | |
| 329 | .await? | |
| 330 | .into_iter() | |
| 331 | .map(|row| { | |
| 332 | let environment_url = row.environment.as_ref().and_then(|_| crate::plan::deploys_to(run, &row)).and_then(|env| env.url); | |
| 333 | Job { environment_url, ..job_view(row) } | |
| 334 | }) | |
| 335 | .collect(); | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 336 | let log_ids = jobs.iter().map(|job| job.id.clone()).collect(); |
| 337 | Ok(Some(AttemptJobs { jobs, log_ids })) | |
| 338 | } | |
| 339 | Some(n) if n == 0 || n > run.attempt => Ok(None), | |
| 340 | Some(n) => { | |
| 341 | let rows = self | |
| 342 | .db | |
| 343 | .prepare("SELECT * FROM job_attempts WHERE run_id = ? AND attempt = ? ORDER BY rowid") | |
| 344 | .bind(&[run.id.as_str().into(), (n as f64).into()])? | |
| 345 | .all() | |
| 346 | .await? | |
| 347 | .results::<AttemptJobRow>()?; | |
| 348 | let log_ids = rows.iter().map(|row| row.log_id.clone()).collect(); | |
| 349 | Ok(Some(AttemptJobs { jobs: rows.into_iter().map(attempt_job_view).collect(), log_ids })) | |
| 350 | } | |
| 351 | } | |
| 352 | } | |
| 353 | ||
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 354 | pub async fn run(&self, a: RunArgs) -> Result<Outcome<RunDetail>> { |
| 355 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { | |
| 356 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); | |
| 357 | } | |
| 358 | let run = check!(self.run_in(&a.repo, &a.id).await?); | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 359 | let Some(AttemptJobs { jobs, .. }) = self.attempt_jobs(&run, a.attempt).await? else { |
| 360 | return Ok(fail(FailureCode::NotFound, format!("This run has no attempt {}.", a.attempt.unwrap_or_default()))); | |
| 361 | }; | |
| 362 | let attempts = self.attempts_of(&run).await?; | |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 363 | let mut summary = run.summary(); |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 364 | // An earlier attempt: as it ended, and nothing waits for it. |
| 365 | if let Some(earlier) = a.attempt.filter(|n| *n != run.attempt).and_then(|n| attempts.iter().find(|at| at.attempt == n)) { | |
| 366 | summary.attempt = earlier.attempt; | |
| 367 | summary.status = "completed".to_owned(); | |
| 368 | summary.conclusion = earlier.conclusion.clone(); | |
| 369 | summary.started_at = earlier.started_at.clone(); | |
| 370 | summary.finished_at = earlier.finished_at.clone(); | |
| 371 | return Ok(Outcome::Ok(RunDetail { | |
| 372 | notes: notes(&run.source), | |
| 373 | run: summary, | |
| 374 | jobs, | |
| 375 | approval: run.approval(), | |
| 376 | pending_deployments: Vec::new(), | |
| 377 | attempts, | |
| 378 | })); | |
| 379 | } | |
| 380 | let pending_deployments = self.pending_for(&run, &a.viewer).await?; | |
| Merge the run page fixes: Cancel run shows on every view of a run that is still going, including an earlier attempt's and job links, and pages refresh when a run is re-run from anywhere; a job's log follows to its true end, above anything covering the bottom of the window, and Jump to latest lands there. | 381 | summary.status = shown_status(&summary.status, jobs.iter().map(|job| job.status.as_str())); |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 382 | Ok(Outcome::Ok(RunDetail { |
| 383 | notes: notes(&run.source), | |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 384 | run: summary, |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 385 | jobs, |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 386 | approval: run.approval(), |
| 387 | pending_deployments, | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 388 | attempts, |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 389 | })) |
| 390 | } | |
| 391 | ||
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 392 | /// A job of the repository's runs by the id a run's page gives it: a |
| 393 | /// live job, or one of an earlier attempt. Its name, steps, where its | |
| 394 | /// logs and summary are kept, and whether it has finished. | |
| 395 | async fn job_for_log(&self, repo: &g1t_contracts::repos::RepoPath, id: &str) -> Result<Option<(Job, String, bool)>> { | |
| 396 | let full = format!("{}/{}", repo.namespace, repo.name); | |
| 397 | let live = self | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 398 | .db |
| 399 | .prepare("SELECT jobs.* FROM jobs JOIN runs ON runs.id = jobs.run_id WHERE jobs.id = ? AND lower(runs.repo) = lower(?)") | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 400 | .bind(&[id.into(), full.as_str().into()])? |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 401 | .first::<JobRow>(None) |
| 402 | .await?; | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 403 | if let Some(job) = live { |
| 404 | let done = job.status == "completed"; | |
| 405 | let view = job_view(job); | |
| 406 | let log_id = view.id.clone(); | |
| 407 | return Ok(Some((view, log_id, done))); | |
| 408 | } | |
| 409 | let kept = self | |
| 410 | .db | |
| 411 | .prepare( | |
| 412 | "SELECT job_attempts.* FROM job_attempts JOIN runs ON runs.id = job_attempts.run_id | |
| 413 | WHERE job_attempts.id = ? AND lower(runs.repo) = lower(?)", | |
| 414 | ) | |
| 415 | .bind(&[id.into(), full.as_str().into()])? | |
| 416 | .first::<AttemptJobRow>(None) | |
| 417 | .await?; | |
| 418 | Ok(kept.map(|row| { | |
| 419 | let log_id = row.log_id.clone(); | |
| 420 | (attempt_job_view(row), log_id, true) | |
| 421 | })) | |
| 422 | } | |
| 423 | ||
| 424 | async fn log_chunks(&self, log_id: &str, after: u64, limit: u32) -> Result<Vec<LogChunk>> { | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 425 | #[derive(Deserialize)] |
| 426 | struct Row { | |
| 427 | seq: u64, | |
| 428 | step: u32, | |
| 429 | text: String, | |
| 430 | } | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 431 | Ok(self |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 432 | .db |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 433 | .prepare("SELECT seq, step, text FROM logs WHERE job_id = ? AND seq > ? ORDER BY seq LIMIT ?") |
| 434 | .bind(&[log_id.into(), (after as f64).into(), limit.into()])? | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 435 | .all() |
| 436 | .await? | |
| 437 | .results::<Row>()? | |
| 438 | .into_iter() | |
| 439 | .map(|row| LogChunk { seq: row.seq, step: row.step, text: row.text }) | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 440 | .collect()) |
| 441 | } | |
| 442 | ||
| 443 | /// Every chunk of a job's log, a page at a time. | |
| 444 | async fn whole_log(&self, log_id: &str) -> Result<Vec<LogChunk>> { | |
| 445 | let mut chunks: Vec<LogChunk> = Vec::new(); | |
| 446 | loop { | |
| 447 | let after = chunks.last().map_or(0, |chunk| chunk.seq); | |
| 448 | let page = self.log_chunks(log_id, after, 500).await?; | |
| 449 | let more = page.len() == 500; | |
| 450 | chunks.extend(page); | |
| 451 | if !more { | |
| 452 | return Ok(chunks); | |
| 453 | } | |
| 454 | } | |
| 455 | } | |
| 456 | ||
| 457 | pub async fn logs(&self, a: LogsArgs) -> Result<Outcome<JobLog>> { | |
| 458 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { | |
| 459 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); | |
| 460 | } | |
| 461 | let Some((_, log_id, done)) = self.job_for_log(&a.repo, &a.job).await? else { | |
| 462 | return Ok(fail(FailureCode::NotFound, "No such job.")); | |
| 463 | }; | |
| 464 | let chunks = self.log_chunks(&log_id, a.after, 500).await?; | |
| 465 | Ok(Outcome::Ok(JobLog { chunks, done })) | |
| 466 | } | |
| 467 | ||
| 468 | /// `job_log_text`: a job's whole log, to download. | |
| 469 | pub async fn job_log_text(&self, a: JobLogTextArgs) -> Result<Outcome<JobLogText>> { | |
| 470 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { | |
| 471 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); | |
| 472 | } | |
| 473 | let Some((job, log_id, done)) = self.job_for_log(&a.repo, &a.job).await? else { | |
| 474 | return Ok(fail(FailureCode::NotFound, "No such job.")); | |
| 475 | }; | |
| 476 | let chunks = self.whole_log(&log_id).await?; | |
| 477 | Ok(Outcome::Ok(JobLogText { job_id: job.id, name: job.name, steps: job.steps, chunks, done, omitted: false })) | |
| 478 | } | |
| 479 | ||
| 480 | /// `run_logs`: every job's whole log for one attempt, to download as one | |
| 481 | /// archive. | |
| 482 | pub async fn run_logs(&self, a: RunLogsArgs) -> Result<Outcome<Vec<JobLogText>>> { | |
| 483 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { | |
| 484 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); | |
| 485 | } | |
| 486 | let run = check!(self.run_in(&a.repo, &a.id).await?); | |
| 487 | let Some(AttemptJobs { jobs, log_ids }) = self.attempt_jobs(&run, a.attempt).await? else { | |
| 488 | return Ok(fail(FailureCode::NotFound, format!("This run has no attempt {}.", a.attempt.unwrap_or_default()))); | |
| 489 | }; | |
| 490 | let mut out = Vec::with_capacity(jobs.len()); | |
| 491 | let mut total = 0usize; | |
| 492 | for (job, log_id) in jobs.into_iter().zip(log_ids) { | |
| 493 | let done = job.status == "completed"; | |
| 494 | let omitted = total >= MAX_RUN_LOG_BYTES; | |
| 495 | let chunks = if omitted { Vec::new() } else { self.whole_log(&log_id).await? }; | |
| 496 | total += chunks.iter().map(|chunk| chunk.text.len()).sum::<usize>(); | |
| 497 | out.push(JobLogText { job_id: job.id, name: job.name, steps: job.steps, chunks, done, omitted }); | |
| 498 | } | |
| 499 | Ok(Outcome::Ok(out)) | |
| 500 | } | |
| 501 | ||
| 502 | /// `summaries`: what each job's steps wrote to `$GITHUB_STEP_SUMMARY`. | |
| 503 | pub async fn summaries(&self, a: SummariesArgs) -> Result<Outcome<Vec<JobSummary>>> { | |
| 504 | if self.visible_repo(&a.repo, &a.viewer).await?.is_none() { | |
| 505 | return Ok(fail(FailureCode::NotFound, "There is no such repository.")); | |
| 506 | } | |
| 507 | let run = check!(self.run_in(&a.repo, &a.id).await?); | |
| 508 | let Some(AttemptJobs { jobs, log_ids }) = self.attempt_jobs(&run, a.attempt).await? else { | |
| 509 | return Ok(fail(FailureCode::NotFound, format!("This run has no attempt {}.", a.attempt.unwrap_or_default()))); | |
| 510 | }; | |
| 511 | #[derive(Deserialize)] | |
| 512 | struct Row { | |
| 513 | job_id: String, | |
| 514 | step: u32, | |
| 515 | markdown: String, | |
| 516 | } | |
| 517 | let rows = self | |
| 518 | .db | |
| 519 | .prepare("SELECT job_id, step, markdown FROM job_summaries WHERE job_id IN (SELECT value FROM json_each(?)) ORDER BY step") | |
| 520 | .bind(&[serde_json::to_string(&log_ids)?.into()])? | |
| 521 | .all() | |
| 522 | .await? | |
| 523 | .results::<Row>()?; | |
| 524 | Ok(Outcome::Ok( | |
| 525 | jobs.into_iter() | |
| 526 | .zip(log_ids) | |
| 527 | .filter_map(|(job, log_id)| { | |
| 528 | let steps: Vec<StepSummary> = rows | |
| 529 | .iter() | |
| 530 | .filter(|row| row.job_id == log_id) | |
| 531 | .map(|row| StepSummary { step: row.step, markdown: row.markdown.clone() }) | |
| 532 | .collect(); | |
| 533 | (!steps.is_empty()).then_some(JobSummary { job_id: job.id, name: job.name, steps }) | |
| 534 | }) | |
| 535 | .collect(), | |
| 536 | )) | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 537 | } |
| 538 | ||
| 539 | pub async fn set_workflow_enabled(&self, a: SetWorkflowEnabledArgs) -> Result<Outcome<Workflow>> { | |
| Merge GitHub pull request #8 (claude/cool-newton-7nm8r9): Docker deployments on g1t.page behind a switch that stays off until Cloudflare's container APIs are checked live, workflows a workspace manages in its repositories, tarball and zipball downloads, refs/pull/* kept to g1t alone, framework detection for g1t.page builds, and a workflow's event payload matching GitHub's. | 540 | let repo = match self.may(&a.actor, &a.repo, Capability::ManageSettings).await? { |
| 541 | Outcome::Ok(repo) => repo, | |
| 542 | Outcome::Fail(refused) => return Ok(Outcome::Fail(refused)), | |
| 543 | }; | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 544 | let wanted = a.workflow.trim_start_matches(".g1t/workflows/"); |
| 545 | let row = self | |
| 546 | .db | |
| 547 | .prepare("SELECT * FROM workflows WHERE lower(repo) = lower(?) AND (id = ? OR path = ?)") | |
| 548 | .bind(&[ | |
| 549 | format!("{}/{}", a.repo.namespace, a.repo.name).into(), | |
| 550 | a.workflow.as_str().into(), | |
| 551 | format!("{}/{wanted}", g1t_actions::workflow::FOLDER).into(), | |
| 552 | ])? | |
| 553 | .first::<WorkflowRow>(None) | |
| 554 | .await?; | |
| 555 | let Some(row) = row else { | |
| 556 | return Ok(fail(FailureCode::NotFound, "No such workflow.")); | |
| 557 | }; | |
| Merge GitHub pull request #8 (claude/cool-newton-7nm8r9): Docker deployments on g1t.page behind a switch that stays off until Cloudflare's container APIs are checked live, workflows a workspace manages in its repositories, tarball and zipball downloads, refs/pull/* kept to g1t alone, framework detection for g1t.page builds, and a workflow's event payload matching GitHub's. | 558 | // A workspace's required workflow (managed.rs) stays on. |
| 559 | if !a.enabled && self.required_here(&repo, &row.path).await? { | |
| 560 | return Ok(fail( | |
| 561 | FailureCode::Forbidden, | |
| 562 | format!("{} is required by {}: only its owners can change where it runs, under its Settings, Actions.", row.name, repo.namespace), | |
| 563 | )); | |
| 564 | } | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 565 | let state = if a.enabled { "active" } else { "disabled" }; |
| 566 | self.db.prepare("UPDATE workflows SET state = ? WHERE id = ?").bind(&[state.into(), row.id.as_str().into()])?.run().await?; | |
| 567 | let row = WorkflowRow { state: state.to_owned(), ..row }; | |
| 568 | Ok(Outcome::Ok(self.summary(&row).await?)) | |
| 569 | } | |
| Merge checks: statuses and check runs on every commit | 570 | |
| 571 | /// `check_runs`: workflow runs with their jobs, by commits, by a run's | |
| 572 | /// id or by one of its jobs' ids, newest first, for the work service to | |
| 573 | /// show as check suites and check runs. It decides who may see them. | |
| 574 | pub async fn check_runs(&self, a: ActionsChecksArgs) -> Result<Vec<RunDetail>> { | |
| 575 | let runs: Vec<RunRow> = if let Some(job) = &a.job_id { | |
| 576 | self.db | |
| 577 | .prepare("SELECT runs.* FROM runs JOIN jobs ON jobs.run_id = runs.id WHERE jobs.id = ? AND runs.repo_id = ?") | |
| 578 | .bind(&[job.as_str().into(), a.repo_id.as_str().into()])? | |
| 579 | .all() | |
| 580 | .await? | |
| 581 | .results::<RunRow>()? | |
| 582 | } else if let Some(run) = &a.run_id { | |
| 583 | self.db | |
| 584 | .prepare("SELECT * FROM runs WHERE id = ? AND repo_id = ?") | |
| 585 | .bind(&[run.as_str().into(), a.repo_id.as_str().into()])? | |
| 586 | .all() | |
| 587 | .await? | |
| 588 | .results::<RunRow>()? | |
| 589 | } else if a.shas.is_empty() { | |
| 590 | Vec::new() | |
| 591 | } else { | |
| 592 | let shas: Vec<&String> = a.shas.iter().take(MAX_COMMITS).collect(); | |
| 593 | let marks = vec!["?"; shas.len()].join(", "); | |
| 594 | let mut binds: Vec<worker::wasm_bindgen::JsValue> = vec![a.repo_id.as_str().into()]; | |
| 595 | binds.extend(shas.iter().map(|sha| sha.as_str().into())); | |
| 596 | binds.push(CHECK_RUNS_LIMIT.into()); | |
| 597 | self.db | |
| 598 | .prepare(format!("SELECT * FROM runs WHERE repo_id = ? AND sha IN ({marks}) ORDER BY id DESC LIMIT ?")) | |
| 599 | .bind(&binds)? | |
| 600 | .all() | |
| 601 | .await? | |
| 602 | .results::<RunRow>()? | |
| 603 | }; | |
| 604 | if runs.is_empty() { | |
| 605 | return Ok(Vec::new()); | |
| 606 | } | |
| 607 | let marks = vec!["?"; runs.len()].join(", "); | |
| 608 | let ids: Vec<worker::wasm_bindgen::JsValue> = runs.iter().map(|run| run.id.as_str().into()).collect(); | |
| 609 | let jobs = self | |
| 610 | .db | |
| 611 | .prepare(format!("SELECT * FROM jobs WHERE run_id IN ({marks}) ORDER BY rowid")) | |
| 612 | .bind(&ids)? | |
| 613 | .all() | |
| 614 | .await? | |
| 615 | .results::<JobRow>()?; | |
| 616 | let mut by_run: std::collections::HashMap<String, Vec<Job>> = std::collections::HashMap::new(); | |
| 617 | for job in jobs { | |
| 618 | by_run.entry(job.run_id.clone()).or_default().push(job_view(job)); | |
| 619 | } | |
| 620 | Ok(runs | |
| 621 | .iter() | |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 622 | .map(|run| RunDetail { |
| 623 | run: run.summary(), | |
| 624 | jobs: by_run.remove(&run.id).unwrap_or_default(), | |
| 625 | notes: Vec::new(), | |
| 626 | approval: run.approval(), | |
| 627 | pending_deployments: Vec::new(), | |
| Merge Actions runs: summaries, attempts and re-runs, graceful cancel, log downloads, badges (actions 0009) | 628 | attempts: Vec::new(), |
| Merge branch 'worktree-agent-a3abfcce648e87dca' | 629 | }) |
| Merge checks: statuses and check runs on every commit | 630 | .collect()) |
| 631 | } | |
| Billing and Usage reconcile: own-provider runs leave Billing's at-price total, and Usage's not-charged part is at price less charged | 632 | } |
| Merge checks: statuses and check runs on every commit | 633 | |
| 634 | /// The most runs `check_runs` reads for a set of commits. | |
| 635 | const CHECK_RUNS_LIMIT: u32 = 200; | |
| Merge the run page fixes: Cancel run shows on every view of a run that is still going, including an earlier attempt's and job links, and pages refresh when a run is re-run from anywhere; a job's log follows to its true end, above anything covering the bottom of the window, and Jump to latest lands there. | 636 | |
| 637 | /// How the run's current attempt stands on its page: as its row says, and | |
| 638 | /// `waiting`, as on GitHub, while a job is held at an environment's rules. | |
| 639 | /// A job queued for a runner, or waiting for the jobs it needs, leaves a | |
| 640 | /// run that has started `in_progress`: it is still going. | |
| 641 | fn shown_status<'a>(status: &str, mut jobs: impl Iterator<Item = &'a str>) -> String { | |
| 642 | if matches!(status, "queued" | "in_progress") && jobs.any(|job| job == "pending") { | |
| 643 | "waiting".to_owned() | |
| 644 | } else { | |
| 645 | status.to_owned() | |
| 646 | } | |
| 647 | } | |
| 648 | ||
| 649 | #[cfg(test)] | |
| 650 | mod tests { | |
| 651 | use super::*; | |
| 652 | ||
| 653 | fn shown(status: &str, jobs: &[&str]) -> String { | |
| 654 | shown_status(status, jobs.iter().copied()) | |
| 655 | } | |
| 656 | ||
| 657 | #[test] | |
| 658 | fn a_job_queued_for_a_self_hosted_runner_keeps_its_run_going() { | |
| 659 | // A re-run of failed jobs: the job that failed now succeeded, and the | |
| 660 | // one that needs it waits for a runner with labels no runner has. | |
| 661 | assert_eq!(shown("in_progress", &["completed", "queued"]), "in_progress"); | |
| 662 | assert_eq!(shown("queued", &["waiting", "waiting"]), "queued"); | |
| 663 | } | |
| 664 | ||
| 665 | #[test] | |
| 666 | fn a_job_held_at_an_environment_makes_its_run_wait() { | |
| 667 | assert_eq!(shown("in_progress", &["completed", "pending"]), "waiting"); | |
| 668 | assert_eq!(shown("queued", &["pending"]), "waiting"); | |
| 669 | } | |
| 670 | ||
| 671 | #[test] | |
| 672 | fn a_finished_or_held_run_reads_as_its_row_says() { | |
| 673 | assert_eq!(shown("completed", &["completed"]), "completed"); | |
| 674 | assert_eq!(shown("action_required", &["waiting"]), "action_required"); | |
| 675 | assert_eq!(shown("pending", &["pending"]), "pending"); | |
| 676 | } | |
| 677 | } |
This file's history is long; its oldest lines are credited to the oldest commit read.