Skip to content

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

3,316 linesCodeBlameRaw
1//! A run's life: made, its jobs waiting on the jobs they need, each job
2//! skipped or expanded into its matrix and queued, started in a sandbox
3//! when its workspace has room, reporting its steps and logs as it goes,
4//! and finished; the run finishes with its last job.
5
6use g1t_actions::events::{RunInfo, runner_context};
7use g1t_actions::expr::{self, Scope, Status};
8use g1t_actions::matrix;
9use g1t_actions::workflow::{self, Workflow};
10use g1t_contracts::access::Capability;
11use g1t_contracts::actions::{JobCallArgs, RunActionArgs, RunApproval, StartJobArgs, WorkflowRun};
12use g1t_contracts::identity::{CreateJobTokenArgs, CreatedAccessToken, RevokeJobTokensArgs};
13use g1t_contracts::repos::{Repo, RepoPath};
14use g1t_contracts::time::rfc3339;
15use g1t_contracts::{FailureCode, Outcome, new_id};
16use g1t_kit::now_ms;
17use g1t_secrets::{random_hex, same, sha256_hex};
18use serde::Deserialize;
19use serde_json::{Map, Value, json};
20use worker::Result;
21
22use crate::broker::{self, Broker};
23use crate::protection::Gate;
24use crate::sync::WorkflowRow;
25use crate::{Actions, Count, MAX_TIMEOUT_MINUTES, SELF_HOSTED_MAX_TIMEOUT_MINUTES, SILENT_MS, SITE, check, fail, has_room, optional, repo_path};
26use g1t_contracts::runners::{Wanted, waiting_reason};
27
28/// The most log one job keeps, in bytes; past it, the log says so and stops.
29const MAX_LOG_BYTES: usize = 4 * 1024 * 1024;
30/// The most a single log report may add.
31const MAX_CHUNK_BYTES: usize = 256 * 1024;
32const MAX_ANNOTATIONS: usize = 50;
33/// Swaps a running job's token for a new one, only while it still has the
34/// one the caller showed (`job_spec` with `rotate`), keeping the hash of
35/// the one it started with for `brokered_secrets` (migration 0020).
36const TOKEN_ROTATE: &str = "UPDATE jobs SET first_token_hash = COALESCE(first_token_hash, token_hash), token_hash = ?1
37 WHERE id = ?2 AND status = 'in_progress' AND token_hash = ?3 RETURNING id";
38
39/// Whether `token` is a running job's: its current one, or with `started`
40/// (`brokered_secrets` only) the one it started with before its harness
41/// swapped it.
42fn token_opens(current: Option<&str>, first: Option<&str>, token: &str, started: bool) -> bool {
43 let hash = sha256_hex(token);
44 current.is_some_and(|h| same(h, &hash)) || (started && first.is_some_and(|h| same(h, &hash)))
45}
46/// A batch of a job's log, under the next `seq` of that job's, worked out
47/// in the same statement (SQLite runs one write at a time). `?4` is the
48/// runner's number for the batch (null from runners that send none): a
49/// batch sent again, after an answer the runner did not hear, has the
50/// number of one already kept, and is not kept twice (migration 0016).
51pub(crate) const LOG_INSERT: &str = "INSERT INTO logs (job_id, seq, step, text, chunk)
52 SELECT ?1, COALESCE(MAX(seq), 0) + 1, ?2, ?3, ?4 FROM logs WHERE job_id = ?1
53 ON CONFLICT (job_id, chunk) DO NOTHING";
54/// The most one step's job summary keeps, in bytes, and how many steps of a
55/// job may have one, as on GitHub.
56pub(crate) const MAX_SUMMARY_BYTES: usize = 1024 * 1024;
57pub(crate) const MAX_SUMMARIES: u32 = 20;
58
59/// Whether a step's summary of `adding` bytes is kept: a job keeps up to
60/// 20 steps' summaries (`steps` it has, `mine` this step's bytes so far)
61/// of up to 1 MiB each.
62pub(crate) fn summary_fits(steps: u32, mine: Option<usize>, adding: usize) -> bool {
63 if adding == 0 {
64 return false;
65 }
66 match mine {
67 Some(used) => used + adding <= MAX_SUMMARY_BYTES,
68 None => steps < MAX_SUMMARIES && adding <= MAX_SUMMARY_BYTES,
69 }
70}
71
72/// The repository whose unfinished runs `event` stops, by id: one deleted,
73/// or archived (not unarchived).
74pub fn stops_runs(event: &g1t_contracts::events::Event) -> Option<String> {
75 let stops = match event.kind.as_str() {
76 "repo.deleted" => true,
77 "repo.archived" => event.data["archived"].as_bool() != Some(false),
78 _ => false,
79 };
80 if !stops {
81 return None;
82 }
83 event.repo_id.clone().or_else(|| event.data["repoId"].as_str().map(str::to_owned))
84}
85
86pub struct NewRun {
87 pub repo: Repo,
88 pub path: String,
89 pub source: String,
90 pub workflow: Workflow,
91 pub info: RunInfo,
92 pub action: Option<String>,
93 pub pull: Option<u32>,
94 pub title: String,
95 pub inputs: Map<String, Value>,
96 pub event_key: String,
97 pub actor_id: Option<String>,
98 pub actor: Option<String>,
99 pub trusted: bool,
100 /// Why the run waits for someone with the Write role to approve it
101 /// before anything starts: a pull request from outside (protection.rs).
102 pub approval: Option<String>,
103 /// The commit the run is listed, and its statuses and checks reported,
104 /// on when it is not the one it builds (`info.sha`): a pull request's
105 /// head, when the run builds its test merge commit, as on GitHub.
106 pub head_sha: Option<String>,
107}
108
109#[derive(Clone, Deserialize)]
110pub struct RunRow {
111 pub id: String,
112 pub workflow_id: String,
113 pub repo_id: String,
114 pub repo: String,
115 pub path: String,
116 pub name: String,
117 pub title: String,
118 pub number: u64,
119 pub attempt: u64,
120 pub event: String,
121 pub action: Option<String>,
122 pub git_ref: String,
123 pub sha: String,
124 pub pull: Option<u32>,
125 pub status: String,
126 pub conclusion: Option<String>,
127 pub error: Option<String>,
128 pub actor: Option<String>,
129 pub actor_id: Option<String>,
130 pub source: String,
131 pub info: String,
132 pub inputs: String,
133 pub trusted: u32,
134 pub concurrency_group: Option<String>,
135 pub created_at: String,
136 pub started_at: Option<String>,
137 pub finished_at: Option<String>,
138 /// JSON `RunApproval`, for a run that needed approval (migration 0006).
139 #[serde(default)]
140 pub approval: Option<String>,
141 /// Whether its concurrency group cancels what it replaces.
142 #[serde(default)]
143 pub cancel_in_progress: u32,
144 /// Who started the current attempt, once it is re-run (migration 0009).
145 #[serde(default)]
146 pub triggering_actor: Option<String>,
147 /// The current attempt runs with debug logging.
148 #[serde(default)]
149 pub debug: u32,
150}
151
152impl RunRow {
153 pub fn approval(&self) -> Option<RunApproval> {
154 self.approval.as_deref().and_then(|text| serde_json::from_str(text).ok())
155 }
156
157 pub fn info(&self) -> RunInfo {
158 let mut info: RunInfo = serde_json::from_str(&self.info).unwrap_or_default();
159 info.run_id = self.id.clone();
160 info.run_number = self.number;
161 info.run_attempt = self.attempt;
162 info.workflow_path = self.path.clone();
163 if info.workflow.is_empty() {
164 info.workflow = self.name.clone();
165 }
166 info
167 }
168
169 pub fn inputs(&self) -> Map<String, Value> {
170 serde_json::from_str(&self.inputs).unwrap_or_default()
171 }
172
173 pub fn summary(&self) -> WorkflowRun {
174 WorkflowRun {
175 id: self.id.clone(),
176 workflow_id: self.workflow_id.clone(),
177 path: self.path.clone(),
178 name: self.name.clone(),
179 title: self.title.clone(),
180 number: self.number,
181 attempt: self.attempt,
182 event: self.event.clone(),
183 git_ref: self.git_ref.clone(),
184 sha: self.sha.clone(),
185 pull: self.pull,
186 status: self.status.clone(),
187 conclusion: self.conclusion.clone(),
188 error: self.error.clone(),
189 actor: self.actor.clone(),
190 created_at: self.created_at.clone(),
191 started_at: self.started_at.clone(),
192 finished_at: self.finished_at.clone(),
193 }
194 }
195}
196
197#[derive(Clone, Deserialize)]
198pub struct JobRow {
199 pub id: String,
200 pub run_id: String,
201 pub repo_id: String,
202 pub namespace: String,
203 pub key: String,
204 pub ordinal: u32,
205 pub name: String,
206 pub needs: String,
207 pub matrix: Option<String>,
208 pub status: String,
209 pub conclusion: Option<String>,
210 pub steps: String,
211 pub annotations: String,
212 pub outputs: String,
213 pub reason: Option<String>,
214 pub token_hash: Option<String>,
215 pub timeout_minutes: u32,
216 pub continue_on_error: u32,
217 pub max_parallel: Option<u32>,
218 /// Set for a job that calls a reusable workflow, and for that
219 /// workflow's jobs (see migration 0002).
220 pub call: Option<String>,
221 pub seen_at: Option<String>,
222 pub started_at: Option<String>,
223 pub finished_at: Option<String>,
224 /// For a job whose `runs-on` names self-hosted runners: what it asks
225 /// for, as a JSON array (see `g1t_contracts::runners::Wanted`), when it
226 /// started waiting, and the runner that took it (migration 0004).
227 #[serde(default)]
228 pub labels: Option<String>,
229 #[serde(default)]
230 pub queued_at: Option<String>,
231 #[serde(default)]
232 pub runner_id: Option<String>,
233 #[serde(default)]
234 pub runner_name: Option<String>,
235 /// The environment it names, read when its needs were done; a job its
236 /// rules hold is `pending` (migration 0006).
237 #[serde(default)]
238 pub environment: Option<String>,
239 /// Its own `concurrency` group, and whether that cancels what it replaces.
240 #[serde(default)]
241 pub concurrency_group: Option<String>,
242 #[serde(default)]
243 pub cancel_in_progress: u32,
244 /// When it was told to stop, while it runs its cleanup steps
245 /// (migration 0009).
246 #[serde(default)]
247 pub cancel_requested_at: Option<String>,
248 /// Whether it was given stand-ins for brokered secrets (migration
249 /// 0019), so its log is masked for their values too.
250 #[serde(default)]
251 pub brokered: u32,
252 /// The hash of the token it started with, once its harness swapped that
253 /// for another (migration 0020): good for `brokered_secrets` only.
254 #[serde(default)]
255 pub first_token_hash: Option<String>,
256 /// Since when it has waited for a machine the runner had none of
257 /// (migration 0025).
258 #[serde(default)]
259 pub waiting_since: Option<String>,
260}
261
262/// How long a cancelled job has to run its `if: always()` and `cancelled()`
263/// steps and its post steps before it is stopped outright, as on GitHub.
264pub const CANCEL_GRACE_MS: u64 = 5 * 60 * 1000;
265
266/// Which jobs a re-run runs again.
267#[derive(Clone, Copy, Debug, PartialEq)]
268pub enum Rerun<'a> {
269 All,
270 /// Those that did not succeed.
271 Failed,
272 /// One job's key.
273 Job(&'a str),
274}
275
276/// The keys a re-run runs again, in `order`: those `which` names and,
277/// transitively, every key that needs one of them. `needs` gives a key's
278/// needs; `succeeded` whether every job of a key succeeded.
279pub fn rerun_keys(order: &[&str], needs: impl Fn(&str) -> Vec<String>, succeeded: impl Fn(&str) -> bool, which: Rerun) -> Vec<String> {
280 let mut again: Vec<String> = Vec::new();
281 for key in order {
282 let named = match which {
283 Rerun::All => true,
284 Rerun::Failed => !succeeded(key),
285 Rerun::Job(job) => *key == job,
286 };
287 if named || needs(key).iter().any(|need| again.contains(need)) {
288 again.push((*key).to_owned());
289 }
290 }
291 again
292}
293
294/// The key under `jobs:` a job belongs to: a called workflow's jobs
295/// (`build/test`, or `build[1]/test` for a matrix's second call) run again
296/// with the job that calls it (`build`).
297pub fn top_key(key: &str) -> &str {
298 let first = key.split('/').next().unwrap_or(key);
299 first.split('[').next().unwrap_or(first)
300}
301
302/// What the keys of the jobs a caller's call makes start with: the
303/// caller's key, and for a matrix the combination's index after it
304/// (`build[1]`), so each combination's call has jobs of its own. A job id
305/// has no `[`, so the two never meet.
306fn call_prefix(key: &str, index: Option<usize>) -> String {
307 match index {
308 Some(index) => format!("{key}[{index}]"),
309 None => key.to_owned(),
310 }
311}
312
313/// Whether a run may call one more reusable workflow, `file`, `depth`
314/// levels below the workflow it started from, having called `called`
315/// already (one name per call; repeats are one workflow). As on GitHub: ten
316/// levels of workflows at most, the top one and nine reusable ones below
317/// it, and 50 different reusable workflows in a run.
318fn call_allowed(depth: u64, called: &[&str], file: &str) -> std::result::Result<(), String> {
319 if depth > MAX_CALL_DEPTH {
320 return Err(format!(
321 "`{file}` would be the {}th level of workflows: a run connects at most ten, the workflow it started from and nine levels of reusable workflows below it.",
322 depth + 1
323 ));
324 }
325 let mut unique: Vec<&str> = called.to_vec();
326 unique.push(file);
327 unique.sort_unstable();
328 unique.dedup();
329 if unique.len() > MAX_CALLED_WORKFLOWS {
330 return Err(format!("Calling `{file}` would make {} reusable workflows in this run: a run calls at most {MAX_CALLED_WORKFLOWS} different ones.", unique.len()));
331 }
332 Ok(())
333}
334
335/// What a job is shown as: its `name` (else its id), under the job whose
336/// call made it (`caller`), read with its matrix when it has an
337/// expression, else with the matrix's values after it.
338fn shown_name(job: &workflow::Job, caller: Option<&str>, combination: &Map<String, Value>, scope: &Scope) -> String {
339 let base = job.name.clone().unwrap_or(job.id.clone());
340 let base = match caller {
341 Some(caller) => format!("{caller} / {base}"),
342 None => base,
343 };
344 if expr::has_expression(&base) {
345 expr::interpolate(&base, scope).unwrap_or(base)
346 } else if job.matrix.is_some() {
347 matrix::job_name(&base, combination)
348 } else {
349 base
350 }
351}
352
353/// Debug logging for a job, as a re-run with it turned on gives GitHub's:
354/// `RUNNER_DEBUG=1` and `runner.debug`, and `ACTIONS_STEP_DEBUG` and
355/// `ACTIONS_RUNNER_DEBUG` set, which the runner reads as the secrets of
356/// those names (`::debug::` lines shown, and how each step's `if` read).
357pub fn debug_logging(variables: &mut Map<String, Value>, runner: &mut Value) {
358 variables.insert("RUNNER_DEBUG".into(), json!("1"));
359 variables.insert("ACTIONS_STEP_DEBUG".into(), json!("true"));
360 variables.insert("ACTIONS_RUNNER_DEBUG".into(), json!("true"));
361 runner["debug"] = json!("1");
362}
363
364impl JobRow {
365 pub fn needs(&self) -> Vec<String> {
366 serde_json::from_str(&self.needs).unwrap_or_default()
367 }
368
369 pub fn call(&self) -> Option<Value> {
370 self.call.as_deref().and_then(|call| serde_json::from_str(call).ok())
371 }
372
373 /// For a job that calls a reusable workflow: what the keys of the jobs
374 /// its call makes start with (`call_prefix`).
375 pub fn call_prefix(&self) -> Option<String> {
376 let call = self.call().filter(|call| call["role"] == "caller")?;
377 Some(call["prefix"].as_str().unwrap_or(&self.key).to_owned())
378 }
379
380 /// A job that calls a reusable workflow and has not called it yet: it
381 /// waits for room under its matrix's `max-parallel`, or in its
382 /// concurrency group.
383 pub fn holds_call(&self) -> bool {
384 self.status == "waiting" && self.call_prefix().is_some()
385 }
386
387 /// For a job of a called workflow: that workflow, the job's own id in
388 /// it, and the job.
389 pub fn callee(&self) -> Option<(Workflow, workflow::Job, Value)> {
390 let call = self.call().filter(|call| call["role"] == "callee")?;
391 let called = workflow::parse(call["source"].as_str()?).ok()?;
392 let job = called.jobs.iter().find(|job| call["job"].as_str() == Some(job.id.as_str()))?.clone();
393 Some((called, job, call))
394 }
395}
396
397/// A job to decide on: its key, its definition, and what it needs, as
398/// (name in `needs`, key of the jobs).
399type Unit = (String, workflow::Job, Vec<(String, String)>);
400
401/// How many levels of reusable workflows may sit below the workflow a run
402/// started from, as on GitHub (ten levels of workflows in all).
403const MAX_CALL_DEPTH: u64 = 9;
404/// How many different reusable workflows a run may call, as on GitHub.
405const MAX_CALLED_WORKFLOWS: usize = 50;
406
407/// What the jobs of one key came to, for `needs.<key>`.
408fn key_result(rows: &[&JobRow]) -> &'static str {
409 let failed = |row: &&&JobRow| row.conclusion.as_deref() == Some("failure") && row.continue_on_error == 0;
410 if rows.iter().any(|row| failed(&row)) {
411 "failure"
412 } else if rows.iter().any(|row| row.conclusion.as_deref() == Some("cancelled")) {
413 "cancelled"
414 } else if rows.iter().all(|row| row.conclusion.as_deref() == Some("skipped")) {
415 "skipped"
416 } else {
417 "success"
418 }
419}
420
421/// Whether any job before `key` failed: one it needs, or one those need,
422/// however far back. A job after a skipped one still sees the failure
423/// that skipped it, as GitHub's failure() does. `needs_of`: each key's
424/// needs, as keys; `failed`: whether a key's jobs came to a failure.
425fn ancestor_failed(needs_of: &std::collections::HashMap<&str, Vec<&str>>, key: &str, failed: impl Fn(&str) -> bool) -> bool {
426 let mut seen = std::collections::HashSet::new();
427 let mut stack: Vec<&str> = needs_of.get(key).cloned().unwrap_or_default();
428 while let Some(next) = stack.pop() {
429 if !seen.insert(next) {
430 continue;
431 }
432 if failed(next) {
433 return true;
434 }
435 stack.extend(needs_of.get(next).into_iter().flatten().copied());
436 }
437 false
438}
439
440/// A job's `environment:`, as deployments read it: its name, the address in
441/// `environment.url` once its expressions are filled in from the run, and
442/// whether the job deploys to it. A job with `deployment: false` only reads
443/// the environment's secrets and variables, and makes no deployment.
444#[derive(Clone, Debug, Default, PartialEq)]
445pub(crate) struct JobEnvironment {
446 pub(crate) name: String,
447 pub(crate) url: Option<String>,
448 pub(crate) deploys: bool,
449}
450
451/// The environment `environment:` names, as written in `raw` (a job), with
452/// `contexts` to fill in expressions: null when it names none, or only
453/// through an expression this cannot read before the job runs.
454pub(crate) fn environment_of(raw: &Value, contexts: &Map<String, Value>) -> Option<JobEnvironment> {
455 let scope = Scope { contexts, status: Status::Success, hash_files: None };
456 let plain = |value: &Value| -> Option<String> {
457 let text = match value {
458 Value::String(text) if text.contains("${{") => expr::interpolate_value(value, &scope).ok().map(|v| expr::to_text(&v))?,
459 Value::String(text) => text.clone(),
460 _ => return None,
461 };
462 let text = text.trim().to_owned();
463 (!text.is_empty()).then_some(text)
464 };
465 match raw.get("environment")? {
466 name @ Value::String(_) => Some(JobEnvironment { name: plain(name)?, url: None, deploys: workflow::records_deployment(raw) }),
467 Value::Object(env) => {
468 let name = plain(env.get("name")?)?;
469 let url = env
470 .get("url")
471 .and_then(plain)
472 .filter(|url| url.starts_with("https://") || url.starts_with("http://"));
473 Some(JobEnvironment { name, url, deploys: workflow::records_deployment(raw) })
474 }
475 _ => None,
476 }
477}
478
479/// The contexts a job's `runs-on` and `environment` are read with before it
480/// runs: the run's `github`, its inputs, and the job's matrix.
481fn start_contexts(run: &RunRow, job: &JobRow, key: &str) -> Map<String, Value> {
482 let mut contexts = Map::new();
483 contexts.insert("github".into(), run.info().context(key, "", run.action.as_deref()));
484 contexts.insert("inputs".into(), Value::Object(run.inputs()));
485 contexts.insert("matrix".into(), job.matrix.as_deref().and_then(|m| serde_json::from_str(m).ok()).unwrap_or_else(|| json!({})));
486 contexts
487}
488
489/// The job as its workflow (or the workflow it calls) defines it.
490fn job_spec(run: &RunRow, job: &JobRow) -> Option<workflow::Job> {
491 match job.callee() {
492 Some((_, spec, _)) => Some(spec),
493 None => workflow::parse(&run.source).ok().and_then(|w| w.jobs.into_iter().find(|j| j.id == job.key)),
494 }
495}
496
497/// The environment a job deploys to, if it deploys: by the name read when
498/// its needs were done (which may have needed their outputs), else as
499/// its `environment:` reads now.
500pub(crate) fn deploys_to(run: &RunRow, job: &JobRow) -> Option<JobEnvironment> {
501 let spec = job_spec(run, job)?;
502 let read = environment_of(&spec.raw, &start_contexts(run, job, &spec.id));
503 let env = match (read, &job.environment) {
504 (Some(env), Some(name)) => Some(JobEnvironment { name: name.clone(), ..env }),
505 (Some(env), None) => Some(env),
506 (None, Some(name)) => Some(JobEnvironment { name: name.clone(), url: None, deploys: workflow::records_deployment(&spec.raw) }),
507 (None, None) => None,
508 };
509 env.filter(|env| env.deploys)
510}
511
512/// Whether a run's repository was public when the run was made, from its
513/// event's `repository.private`: private when the event doesn't say.
514fn run_is_public(run: &RunRow) -> bool {
515 run.info().event.get("repository").and_then(|repository| repository.get("private")).and_then(Value::as_bool) == Some(false)
516}
517
518/// The machine a job's `runs-on` asks for (`instance_for`), for the
519/// runner: none for the standard one. `ubuntu-latest` follows GitHub: the
520/// 4-core machine in a public repository. Billing charges the job as the
521/// machine named here, so what it ran on is what it pays for.
522fn start_instance(run: &RunRow, job: &JobRow) -> Option<String> {
523 let spec = match job.callee() {
524 Some((_, spec, _)) => spec,
525 None => workflow::parse(&run.source).ok().and_then(|w| w.jobs.into_iter().find(|j| j.id == job.key))?,
526 };
527 // `runs-on` as the job was queued with: its matrix and the run's
528 // inputs. A label that needs more than those is the standard machine.
529 let contexts = start_contexts(run, job, &spec.id);
530 let scope = Scope { contexts: &contexts, status: Status::Success, hash_files: None };
531 let labels: Vec<String> = match expr::interpolate_value(&spec.runs_on, &scope).unwrap_or(Value::Null) {
532 Value::String(label) => vec![label],
533 Value::Array(labels) => labels.iter().map(expr::to_text).collect(),
534 Value::Object(given) => match given.get("labels") {
535 Some(Value::Array(labels)) => labels.iter().map(expr::to_text).collect(),
536 Some(label) => vec![expr::to_text(label)],
537 None => Vec::new(),
538 },
539 _ => Vec::new(),
540 };
541 let instance = g1t_contracts::actions::instance_for(&labels, run_is_public(run));
542 (instance != g1t_contracts::actions::STANDARD_INSTANCE).then(|| instance.label.to_owned())
543}
544
545fn now() -> String {
546 rfc3339(now_ms())
547}
548
549/// How a finished run went for one environment, from the conclusions of
550/// the jobs that deploy to it: failed if any failed, an error if any was
551/// cancelled, else a success; nothing when none ran (all skipped).
552pub(crate) fn deployment_outcome(conclusions: &[Option<String>]) -> Option<&'static str> {
553 let ran: Vec<&str> = conclusions.iter().flatten().map(String::as_str).filter(|c| *c != "skipped").collect();
554 if ran.is_empty() {
555 return None;
556 }
557 if ran.iter().any(|c| *c == "failure" || *c == "timed_out") {
558 return Some("failure");
559 }
560 if ran.contains(&"cancelled") {
561 return Some("error");
562 }
563 Some("success")
564}
565
566impl Actions {
567 pub async fn run_row(&self, id: &str) -> Result<Option<RunRow>> {
568 self.db.prepare("SELECT * FROM runs WHERE id = ?").bind(&[id.into()])?.first::<RunRow>(None).await
569 }
570
571 pub async fn job_rows(&self, run_id: &str) -> Result<Vec<JobRow>> {
572 self.db
573 .prepare("SELECT * FROM jobs WHERE run_id = ? ORDER BY rowid")
574 .bind(&[run_id.into()])?
575 .all()
576 .await?
577 .results::<JobRow>()
578 }
579
580 pub async fn run_summary(&self, id: &str) -> Result<Outcome<WorkflowRun>> {
581 Ok(match self.run_row(id).await? {
582 Some(row) => Outcome::Ok(row.summary()),
583 None => fail(FailureCode::NotFound, "No such run."),
584 })
585 }
586
587 /// The contexts every expression outside a job's steps may use.
588 fn base_contexts(run: &RunRow, vars: &Map<String, Value>, job: &str) -> Map<String, Value> {
589 let mut contexts = Map::new();
590 contexts.insert("github".into(), run.info().context(job, "", run.action.as_deref()));
591 contexts.insert("inputs".into(), Value::Object(run.inputs()));
592 contexts.insert("vars".into(), Value::Object(vars.clone()));
593 contexts.insert("needs".into(), json!({}));
594 contexts.insert("runner".into(), runner_context());
595 contexts
596 }
597
598 /// Whether `namespace` is a person's own workspace: usernames and
599 /// workspaces share one namespace, so it is when someone has that
600 /// username. Kept in the isolate for a few minutes, so a burst of
601 /// runs asks identity once.
602 async fn personal_namespace(&self, namespace: &str) -> Result<bool> {
603 const KEEP_MS: u64 = 5 * 60 * 1000;
604 thread_local! {
605 static PERSONAL: std::cell::RefCell<std::collections::HashMap<String, (bool, u64)>> = Default::default();
606 }
607 let now = now_ms();
608 let key = namespace.to_ascii_lowercase();
609 if let Some(personal) = PERSONAL.with(|kept| kept.borrow().get(&key).filter(|(_, at)| now.saturating_sub(*at) < KEEP_MS).map(|(personal, _)| *personal)) {
610 return Ok(personal);
611 }
612 let found: g1t_contracts::Viewer = g1t_kit::call(
613 &self.identity,
614 "user_by_username",
615 &g1t_contracts::identity::UsernameArgs { username: key.clone() },
616 )
617 .await?;
618 let personal = found.is_some_and(|user| user.username.eq_ignore_ascii_case(namespace));
619 PERSONAL.with(|kept| {
620 let mut kept = kept.borrow_mut();
621 if kept.len() > 1000 {
622 kept.clear();
623 }
624 kept.insert(key, (personal, now));
625 });
626 Ok(personal)
627 }
628
629 /// Makes a run and its jobs, and starts what can start. `None` when the
630 /// event already started this workflow.
631 pub async fn create_run(&self, new: NewRun) -> Result<Option<String>> {
632 self.create_run_with(new, false).await
633 }
634
635 /// As `create_run`, but the run's pending status must reach Work: one
636 /// that cannot is cancelled and the error returned, so that a caller
637 /// waiting on statuses (the merge queue) never reads "no workflows" or
638 /// a premature pass from a run nothing was told about.
639 pub async fn create_run_registered(&self, new: NewRun) -> Result<Option<String>> {
640 self.create_run_with(new, true).await
641 }
642
643 async fn create_run_with(&self, new: NewRun, strict: bool) -> Result<Option<String>> {
644 // Nothing starts on an archived repository. A deleted one is never
645 // found to start anything on.
646 if new.repo.archived() {
647 return Ok(None);
648 }
649 // Nor while its Actions are off (Settings, Actions; a fork's are
650 // until someone turns them on), whatever started it. This is the
651 // gate; read once per request, so the runs of one push share it.
652 if !self.actions_on(&new.repo).await? {
653 return Ok(None);
654 }
655 let workflow_row = self.workflow_row(&new.repo, &new.path, &new.workflow.display_name(&new.path), &new.source).await?;
656 let numbered = self
657 .db
658 .prepare("UPDATE workflows SET run_count = run_count + 1 WHERE id = ? RETURNING run_count AS n")
659 .bind(&[workflow_row.id.as_str().into()])?
660 .first::<Count>(None)
661 .await?
662 .map_or(1, |count| count.n);
663 let id = new_id("run", now_ms());
664 let mut info = new.info.clone();
665 // A personal workspace's repositories are a `User`'s, as on GitHub.
666 if self.personal_namespace(&new.repo.namespace).await? {
667 crate::payload::owned_by_person(&mut info.event, &new.repo.namespace);
668 }
669 info.workflow = new.workflow.display_name(&new.path);
670 info.workflow_path = new.path.clone();
671 info.run_id = id.clone();
672 info.run_number = u64::from(numbered);
673 let vars = self
674 .variables_for(&new.repo.id, &format!("{}/{}", new.repo.namespace, new.repo.name), None, new.trusted)
675 .await?;
676
677 // run-name and the concurrency group read github, inputs and vars.
678 let mut contexts = Map::new();
679 contexts.insert("github".into(), info.context("", "", new.action.as_deref()));
680 contexts.insert("inputs".into(), Value::Object(new.inputs.clone()));
681 contexts.insert("vars".into(), Value::Object(vars));
682 let scope = Scope {
683 contexts: &contexts,
684 status: Status::Success,
685 hash_files: None,
686 };
687 let title = new
688 .workflow
689 .run_name
690 .as_deref()
691 .and_then(|run_name| expr::interpolate(run_name, &scope).ok())
692 .filter(|title| !title.trim().is_empty())
693 .unwrap_or(new.title.clone());
694 let group = new.workflow.concurrency.as_ref().and_then(|c| expr::interpolate(&c.group, &scope).ok());
695 let cancel_in_progress = new
696 .workflow
697 .concurrency
698 .as_ref()
699 .and_then(|c| expr::interpolate_value(&c.cancel_in_progress, &scope).ok())
700 .is_some_and(|value| expr::truthy(&value));
701
702 let approval = new.approval.as_ref().map(|reason| RunApproval { state: "required".into(), reason: reason.clone(), approved_by: None });
703 let inserted = self
704 .db
705 .prepare(
706 "INSERT OR IGNORE INTO runs (id, workflow_id, repo_id, repo, path, name, title, number, event, action, git_ref, sha,
707 pull, status, actor, actor_id, source, info, inputs, trusted, concurrency_group, event_key, created_at,
708 approval, cancel_in_progress)
709 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
710 )
711 .bind(&[
712 id.as_str().into(),
713 workflow_row.id.as_str().into(),
714 new.repo.id.as_str().into(),
715 format!("{}/{}", new.repo.namespace, new.repo.name).into(),
716 new.path.as_str().into(),
717 info.workflow.as_str().into(),
718 title.as_str().into(),
719 numbered.into(),
720 info.event_name.as_str().into(),
721 optional(new.action.as_deref()),
722 info.git_ref.as_str().into(),
723 new.head_sha.as_deref().unwrap_or(&info.sha).into(),
724 new.pull.map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
725 if approval.is_some() { "action_required" } else { "queued" }.into(),
726 optional(new.actor.as_deref()),
727 optional(new.actor_id.as_deref()),
728 new.source.as_str().into(),
729 serde_json::to_string(&info)?.into(),
730 serde_json::to_string(&new.inputs)?.into(),
731 u32::from(new.trusted).into(),
732 optional(group.as_deref()),
733 new.event_key.as_str().into(),
734 now().into(),
735 approval.as_ref().map(serde_json::to_string).transpose()?.as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
736 u32::from(cancel_in_progress).into(),
737 ])?
738 .first::<Value>(None)
739 .await?;
740 if inserted.is_none() {
741 return Ok(None);
742 }
743 let mut unregistered = None;
744 if let Some(run) = self.run_row(&id).await? {
745 if strict {
746 if let Err(error) = self.try_report_pending(&run).await {
747 unregistered = Some((run, error));
748 }
749 } else {
750 self.report_pending(&run).await?;
751 }
752 }
753
754 // Every job, waiting; each is expanded when the jobs it needs are done.
755 let mut statements = Vec::new();
756 for job in &new.workflow.jobs {
757 statements.push(
758 self.db
759 .prepare(
760 "INSERT INTO jobs (id, run_id, repo_id, namespace, key, name, needs, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting')",
761 )
762 .bind(&[
763 new_id("job", now_ms()).into(),
764 id.as_str().into(),
765 new.repo.id.as_str().into(),
766 new.repo.namespace.as_str().into(),
767 job.id.as_str().into(),
768 job.name.clone().filter(|n| !expr::has_expression(n)).unwrap_or(job.id.clone()).into(),
769 serde_json::to_string(&job.needs)?.into(),
770 ])?,
771 );
772 }
773 self.db.batch(statements).await?;
774 if let Some((run, error)) = unregistered {
775 self.cancel_run(&run, "Its pending status could not be registered.", false).await?;
776 return Err(error);
777 }
778
779 // A pull request's run from outside waits to be approved; it joins
780 // its concurrency group once it is (protection.rs, approve_run).
781 if approval.is_some() {
782 return Ok(Some(id));
783 }
784 if let Some(run) = self.run_row(&id).await? {
785 self.enter_group(&run).await?;
786 }
787 Ok(Some(id))
788 }
789
790 /// A run about to start: one run at a time per concurrency group, as on
791 /// GitHub. A newer run replaces one that waits in the group, and with
792 /// `cancel-in-progress` the one that runs; otherwise it waits as
793 /// `pending` for the one that runs. Then it moves along.
794 pub(crate) async fn enter_group(&self, run: &RunRow) -> Result<()> {
795 if let Some(group) = &run.concurrency_group {
796 let cancel_in_progress = run.cancel_in_progress != 0;
797 let others = self
798 .db
799 .prepare(
800 "SELECT * FROM runs WHERE repo_id = ? AND concurrency_group = ? AND id != ? AND status NOT IN ('completed', 'action_required') ORDER BY id",
801 )
802 .bind(&[run.repo_id.as_str().into(), group.as_str().into(), run.id.as_str().into()])?
803 .all()
804 .await?
805 .results::<RunRow>()?;
806 for other in &others {
807 if cancel_in_progress || other.status == "pending" {
808 // A newer run replaces a waiting one, as on GitHub.
809 self.cancel_run(other, "A newer run in the same concurrency group replaced it.", false).await?;
810 }
811 }
812 if !cancel_in_progress && others.iter().any(|other| other.status != "pending") {
813 self.db
814 .prepare("UPDATE runs SET status = 'pending' WHERE id = ?")
815 .bind(&[run.id.as_str().into()])?
816 .run()
817 .await?;
818 return Ok(());
819 }
820 }
821 self.advance(&run.id).await
822 }
823
824 /// A run that could not start, such as for a workflow file that does
825 /// not read. None while `repo`'s Actions are off, as for `create_run`.
826 #[allow(clippy::too_many_arguments)]
827 pub async fn record_failed_run(
828 &self,
829 repo: &Repo,
830 row: &WorkflowRow,
831 git_ref: &str,
832 sha: &str,
833 event_key: &str,
834 actor_id: Option<&str>,
835 actor: &str,
836 problem: &str,
837 ) -> Result<()> {
838 if !self.actions_on(repo).await? {
839 return Ok(());
840 }
841 let numbered = self
842 .db
843 .prepare("UPDATE workflows SET run_count = run_count + 1 WHERE id = ? RETURNING run_count AS n")
844 .bind(&[row.id.as_str().into()])?
845 .first::<Count>(None)
846 .await?
847 .map_or(1, |count| count.n);
848 let at = now();
849 self.db
850 .prepare(
851 "INSERT OR IGNORE INTO runs (id, workflow_id, repo_id, repo, path, name, title, number, event, git_ref, sha, status,
852 conclusion, error, actor, actor_id, source, info, event_key, created_at, finished_at)
853 VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'push', ?, ?, 'completed', 'failure', ?, ?, ?, ?, '{}', ?, ?, ?)",
854 )
855 .bind(&[
856 new_id("run", now_ms()).into(),
857 row.id.as_str().into(),
858 row.repo_id.as_str().into(),
859 row.repo.as_str().into(),
860 row.path.as_str().into(),
861 row.path.as_str().into(),
862 "Invalid workflow file".into(),
863 numbered.into(),
864 git_ref.into(),
865 sha.into(),
866 problem.into(),
867 actor.into(),
868 optional(actor_id),
869 row.source.as_str().into(),
870 event_key.into(),
871 at.as_str().into(),
872 at.as_str().into(),
873 ])?
874 .run()
875 .await?;
876 Ok(())
877 }
878
879 /// Moves a run along: jobs whose needs are done are decided on, and
880 /// jobs that can start are started.
881 pub async fn advance(&self, run_id: &str) -> Result<()> {
882 // Each pass may finish jobs (skipped ones), which may free others.
883 for _ in 0..20 {
884 let Some(run) = self.run_row(run_id).await? else { return Ok(()) };
885 if matches!(run.status.as_str(), "completed" | "pending" | "action_required") {
886 return Ok(());
887 }
888 let workflow = match workflow::parse(&run.source) {
889 Ok(workflow) => workflow,
890 Err(problem) => {
891 self.finish_run(&run, Some(&problem)).await?;
892 return Ok(());
893 }
894 };
895 let jobs = self.job_rows(run_id).await?;
896 let mut changed = false;
897 // What to decide on: the workflow's jobs, and the jobs of the
898 // workflows they call, each with its needs as (name, key).
899 let mut units: Vec<Unit> = workflow
900 .jobs
901 .iter()
902 .map(|job| (job.id.clone(), job.clone(), job.needs.iter().map(|n| (n.clone(), n.clone())).collect()))
903 .collect();
904 let mut seen = std::collections::HashSet::new();
905 for row in &jobs {
906 if !seen.insert(row.key.clone()) {
907 continue;
908 }
909 if let Some((_, job, call)) = row.callee() {
910 let parent = call["parent"].as_str().unwrap_or_default().to_owned();
911 let needs = job.needs.iter().map(|n| (n.clone(), format!("{parent}/{n}"))).collect();
912 units.push((row.key.clone(), job, needs));
913 }
914 }
915 // Each key's needs, as keys, to look back through for failure().
916 let needs_of: std::collections::HashMap<&str, Vec<&str>> =
917 units.iter().map(|(key, _, needs)| (key.as_str(), needs.iter().map(|(_, need)| need.as_str()).collect())).collect();
918 let key_failed = |key: &str| key_result(&jobs.iter().filter(|row| row.key == key).collect::<Vec<_>>()) == "failure";
919 for (key, job, needs) in &units {
920 let rows: Vec<&JobRow> = jobs.iter().filter(|row| &row.key == key).collect();
921 if rows.is_empty() || !rows.iter().all(|row| row.status == "waiting" && !row.holds_call()) {
922 continue;
923 }
924 let needed: Vec<(&String, Vec<&JobRow>)> =
925 needs.iter().map(|(name, need)| (name, jobs.iter().filter(|row| &row.key == need).collect())).collect();
926 if !needed.iter().all(|(_, rows)| rows.iter().all(|row| row.status == "completed")) {
927 continue;
928 }
929 let failed_before = ancestor_failed(&needs_of, key, key_failed);
930 self.decide(&run, job, rows[0], &needed, failed_before).await?;
931 changed = true;
932 }
933 // A job that called a workflow finishes with that workflow's jobs.
934 for row in jobs.iter().filter(|row| row.status == "calling") {
935 let prefix = row.call_prefix().unwrap_or(row.key.clone());
936 let children: Vec<&JobRow> = jobs
937 .iter()
938 .filter(|child| child.call().is_some_and(|call| call["role"] == "callee" && call["parent"].as_str() == Some(prefix.as_str())))
939 .collect();
940 if !children.is_empty() && children.iter().all(|child| child.status == "completed") {
941 self.finish_call(&run, row, &children).await?;
942 changed = true;
943 }
944 }
945 // Calls that wait start while their matrix's `max-parallel` and
946 // their concurrency group have room.
947 let mut calling: std::collections::HashMap<&str, u32> = std::collections::HashMap::new();
948 for row in jobs.iter().filter(|row| row.status == "calling") {
949 *calling.entry(row.key.as_str()).or_default() += 1;
950 }
951 for row in jobs.iter().filter(|row| row.holds_call()) {
952 let running = calling.get(row.key.as_str()).copied().unwrap_or(0);
953 if row.max_parallel.is_some_and(|max| running >= max) || self.group_busy(row).await? {
954 continue;
955 }
956 if self.start_call(row).await? {
957 calling.insert(row.key.as_str(), running + 1);
958 changed = true;
959 }
960 }
961 if !changed {
962 break;
963 }
964 }
965 self.start_queued().await?;
966 self.finish_if_done(run_id).await
967 }
968
969 /// Decides on one job whose needs are done: skip it, fail it, or expand
970 /// it into its matrix and queue it. `failed_before`: whether any job
971 /// before it failed, however far back (`ancestor_failed`).
972 async fn decide(&self, run: &RunRow, job: &workflow::Job, row: &JobRow, needed: &[(&String, Vec<&JobRow>)], failed_before: bool) -> Result<()> {
973 let vars = self.variables_for(&run.repo_id, &run.repo, None, run.trusted != 0).await?;
974 let mut contexts = Self::base_contexts(run, &vars, &job.id);
975 // A called workflow's jobs read the inputs they were called with.
976 let call = row.call();
977 // Shown under the job whose call made it, by that job's name.
978 let caller = call.as_ref().filter(|c| c["role"] == "callee").and_then(|c| {
979 c["title"].as_str().map(str::to_owned).or_else(|| c["parent"].as_str().map(|parent| parent.replace('/', " / ")))
980 });
981 if let Some(call) = call.as_ref().filter(|c| c["role"] == "callee") {
982 contexts.insert("inputs".into(), call["inputs"].clone());
983 }
984 let mut needs = Map::new();
985 let mut results = Vec::new();
986 for (key, rows) in needed {
987 let result = key_result(rows);
988 let mut outputs = Map::new();
989 for row in rows {
990 if let Ok(Value::Object(more)) = serde_json::from_str::<Value>(&row.outputs) {
991 outputs.extend(more);
992 }
993 }
994 results.push(result);
995 needs.insert((*key).clone(), json!({ "result": result, "outputs": outputs }));
996 }
997 // As on GitHub: a need that was skipped makes success() false but
998 // not failure(); failure() is a failure anywhere before the job.
999 let status = expr::job_status(results, failed_before, run.conclusion.as_deref() == Some("cancelled"));
1000 contexts.insert("needs".into(), Value::Object(needs));
1001 let scope = Scope {
1002 contexts: &contexts,
1003 status,
1004 hash_files: None,
1005 };
1006 let condition = job.condition.as_deref().unwrap_or_default();
1007 match expr::condition(condition, &scope) {
1008 Ok(true) => {}
1009 Ok(false) => return self.skip_job(row, None).await,
1010 Err(problem) => return self.fail_job(row, &format!("Its `if` does not read: {problem}")).await,
1011 }
1012 // Its matrix, which may come from a needed job's outputs.
1013 let combinations = match &job.matrix {
1014 None => vec![Map::new()],
1015 Some(matrix) => {
1016 let value = match expr::interpolate_value(matrix, &scope) {
1017 Ok(value) => value,
1018 Err(problem) => return self.fail_job(row, &format!("Its matrix does not read: {problem}")).await,
1019 };
1020 match matrix::expand(&value) {
1021 Ok(combinations) if !combinations.is_empty() => combinations,
1022 Ok(_) => return self.fail_job(row, "Its matrix makes no jobs.").await,
1023 Err(problem) => return self.fail_job(row, &problem).await,
1024 }
1025 }
1026 };
1027 // A job that calls a reusable workflow calls it once for each.
1028 if let Some(uses) = &job.uses {
1029 return self.call_workflow(run, job, row, uses, &contexts, &combinations, caller.as_deref()).await;
1030 }
1031 let total = combinations.len();
1032 let raw = job.raw.as_object().cloned().unwrap_or_default();
1033 // Whether pull requests from forks may use self-hosted runners here,
1034 // asked once, and only for a run that is not trusted.
1035 let mut forks_allowed: Option<bool> = None;
1036 // Each concurrency group its jobs join, and whether it cancels.
1037 let mut groups: Vec<(String, bool)> = Vec::new();
1038 let mut statements = Vec::new();
1039 for (index, combination) in combinations.iter().enumerate() {
1040 let mut contexts = contexts.clone();
1041 contexts.insert("matrix".into(), Value::Object(combination.clone()));
1042 contexts.insert(
1043 "strategy".into(),
1044 json!({ "fail-fast": job.fail_fast, "job-index": index, "job-total": total, "max-parallel": job.max_parallel.unwrap_or(total as u32) }),
1045 );
1046 let scope = Scope {
1047 contexts: &contexts,
1048 status: Status::Success,
1049 hash_files: None,
1050 };
1051 let name = shown_name(job, caller.as_deref(), combination, &scope);
1052 let runs_on = expr::interpolate_value(&job.runs_on, &scope).unwrap_or(Value::Null);
1053 let labels = match &runs_on {
1054 Value::String(label) => vec![label.clone()],
1055 Value::Array(labels) => labels.iter().map(expr::to_text).collect(),
1056 Value::Object(spec) => spec.get("labels").map(|l| match l {
1057 Value::Array(labels) => labels.iter().map(expr::to_text).collect(),
1058 other => vec![expr::to_text(other)],
1059 }).unwrap_or_default(),
1060 _ => Vec::new(),
1061 };
1062 // `runs-on: self-hosted` (or a group): the workspace's own
1063 // machines, which may run any OS. Otherwise g1t's Linux sandboxes.
1064 let group = match &runs_on {
1065 Value::Object(spec) => spec.get("group").map(expr::to_text),
1066 _ => None,
1067 };
1068 let wanted = Wanted::of(&labels, group.as_deref());
1069 let mut reason = if wanted.self_hosted {
1070 None
1071 } else {
1072 labels
1073 .iter()
1074 .find(|label| {
1075 let lower = label.to_ascii_lowercase();
1076 lower.contains("windows") || lower.contains("macos")
1077 })
1078 .map(|label| {
1079 let os = if label.to_ascii_lowercase().contains("windows") { "windows" } else { "macos" };
1080 format!("`runs-on: {label}`: g1t's own runners are Linux. A self-hosted runner can run it: `runs-on: [self-hosted, {os}]`.")
1081 })
1082 };
1083 // A pull request from a fork runs code anyone could write: never
1084 // on the workspace's machines unless it said they may.
1085 if wanted.self_hosted && run.trusted == 0 {
1086 let allowed = match forks_allowed {
1087 Some(allowed) => allowed,
1088 None => {
1089 let allowed = self.effective_runner_settings(&row.namespace, Some(&run.repo_id)).await?.fork_pull_requests;
1090 forks_allowed = Some(allowed);
1091 allowed
1092 }
1093 };
1094 if !allowed {
1095 reason = Some(
1096 "Pull requests from forks do not run on self-hosted runners here. An admin can allow it under Settings, Runners.".to_owned(),
1097 );
1098 }
1099 }
1100 let max_minutes = if wanted.self_hosted { SELF_HOSTED_MAX_TIMEOUT_MINUTES } else { MAX_TIMEOUT_MINUTES };
1101 let timeout = raw
1102 .get("timeout-minutes")
1103 .and_then(|value| expr::interpolate_value(value, &scope).ok())
1104 .and_then(|value| value.as_f64().or_else(|| expr::to_text(&value).parse().ok()))
1105 .map_or(g1t_actions::workflow::DEFAULT_TIMEOUT_MINUTES.min(max_minutes), |minutes| (minutes.ceil() as u32).clamp(1, max_minutes));
1106 let continue_on_error = raw
1107 .get("continue-on-error")
1108 .and_then(|value| expr::interpolate_value(value, &scope).ok())
1109 .is_some_and(|value| expr::truthy(&value));
1110 let (mut status, mut conclusion, mut finished) = match &reason {
1111 Some(_) => ("completed", Some("failure"), Some(now())),
1112 None => ("queued", None, None),
1113 };
1114 // A self-hosted job waits, saying for what, until a runner takes it.
1115 let (labels_json, queued_at) = if wanted.self_hosted && reason.is_none() {
1116 reason = Some(waiting_reason(&wanted));
1117 (Some(serde_json::to_string(&wanted.stored())?), Some(now()))
1118 } else {
1119 (None, None)
1120 };
1121 // The environment it names, an expression read now, and what
1122 // that environment's protection rules say: it starts, waits as
1123 // `pending` (protection.rs), or may not deploy there.
1124 let environment = environment_of(&job.raw, &contexts).map(|env| env.name);
1125 if status == "queued"
1126 && let Some(name) = &environment
1127 {
1128 match self.gate(run, name).await? {
1129 Gate::Open => {}
1130 Gate::Held(why) => {
1131 status = "pending";
1132 reason = Some(why);
1133 }
1134 Gate::Refused(why) => {
1135 (status, conclusion, finished) = ("completed", Some("failure"), Some(now()));
1136 reason = Some(why);
1137 }
1138 }
1139 }
1140 // Its own concurrency group.
1141 let job_group = job
1142 .concurrency
1143 .as_ref()
1144 .and_then(|c| expr::interpolate(&c.group, &scope).ok())
1145 .map(|group| group.trim().to_owned())
1146 .filter(|group| !group.is_empty());
1147 let job_cancel = job
1148 .concurrency
1149 .as_ref()
1150 .and_then(|c| expr::interpolate_value(&c.cancel_in_progress, &scope).ok())
1151 .is_some_and(|value| expr::truthy(&value));
1152 if status != "completed"
1153 && let Some(group) = &job_group
1154 && !groups.iter().any(|(known, _)| known == group)
1155 {
1156 groups.push((group.clone(), job_cancel));
1157 }
1158 let values: Vec<worker::wasm_bindgen::JsValue> = vec![
1159 name.into(),
1160 serde_json::to_string(combination)?.into(),
1161 status.into(),
1162 optional(conclusion),
1163 optional(reason.as_deref()),
1164 timeout.into(),
1165 u32::from(continue_on_error).into(),
1166 job.max_parallel.map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
1167 optional(finished.as_deref()),
1168 optional(labels_json.as_deref()),
1169 optional(queued_at.as_deref()),
1170 optional(environment.as_deref()),
1171 optional(job_group.as_deref()),
1172 u32::from(job_cancel).into(),
1173 ];
1174 if index == 0 {
1175 let mut bound = values;
1176 bound.push(row.id.as_str().into());
1177 statements.push(
1178 self.db
1179 .prepare(
1180 "UPDATE jobs SET name = ?, matrix = ?, status = ?, conclusion = ?, reason = ?, timeout_minutes = ?,
1181 continue_on_error = ?, max_parallel = ?, finished_at = ?, labels = ?, queued_at = ?, environment = ?,
1182 concurrency_group = ?, cancel_in_progress = ? WHERE id = ?",
1183 )
1184 .bind(&bound)?,
1185 );
1186 } else {
1187 let mut bound: Vec<worker::wasm_bindgen::JsValue> = vec![
1188 new_id("job", now_ms()).into(),
1189 row.run_id.as_str().into(),
1190 row.repo_id.as_str().into(),
1191 row.namespace.as_str().into(),
1192 row.key.as_str().into(),
1193 (index as u32).into(),
1194 row.needs.as_str().into(),
1195 optional(row.call.as_deref()),
1196 ];
1197 bound.extend(values);
1198 statements.push(
1199 self.db
1200 .prepare(
1201 "INSERT INTO jobs (id, run_id, repo_id, namespace, key, ordinal, needs, call, name, matrix, status, conclusion, reason,
1202 timeout_minutes, continue_on_error, max_parallel, finished_at, labels, queued_at, environment,
1203 concurrency_group, cancel_in_progress)
1204 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1205 )
1206 .bind(&bound)?,
1207 );
1208 }
1209 }
1210 self.db.batch(statements).await?;
1211 self.replace_in_groups(run, &row.key, &groups).await
1212 }
1213
1214 /// A job queued in its own concurrency group: with `cancel-in-progress`
1215 /// it cancels the group's other jobs; otherwise it replaces any that
1216 /// are queued and not started, and waits for the one running
1217 /// (`start_queued` starts one of a group at a time). As on GitHub.
1218 async fn replace_in_groups(&self, run: &RunRow, key: &str, groups: &[(String, bool)]) -> Result<()> {
1219 if groups.is_empty() {
1220 return Ok(());
1221 }
1222 #[derive(Deserialize)]
1223 struct Id {
1224 id: String,
1225 }
1226 let mine: Vec<String> = self
1227 .db
1228 .prepare("SELECT id FROM jobs WHERE run_id = ? AND key = ?")
1229 .bind(&[run.id.as_str().into(), key.into()])?
1230 .all()
1231 .await?
1232 .results::<Id>()?
1233 .into_iter()
1234 .map(|row| row.id)
1235 .collect();
1236 let mut moved: Vec<String> = Vec::new();
1237 for (group, cancel) in groups {
1238 let others = self
1239 .db
1240 // A call that waits in the group, or calls, is in it too.
1241 .prepare("SELECT * FROM jobs WHERE repo_id = ? AND concurrency_group = ? AND status IN ('waiting', 'queued', 'pending', 'in_progress', 'calling')")
1242 .bind(&[run.repo_id.as_str().into(), group.as_str().into()])?
1243 .all()
1244 .await?
1245 .results::<JobRow>()?;
1246 for other in others.iter().filter(|other| !mine.contains(&other.id)) {
1247 if *cancel || matches!(other.status.as_str(), "queued" | "waiting") {
1248 self.stop_job(other, "A newer job in the same concurrency group replaced it.").await?;
1249 if !moved.contains(&other.run_id) {
1250 moved.push(other.run_id.clone());
1251 }
1252 }
1253 }
1254 }
1255 for other_run in moved.iter().filter(|id| **id != run.id) {
1256 Box::pin(self.advance(other_run)).await?;
1257 }
1258 Ok(())
1259 }
1260
1261 /// A job that calls a reusable workflow, in the repository or another
1262 /// (reach.rs): once for each combination of its matrix, as on GitHub,
1263 /// each with the inputs and secrets it passes read with that
1264 /// combination's `matrix`. Each call waits (`holds_call`) until its
1265 /// matrix's `max-parallel` and its concurrency group have room, when
1266 /// `start_call` puts the workflow's jobs in the run under it.
1267 #[allow(clippy::too_many_arguments)]
1268 async fn call_workflow(
1269 &self,
1270 run: &RunRow,
1271 job: &workflow::Job,
1272 row: &JobRow,
1273 uses: &str,
1274 contexts: &Map<String, Value>,
1275 combinations: &[Map<String, Value>],
1276 caller: Option<&str>,
1277 ) -> Result<()> {
1278 let depth = row.call().and_then(|c| c["depth"].as_u64()).unwrap_or(0) + 1;
1279 if depth > MAX_CALL_DEPTH {
1280 return self.fail_job(row, &call_allowed(depth, &[], uses).unwrap_err()).await;
1281 }
1282 let (file, source, origin) = match self.called_workflow(run, row, uses).await? {
1283 Ok(found) => found,
1284 Err(why) => return self.fail_job(row, &why).await,
1285 };
1286 let jobs = self.job_rows(&run.id).await?;
1287 // Each call so far, by the workflow it called.
1288 let called_paths: Vec<String> = jobs
1289 .iter()
1290 .filter(|other| other.call_prefix().is_some())
1291 .filter_map(JobRow::call)
1292 .filter_map(|call| call["path"].as_str().map(str::to_owned))
1293 .collect();
1294 let called_already: Vec<&str> = called_paths.iter().map(String::as_str).collect();
1295 if let Err(why) = call_allowed(depth, &called_already, &file) {
1296 return self.fail_job(row, &why).await;
1297 }
1298 let called = match workflow::parse(&source) {
1299 Ok(called) => called,
1300 Err(problem) => return self.fail_job(row, &format!("`{file}` does not read: {problem}")).await,
1301 };
1302 let Some(trigger) = called.trigger("workflow_call") else {
1303 return self.fail_job(row, &format!("`{file}` cannot be called: it has no `on: workflow_call`.")).await;
1304 };
1305 // Secrets: none but the job's token unless `secrets:` passes them,
1306 // by name or with `inherit`; read when each job starts (job_spec).
1307 let outer = row.call().filter(|c| c["role"] == "callee").and_then(|c| c.get("secrets").cloned());
1308 let total = combinations.len();
1309 let mut groups: Vec<(String, bool)> = Vec::new();
1310 let mut statements = Vec::new();
1311 for (index, combination) in combinations.iter().enumerate() {
1312 let mut contexts = contexts.clone();
1313 contexts.insert("matrix".into(), Value::Object(combination.clone()));
1314 contexts.insert(
1315 "strategy".into(),
1316 json!({ "fail-fast": job.fail_fast, "job-index": index, "job-total": total, "max-parallel": job.max_parallel.unwrap_or(total as u32) }),
1317 );
1318 let scope = Scope { contexts: &contexts, status: Status::Success, hash_files: None };
1319 let name = shown_name(job, caller, combination, &scope);
1320 // Inputs: what `with:` passes, as the called workflow types them.
1321 let given = match job.raw.get("with") {
1322 Some(with) => match expr::interpolate_value(with, &scope) {
1323 Ok(Value::Object(given)) => Ok(given),
1324 Ok(_) => Ok(Map::new()),
1325 Err(problem) => Err(format!("Its `with` does not read: {problem}")),
1326 },
1327 None => Ok(Map::new()),
1328 };
1329 let inputs = given.and_then(|given| crate::reach::call_inputs(&file, &trigger.inputs, &given));
1330 let secrets = crate::reach::secrets_plan(&job.raw, &contexts, outer.clone());
1331 let problem = match &inputs {
1332 Err(why) => Some(why.clone()),
1333 Ok(_) => crate::reach::missing_secrets(&called.raw, &secrets)
1334 .first()
1335 .map(|name| format!("`{file}` needs the secret `{name}`: pass it under `secrets:`, or use `secrets: inherit`."))
1336 .or_else(|| {
1337 crate::reach::undeclared_secrets(&called.raw, &secrets)
1338 .first()
1339 .map(|name| format!("Invalid secret: `{name}` is not defined in `{file}`."))
1340 }),
1341 };
1342 // Its own concurrency group, which it holds while its workflow runs.
1343 let group = job
1344 .concurrency
1345 .as_ref()
1346 .and_then(|c| expr::interpolate(&c.group, &scope).ok())
1347 .map(|group| group.trim().to_owned())
1348 .filter(|group| !group.is_empty());
1349 let cancel = job
1350 .concurrency
1351 .as_ref()
1352 .and_then(|c| expr::interpolate_value(&c.cancel_in_progress, &scope).ok())
1353 .is_some_and(|value| expr::truthy(&value));
1354 if problem.is_none()
1355 && let Some(group) = &group
1356 && !groups.iter().any(|(known, _)| known == group)
1357 {
1358 groups.push((group.clone(), cancel));
1359 }
1360 let call = json!({
1361 "role": "caller", "path": file, "source": source, "origin": origin, "depth": depth,
1362 "prefix": call_prefix(&row.key, job.matrix.is_some().then_some(index)), "title": name,
1363 "inputs": inputs.unwrap_or_default(), "secrets": secrets, "fail_fast": job.fail_fast,
1364 });
1365 let (status, conclusion, finished) = match &problem {
1366 Some(_) => ("completed", Some("failure"), Some(now())),
1367 None => ("waiting", None, None),
1368 };
1369 let values: Vec<worker::wasm_bindgen::JsValue> = vec![
1370 name.as_str().into(),
1371 serde_json::to_string(combination)?.into(),
1372 status.into(),
1373 optional(conclusion),
1374 optional(problem.as_deref()),
1375 job.max_parallel.map(|max| max.max(1)).map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
1376 optional(finished.as_deref()),
1377 optional(group.as_deref()),
1378 u32::from(cancel).into(),
1379 serde_json::to_string(&call)?.into(),
1380 ];
1381 if index == 0 {
1382 let mut bound = values;
1383 bound.push(row.id.as_str().into());
1384 statements.push(
1385 self.db
1386 .prepare(
1387 "UPDATE jobs SET name = ?, matrix = ?, status = ?, conclusion = ?, reason = ?, max_parallel = ?, finished_at = ?,
1388 concurrency_group = ?, cancel_in_progress = ?, call = ? WHERE id = ?",
1389 )
1390 .bind(&bound)?,
1391 );
1392 } else {
1393 let mut bound: Vec<worker::wasm_bindgen::JsValue> = vec![
1394 new_id("job", now_ms()).into(),
1395 row.run_id.as_str().into(),
1396 row.repo_id.as_str().into(),
1397 row.namespace.as_str().into(),
1398 row.key.as_str().into(),
1399 (index as u32).into(),
1400 row.needs.as_str().into(),
1401 ];
1402 bound.extend(values);
1403 statements.push(
1404 self.db
1405 .prepare(
1406 "INSERT INTO jobs (id, run_id, repo_id, namespace, key, ordinal, needs, name, matrix, status, conclusion, reason,
1407 max_parallel, finished_at, concurrency_group, cancel_in_progress, call)
1408 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1409 )
1410 .bind(&bound)?,
1411 );
1412 }
1413 }
1414 self.db.batch(statements).await?;
1415 self.replace_in_groups(run, &row.key, &groups).await
1416 }
1417
1418 /// Whether another job of `row`'s concurrency group runs, or calls a
1419 /// workflow, so that `row` waits for it.
1420 async fn group_busy(&self, row: &JobRow) -> Result<bool> {
1421 let Some(group) = &row.concurrency_group else { return Ok(false) };
1422 let busy = self
1423 .db
1424 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE repo_id = ? AND concurrency_group = ? AND status IN ('in_progress', 'calling') AND id != ?")
1425 .bind(&[row.repo_id.as_str().into(), group.as_str().into(), row.id.as_str().into()])?
1426 .first::<Count>(None)
1427 .await?
1428 .map_or(0, |count| count.n);
1429 Ok(busy > 0)
1430 }
1431
1432 /// A call that waited (`holds_call`) is made: the called workflow's
1433 /// jobs join the run under it, named under its name and keyed under its
1434 /// prefix. False when it no longer waits.
1435 async fn start_call(&self, row: &JobRow) -> Result<bool> {
1436 let Some(call) = row.call() else { return Ok(false) };
1437 let Some(prefix) = row.call_prefix() else { return Ok(false) };
1438 let Some(called) = call["source"].as_str().and_then(|source| workflow::parse(source).ok()) else { return Ok(false) };
1439 let file = call["path"].as_str().unwrap_or_default();
1440 let started = self
1441 .db
1442 .prepare("UPDATE jobs SET status = 'calling', reason = ?, started_at = ? WHERE id = ? AND status = 'waiting' RETURNING id")
1443 .bind(&[format!("Calls `{file}`.").into(), now().into(), row.id.as_str().into()])?
1444 .first::<Value>(None)
1445 .await?;
1446 if started.is_none() {
1447 return Ok(false);
1448 }
1449 let mut statements = Vec::new();
1450 for called_job in &called.jobs {
1451 let needs: Vec<String> = called_job.needs.iter().map(|n| format!("{prefix}/{n}")).collect();
1452 let callee = json!({
1453 "role": "callee", "parent": prefix, "title": row.name, "job": called_job.id, "path": file,
1454 "source": call["source"], "inputs": call["inputs"], "depth": call["depth"], "origin": call["origin"], "secrets": call["secrets"],
1455 });
1456 statements.push(
1457 self.db
1458 .prepare("INSERT INTO jobs (id, run_id, repo_id, namespace, key, name, needs, status, call) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting', ?)")
1459 .bind(&[
1460 new_id("job", now_ms()).into(),
1461 row.run_id.as_str().into(),
1462 row.repo_id.as_str().into(),
1463 row.namespace.as_str().into(),
1464 format!("{prefix}/{}", called_job.id).into(),
1465 format!("{} / {}", row.name, called_job.name.clone().unwrap_or(called_job.id.clone())).into(),
1466 serde_json::to_string(&needs)?.into(),
1467 serde_json::to_string(&callee)?.into(),
1468 ])?,
1469 );
1470 }
1471 if !statements.is_empty() {
1472 self.db.batch(statements).await?;
1473 }
1474 Ok(true)
1475 }
1476
1477 /// The runs with a call waiting in `group`, but `run_id`, moved along
1478 /// now that a job of the group has finished.
1479 async fn wake_group(&self, repo_id: &str, group: &str, run_id: &str) -> Result<()> {
1480 #[derive(Deserialize)]
1481 struct RunId {
1482 run_id: String,
1483 }
1484 let waiting = self
1485 .db
1486 .prepare("SELECT DISTINCT run_id FROM jobs WHERE repo_id = ? AND concurrency_group = ? AND status = 'waiting' AND run_id != ?")
1487 .bind(&[repo_id.into(), group.into(), run_id.into()])?
1488 .all()
1489 .await?
1490 .results::<RunId>()?;
1491 for other in waiting {
1492 Box::pin(self.advance(&other.run_id)).await?;
1493 }
1494 Ok(())
1495 }
1496
1497 /// A job that called a workflow, finished with its jobs: their result,
1498 /// and the outputs the workflow declares. A failed call of a fail-fast
1499 /// matrix stops the matrix's other calls.
1500 async fn finish_call(&self, run: &RunRow, row: &JobRow, children: &[&JobRow]) -> Result<()> {
1501 let call = row.call().unwrap_or_default();
1502 let called = call["source"].as_str().and_then(|s| workflow::parse(s).ok());
1503 let mut jobs_context = Map::new();
1504 let mut by_key: std::collections::BTreeMap<String, Vec<&JobRow>> = std::collections::BTreeMap::new();
1505 for child in children {
1506 by_key.entry(child.key.clone()).or_default().push(child);
1507 }
1508 for (key, rows) in &by_key {
1509 let mut outputs = Map::new();
1510 for child in rows {
1511 if let Ok(Value::Object(more)) = serde_json::from_str::<Value>(&child.outputs) {
1512 outputs.extend(more);
1513 }
1514 }
1515 let id = key.rsplit('/').next().unwrap_or(key);
1516 jobs_context.insert(id.to_owned(), json!({ "result": key_result(rows), "outputs": outputs }));
1517 }
1518 let inputs = children.first().and_then(|c| c.call()).map(|c| c["inputs"].clone()).unwrap_or(json!({}));
1519 let mut contexts = Map::new();
1520 contexts.insert("jobs".into(), Value::Object(jobs_context));
1521 contexts.insert("inputs".into(), inputs);
1522 let scope = Scope { contexts: &contexts, status: Status::Success, hash_files: None };
1523 let mut outputs = Map::new();
1524 if let Some(Value::Object(declared)) = called.as_ref().map(|w| {
1525 let on = w.raw.get("on").or_else(|| w.raw.get("true")).cloned().unwrap_or(Value::Null);
1526 on.get("workflow_call").and_then(|c| c.get("outputs")).cloned().unwrap_or(Value::Null)
1527 }) {
1528 for (name, spec) in declared {
1529 if let Some(value) = spec.get("value") {
1530 let value = expr::interpolate_value(value, &scope).unwrap_or(Value::Null);
1531 outputs.insert(name, Value::String(expr::to_text(&value)));
1532 }
1533 }
1534 }
1535 let conclusion = key_result(children);
1536 let finished = self
1537 .db
1538 .prepare("UPDATE jobs SET status = 'completed', conclusion = ?, outputs = ?, finished_at = ? WHERE id = ? AND status = 'calling' RETURNING id")
1539 .bind(&[conclusion.into(), serde_json::to_string(&outputs)?.into(), now().into(), row.id.as_str().into()])?
1540 .first::<Value>(None)
1541 .await?;
1542 if finished.is_none() {
1543 return Ok(());
1544 }
1545 if conclusion == "failure" && row.matrix.as_deref().is_some_and(|m| m != "{}") && call["fail_fast"] != json!(false) {
1546 let siblings = self
1547 .db
1548 .prepare("SELECT * FROM jobs WHERE run_id = ? AND key = ? AND status != 'completed'")
1549 .bind(&[row.run_id.as_str().into(), row.key.as_str().into()])?
1550 .all()
1551 .await?
1552 .results::<JobRow>()?;
1553 for sibling in siblings {
1554 self.stop_job(&sibling, "Another job of its matrix failed, and the matrix is fail-fast.").await?;
1555 }
1556 }
1557 if let Some(group) = &row.concurrency_group {
1558 self.wake_group(&run.repo_id, group, &run.id).await?;
1559 }
1560 Ok(())
1561 }
1562
1563 /// A file's text at a commit, if it is there.
1564 pub(crate) async fn read_file(&self, path: &RepoPath, ws: &g1t_contracts::User, sha: &str, file: &str) -> Result<Option<String>> {
1565 let blob: Outcome<g1t_contracts::repos::BlobView> = g1t_kit::call(
1566 &self.repos,
1567 "blob",
1568 &g1t_contracts::repos::BlobArgs {
1569 path: path.clone(),
1570 viewer: Some(ws.clone()),
1571 git_ref: sha.to_owned(),
1572 file_path: file.to_owned(),
1573 },
1574 )
1575 .await?;
1576 Ok(match blob {
1577 Outcome::Ok(view) => view.text,
1578 Outcome::Fail(_) => None,
1579 })
1580 }
1581
1582 async fn skip_job(&self, row: &JobRow, reason: Option<&str>) -> Result<()> {
1583 self.db
1584 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'skipped', reason = ?, finished_at = ? WHERE id = ?")
1585 .bind(&[optional(reason), now().into(), row.id.as_str().into()])?
1586 .run()
1587 .await?;
1588 Ok(())
1589 }
1590
1591 async fn fail_job(&self, row: &JobRow, reason: &str) -> Result<()> {
1592 self.db
1593 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'failure', reason = ?, finished_at = ? WHERE id = ? AND status != 'completed'")
1594 .bind(&[reason.into(), now().into(), row.id.as_str().into()])?
1595 .run()
1596 .await?;
1597 Ok(())
1598 }
1599
1600 /// Starts queued jobs, oldest first, while their workspace has room.
1601 pub async fn start_queued(&self) -> Result<()> {
1602 let queued = self
1603 .db
1604 // Self-hosted jobs are taken by their runners (runners.rs).
1605 .prepare("SELECT * FROM jobs WHERE status = 'queued' AND labels IS NULL ORDER BY rowid LIMIT 50")
1606 .all()
1607 .await?
1608 .results::<JobRow>()?;
1609 let mut running: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
1610 // Every workspace's jobs on g1t's own machines: past its share, a
1611 // workspace starts more only while the pool has room (has_room).
1612 let mut in_pool = if queued.is_empty() {
1613 0
1614 } else {
1615 self.db
1616 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE status = 'in_progress' AND runner_id IS NULL")
1617 .first::<Count>(None)
1618 .await?
1619 .map_or(0, |count| count.n)
1620 };
1621 for job in queued {
1622 let in_workspace = match running.get(&job.namespace) {
1623 Some(n) => *n,
1624 None => {
1625 let n = self
1626 .db
1627 // Only g1t's own sandboxes count against the workspace's room.
1628 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE status = 'in_progress' AND namespace = ? AND runner_id IS NULL")
1629 .bind(&[job.namespace.as_str().into()])?
1630 .first::<Count>(None)
1631 .await?
1632 .map_or(0, |count| count.n);
1633 running.insert(job.namespace.clone(), n);
1634 n
1635 }
1636 };
1637 if !has_room(in_workspace, in_pool) {
1638 continue;
1639 }
1640 if let Some(max) = job.max_parallel {
1641 let siblings = self
1642 .db
1643 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE run_id = ? AND key = ? AND status = 'in_progress'")
1644 .bind(&[job.run_id.as_str().into(), job.key.as_str().into()])?
1645 .first::<Count>(None)
1646 .await?
1647 .map_or(0, |count| count.n);
1648 if siblings >= max {
1649 continue;
1650 }
1651 }
1652 // One job of a concurrency group runs at a time.
1653 if let Some(group) = &job.concurrency_group {
1654 let running = self
1655 .db
1656 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE repo_id = ? AND concurrency_group = ? AND status IN ('in_progress', 'calling') AND id != ?")
1657 .bind(&[job.repo_id.as_str().into(), group.as_str().into(), job.id.as_str().into()])?
1658 .first::<Count>(None)
1659 .await?
1660 .map_or(0, |count| count.n);
1661 if running > 0 {
1662 continue;
1663 }
1664 }
1665 let token = random_hex(24);
1666 let at = now();
1667 let claimed = self
1668 .db
1669 .prepare(
1670 "UPDATE jobs SET status = 'in_progress', token_hash = ?, first_token_hash = NULL, started_at = ?, seen_at = ?, waiting_since = NULL WHERE id = ? AND status = 'queued' RETURNING id",
1671 )
1672 .bind(&[sha256_hex(&token).into(), at.as_str().into(), at.as_str().into(), job.id.as_str().into()])?
1673 .first::<Value>(None)
1674 .await?;
1675 if claimed.is_none() {
1676 continue;
1677 }
1678 running.insert(job.namespace.clone(), in_workspace + 1);
1679 in_pool += 1;
1680 self.db
1681 .prepare("UPDATE runs SET status = 'in_progress', started_at = COALESCE(started_at, ?) WHERE id = ? AND status = 'queued'")
1682 .bind(&[at.as_str().into(), job.run_id.as_str().into()])?
1683 .run()
1684 .await?;
1685 let run = self.run_row(&job.run_id).await?;
1686 let repo: RepoPath = run.as_ref().map(|run| repo_path(&run.repo)).unwrap_or(RepoPath {
1687 namespace: job.namespace.clone(),
1688 name: String::new(),
1689 });
1690 // The machine it asked for, for the runner.
1691 let instance = run.as_ref().and_then(|run| start_instance(run, &job));
1692 let trusted = run.as_ref().is_some_and(|run| run.trusted != 0);
1693 // Only a trusted run's jobs get secrets, brokered ones included.
1694 let brokered = trusted && self.may_broker(&job.repo_id, &job.namespace).await?;
1695 let started: Outcome<Value> = g1t_kit::call(
1696 &self.runner,
1697 "start_actions_job",
1698 &StartJobArgs {
1699 job: job.id.clone(),
1700 token,
1701 repo,
1702 timeout_minutes: job.timeout_minutes,
1703 instance,
1704 brokered,
1705 },
1706 )
1707 .await
1708 .unwrap_or_else(|error| fail(FailureCode::Conflict, format!("The runner could not be reached: {error}")));
1709 if let Outcome::Fail(refused) = started {
1710 // No machine free (every sandbox of its class taken, or a
1711 // rollout replacing them): back in the queue, tried again at
1712 // the next sweep, until it has waited WAIT_FOR_MACHINE_MS.
1713 // The sandboxes after it would find none either, so this
1714 // sweep starts no more.
1715 if refused.code == FailureCode::Unavailable {
1716 let since = job.waiting_since.clone().unwrap_or_else(|| at.clone());
1717 if crate::waited_for_a_machine(Some(&since), now_ms()) {
1718 let minutes = crate::WAIT_FOR_MACHINE_MS / 60_000;
1719 let reason = format!("{} None came free in {minutes} minutes.", refused.message);
1720 Box::pin(self.finish_job(&job.id, "failure", Some(&reason), None)).await?;
1721 continue;
1722 }
1723 self.db
1724 .prepare(
1725 "UPDATE jobs SET status = 'queued', token_hash = NULL, started_at = NULL, seen_at = NULL, waiting_since = ?, reason = ?
1726 WHERE id = ? AND status = 'in_progress'",
1727 )
1728 .bind(&[since.as_str().into(), refused.message.as_str().into(), job.id.as_str().into()])?
1729 .run()
1730 .await?;
1731 worker::console_warn!("actions: job {} waits for a machine: {}", job.id, refused.message);
1732 break;
1733 }
1734 // Billing would not pay for a scheduled run's job: the
1735 // schedule waits rather than making runs only to refuse them.
1736 if refused.code == FailureCode::PaymentRequired
1737 && let Some(run) = run.as_ref().filter(|run| run.event == "schedule")
1738 {
1739 self.db
1740 .prepare("UPDATE workflows SET schedule_refused_until = ? WHERE id = ?")
1741 .bind(&[rfc3339(now_ms() + crate::SCHEDULE_REFUSED_MS).into(), run.workflow_id.as_str().into()])?
1742 .run()
1743 .await?;
1744 }
1745 Box::pin(self.finish_job(&job.id, "failure", Some(&refused.message), None)).await?;
1746 } else {
1747 self.job_started(&job.id).await?;
1748 }
1749 }
1750 Ok(())
1751 }
1752
1753 /// Finishes a job and moves its run along.
1754 pub async fn finish_job(&self, job_id: &str, conclusion: &str, reason: Option<&str>, outputs: Option<&Map<String, Value>>) -> Result<()> {
1755 let finished = self
1756 .db
1757 .prepare(
1758 "UPDATE jobs SET status = 'completed', conclusion = ?, reason = COALESCE(?, reason), outputs = COALESCE(?, outputs),
1759 finished_at = ?, token_hash = NULL, first_token_hash = NULL WHERE id = ? AND status != 'completed' RETURNING *",
1760 )
1761 .bind(&[
1762 conclusion.into(),
1763 optional(reason),
1764 outputs.map(|o| serde_json::to_string(o).unwrap_or_default()).as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
1765 now().into(),
1766 job_id.into(),
1767 ])?
1768 .first::<JobRow>(None)
1769 .await?;
1770 let Some(job) = finished else { return Ok(()) };
1771 self.tell_live(&job.repo_id, &job.run_id, None, None).await;
1772 // Its G1T_TOKEN stops working with it.
1773 self.revoke_job_tokens(&job.id).await;
1774 // A g1t.page build it opened and did not finish fails now, not at
1775 // the deployments sweep. Only a job that ran can have opened one.
1776 if job.started_at.is_some() {
1777 self.end_job_builds(&job.id, conclusion).await;
1778 }
1779 // A job that deploys failed: so did its run's deployment, now.
1780 if conclusion == "failure" && job.continue_on_error == 0 && job.started_at.is_some()
1781 && let Some(run) = self.run_row(&job.run_id).await?
1782 && let Some(env) = deploys_to(&run, &job)
1783 {
1784 self.report_deployment(&run, &env, "failure", false).await;
1785 }
1786 // A self-hosted runner's job: the runner is free again, and its time
1787 // is recorded, at nothing.
1788 if job.runner_id.is_some() {
1789 self.released(&job).await?;
1790 }
1791 // Steps still marked as going are not going any more.
1792 let mut steps: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
1793 let mut touched = false;
1794 for step in steps.iter_mut() {
1795 if step["status"] != "completed" {
1796 let was_running = step["status"] == "in_progress";
1797 step["status"] = json!("completed");
1798 step["conclusion"] = json!(if was_running { conclusion } else { "skipped" });
1799 touched = true;
1800 }
1801 }
1802 if touched {
1803 self.db
1804 .prepare("UPDATE jobs SET steps = ? WHERE id = ?")
1805 .bind(&[serde_json::to_string(&steps)?.into(), job.id.as_str().into()])?
1806 .run()
1807 .await?;
1808 }
1809 // fail-fast: one failed combination stops the rest of its matrix.
1810 if conclusion == "failure" && job.continue_on_error == 0 && job.matrix.as_deref().is_some_and(|m| m != "{}") {
1811 let run = self.run_row(&job.run_id).await?;
1812 // As its workflow, or the workflow it is a job of, says.
1813 let fail_fast = run.as_ref().and_then(|run| job_spec(run, &job)).is_none_or(|j| j.fail_fast);
1814 if fail_fast {
1815 let siblings = self
1816 .db
1817 .prepare("SELECT * FROM jobs WHERE run_id = ? AND key = ? AND status != 'completed'")
1818 .bind(&[job.run_id.as_str().into(), job.key.as_str().into()])?
1819 .all()
1820 .await?
1821 .results::<JobRow>()?;
1822 for sibling in siblings {
1823 self.stop_job(&sibling, "Another job of its matrix failed, and the matrix is fail-fast.").await?;
1824 }
1825 }
1826 }
1827 // A call waiting in its concurrency group, in another run, may start.
1828 if let Some(group) = &job.concurrency_group {
1829 self.wake_group(&job.repo_id, group, &job.run_id).await?;
1830 }
1831 Box::pin(self.advance(&job.run_id)).await
1832 }
1833
1834 /// Cancels a job. One that is running is told to stop (the answer to
1835 /// its next report), and runs its `if: always()` and `cancelled()`
1836 /// steps and its post steps before it ends `cancelled`; one that has
1837 /// not started is cancelled at once.
1838 async fn stop_job(&self, job: &JobRow, reason: &str) -> Result<()> {
1839 // A job calling a workflow stops with that workflow's jobs.
1840 if job.status == "calling"
1841 && let Some(prefix) = job.call_prefix()
1842 {
1843 let under = format!("{prefix}/");
1844 for child in self.job_rows(&job.run_id).await?.iter().filter(|child| child.key.starts_with(&under) && child.status != "completed") {
1845 Box::pin(self.stop_job(child, reason)).await?;
1846 }
1847 }
1848 if job.status == "in_progress" && job.started_at.is_some() {
1849 self.db
1850 .prepare("UPDATE jobs SET cancel_requested_at = COALESCE(cancel_requested_at, ?), reason = ? WHERE id = ? AND status = 'in_progress'")
1851 .bind(&[now().into(), reason.into(), job.id.as_str().into()])?
1852 .run()
1853 .await?;
1854 return Ok(());
1855 }
1856 self.hard_stop(job, reason).await
1857 }
1858
1859 /// Cancels a job outright, stopping its sandbox if it has one.
1860 async fn hard_stop(&self, job: &JobRow, reason: &str) -> Result<()> {
1861 // A self-hosted runner hears it was cancelled on its next poll.
1862 if job.status == "in_progress" && job.runner_id.is_none() {
1863 let _: Result<Value> = g1t_kit::call(&self.runner, "stop_actions_job", &json!({ "job": job.id })).await;
1864 }
1865 let stopped = self
1866 .db
1867 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'cancelled', reason = ?, finished_at = ?, token_hash = NULL, first_token_hash = NULL WHERE id = ? AND status != 'completed' RETURNING *")
1868 .bind(&[reason.into(), now().into(), job.id.as_str().into()])?
1869 .first::<JobRow>(None)
1870 .await?;
1871 if stopped.as_ref().is_some_and(|row| row.started_at.is_some()) {
1872 self.revoke_job_tokens(&job.id).await;
1873 self.end_job_builds(&job.id, "cancelled").await;
1874 }
1875 if let Some(stopped) = stopped.filter(|row| row.runner_id.is_some()) {
1876 self.released(&stopped).await?;
1877 }
1878 Ok(())
1879 }
1880
1881 /// Ends a job's tokens at once. A failure is logged: the token expires
1882 /// on its own soon after the job's time limit.
1883 async fn revoke_job_tokens(&self, job_id: &str) {
1884 let revoked: Result<bool> =
1885 g1t_kit::call(&self.identity, "revoke_job_tokens", &RevokeJobTokensArgs { job_id: job_id.to_owned() }).await;
1886 if let Err(error) = revoked {
1887 worker::console_error!("actions: the tokens of job {job_id} were not revoked: {error}");
1888 }
1889 }
1890
1891 /// Finishes the run when every job has.
1892 async fn finish_if_done(&self, run_id: &str) -> Result<()> {
1893 let Some(run) = self.run_row(run_id).await? else { return Ok(()) };
1894 if matches!(run.status.as_str(), "completed" | "pending" | "action_required") {
1895 return Ok(());
1896 }
1897 let jobs = self.job_rows(run_id).await?;
1898 if !jobs.iter().all(|job| job.status == "completed") {
1899 return Ok(());
1900 }
1901 self.finish_run(&run, None).await
1902 }
1903
1904 async fn finish_run(&self, run: &RunRow, error: Option<&str>) -> Result<()> {
1905 let jobs = self.job_rows(&run.id).await?;
1906 let rows: Vec<&JobRow> = jobs.iter().collect();
1907 let conclusion = if error.is_some() {
1908 "failure"
1909 } else if run.conclusion.as_deref() == Some("cancelled") {
1910 "cancelled"
1911 } else if rows.is_empty() {
1912 "skipped"
1913 } else {
1914 key_result(&rows)
1915 };
1916 let done = self
1917 .db
1918 .prepare("UPDATE runs SET status = 'completed', conclusion = ?, error = COALESCE(?, error), finished_at = ? WHERE id = ? AND status != 'completed' RETURNING id")
1919 .bind(&[conclusion.into(), optional(error), now().into(), run.id.as_str().into()])?
1920 .first::<Value>(None)
1921 .await?;
1922 if done.is_none() {
1923 return Ok(());
1924 }
1925 self.report_status(run, conclusion).await?;
1926 self.settle_deployments(run, &jobs, conclusion == "cancelled").await;
1927 let published: Result<()> = g1t_kit::call(
1928 &self.events,
1929 "publish",
1930 &g1t_contracts::events::Publish {
1931 events: vec![g1t_contracts::events::NewEvent {
1932 kind: "workflow.completed",
1933 source: "actions",
1934 repo_id: Some(run.repo_id.clone()),
1935 actor: run.actor_id.clone(),
1936 data: g1t_contracts::events::WorkflowEvent {
1937 run_id: run.id.clone(),
1938 repo_id: run.repo_id.clone(),
1939 workflow: run.name.clone(),
1940 path: run.path.clone(),
1941 number: run.number,
1942 event: run.event.clone(),
1943 conclusion: conclusion.to_owned(),
1944 git_ref: run.git_ref.clone(),
1945 sha: run.sha.clone(),
1946 pull: run.pull,
1947 },
1948 }],
1949 },
1950 )
1951 .await;
1952 if let Err(error) = published {
1953 worker::console_error!("actions: could not publish workflow.completed: {error}");
1954 }
1955 // The next run waiting in its concurrency group.
1956 if let Some(group) = &run.concurrency_group {
1957 let next = self
1958 .db
1959 .prepare("SELECT * FROM runs WHERE repo_id = ? AND concurrency_group = ? AND status = 'pending' ORDER BY id LIMIT 1")
1960 .bind(&[run.repo_id.as_str().into(), group.as_str().into()])?
1961 .first::<RunRow>(None)
1962 .await?;
1963 if let Some(next) = next {
1964 self.db.prepare("UPDATE runs SET status = 'queued' WHERE id = ?").bind(&[next.id.as_str().into()])?.run().await?;
1965 Box::pin(self.advance(&next.id)).await?;
1966 }
1967 }
1968 Ok(())
1969 }
1970
1971 /// Tells the deployments service that a job ended (`workflow_job_ended`),
1972 /// so a build it opened with `start_from_workflow` and left open fails
1973 /// at once. Never fails the job: an answer that does not come is
1974 /// logged, and the sweep fails the build later.
1975 async fn end_job_builds(&self, job_id: &str, conclusion: &str) {
1976 let ended: Result<Value> =
1977 g1t_kit::call(&self.deployments, "workflow_job_ended", &json!({ "jobId": job_id, "conclusion": conclusion })).await;
1978 if let Err(error) = ended {
1979 worker::console_log!("actions: could not tell deployments that job {job_id} ended: {error}");
1980 }
1981 }
1982
1983 /// Tells the deployments service how a run's deployment to `env` stands:
1984 /// made when its first job naming the environment starts, failed when one
1985 /// of them fails, and settled (`last`) when the run finishes. Never fails
1986 /// the run: a deployment that could not be recorded is logged.
1987 async fn report_deployment(&self, run: &RunRow, env: &JobEnvironment, state: &str, last: bool) {
1988 let path = repo_path(&run.repo);
1989 let reported: Result<Value> = g1t_kit::call(
1990 &self.deployments,
1991 "actions_deployment",
1992 &json!({
1993 "repoId": run.repo_id,
1994 "repo": { "namespace": path.namespace, "name": path.name },
1995 "runId": run.id,
1996 "attempt": run.attempt,
1997 "runUrl": format!("{SITE}/{}/actions/runs/{}", run.repo, run.id),
1998 "environment": env.name,
1999 "url": env.url,
2000 "ref": run.git_ref,
2001 "sha": run.sha,
2002 "state": state,
2003 "final": last,
2004 "creator": run.actor,
2005 "workflow": run.name,
2006 }),
2007 )
2008 .await;
2009 if let Err(error) = reported {
2010 worker::console_error!("actions: deployment to {} not recorded for run {}: {error}", env.name, run.id);
2011 }
2012 }
2013
2014 /// A job that deploys has started: its run's deployment to the
2015 /// environment is under way.
2016 pub(crate) async fn job_started(&self, job_id: &str) -> Result<()> {
2017 let Some(job) = self.db.prepare("SELECT * FROM jobs WHERE id = ?").bind(&[job_id.into()])?.first::<JobRow>(None).await? else {
2018 return Ok(());
2019 };
2020 let Some(run) = self.run_row(&job.run_id).await? else { return Ok(()) };
2021 self.tell_live(&run.repo_id, &run.id, Some(&run.sha), run.pull).await;
2022 if let Some(env) = deploys_to(&run, &job) {
2023 self.report_deployment(&run, &env, "in_progress", false).await;
2024 }
2025 Ok(())
2026 }
2027
2028 /// Pages open on the repository hear that a run's job started or
2029 /// finished, which is no event (`g1t_contracts::live`). Logged and left
2030 /// when notify cannot be reached: the pages catch up by themselves.
2031 pub(crate) async fn tell_live(&self, repo_id: &str, run_id: &str, sha: Option<&str>, pull: Option<u32>) {
2032 let Some(notify) = &self.notify else { return };
2033 let change = g1t_contracts::live::RepoChange {
2034 repo_id: repo_id.to_owned(),
2035 kind: g1t_contracts::live::RUN_UPDATED.to_owned(),
2036 run: Some(run_id.to_owned()),
2037 sha: sha.map(str::to_owned),
2038 number: pull,
2039 at: now(),
2040 ..Default::default()
2041 };
2042 let args = g1t_contracts::live::RepoChangedArgs { changes: vec![change] };
2043 let told: Result<Value> = g1t_kit::call(notify, g1t_contracts::live::REPO_CHANGED, &args).await;
2044 if let Err(error) = told {
2045 worker::console_error!("actions: live pages not told of run {run_id}: {error}");
2046 }
2047 }
2048
2049 /// The run is over: each environment its jobs deployed to takes the
2050 /// outcome of those jobs (`deployment_outcome`).
2051 async fn settle_deployments(&self, run: &RunRow, jobs: &[JobRow], cancelled: bool) {
2052 let mut seen: Vec<(JobEnvironment, Vec<Option<String>>)> = Vec::new();
2053 for job in jobs {
2054 let Some(env) = deploys_to(run, job) else { continue };
2055 let conclusion = if cancelled && job.conclusion.as_deref() != Some("skipped") && job.started_at.is_some() {
2056 Some("cancelled".to_owned())
2057 } else if job.started_at.is_none() {
2058 Some("skipped".to_owned())
2059 } else {
2060 job.conclusion.clone()
2061 };
2062 match seen.iter_mut().find(|(known, _)| known.name.eq_ignore_ascii_case(&env.name)) {
2063 Some((known, conclusions)) => {
2064 if known.url.is_none() {
2065 known.url = env.url.clone();
2066 }
2067 conclusions.push(conclusion);
2068 }
2069 None => seen.push((env, vec![conclusion])),
2070 }
2071 }
2072 for (env, conclusions) in seen {
2073 if let Some(state) = deployment_outcome(&conclusions) {
2074 self.report_deployment(run, &env, state, true).await;
2075 }
2076 }
2077 }
2078
2079 /// Tells the pull request (or commit) how the run went, as a status.
2080 async fn report_status(&self, run: &RunRow, conclusion: &str) -> Result<()> {
2081 let state = match conclusion {
2082 "success" | "skipped" => "success",
2083 "cancelled" => "error",
2084 _ => "failure",
2085 };
2086 let _: Result<Value> = g1t_kit::call(
2087 &self.work,
2088 "set_commit_status",
2089 &json!({
2090 "repoId": run.repo_id,
2091 "sha": run.sha,
2092 "context": format!("{} / {}", run.name, run.event),
2093 "state": state,
2094 "description": format!("{} {}", run.name, match conclusion {
2095 "success" => "passed",
2096 "skipped" => "was skipped",
2097 "cancelled" => "was cancelled",
2098 _ => "failed",
2099 }),
2100 "targetUrl": format!("{SITE}/{}/actions/runs/{}", run.repo, run.id),
2101 "source": "actions",
2102 }),
2103 )
2104 .await;
2105 Ok(())
2106 }
2107
2108 /// Tells the pull request a run has started on its head.
2109 pub async fn report_pending(&self, run: &RunRow) -> Result<()> {
2110 if let Err(error) = self.try_report_pending(run).await {
2111 worker::console_warn!("pending status for run {} not reported: {error}", run.id);
2112 }
2113 Ok(())
2114 }
2115
2116 /// Reports a run as pending on its commit, failing when Work did not
2117 /// store it.
2118 pub async fn try_report_pending(&self, run: &RunRow) -> Result<()> {
2119 let stored: Outcome<bool> = g1t_kit::call(
2120 &self.work,
2121 "set_commit_status",
2122 &json!({
2123 "repoId": run.repo_id,
2124 "sha": run.sha,
2125 "context": format!("{} / {}", run.name, run.event),
2126 "state": "pending",
2127 "description": if run.status == "action_required" {
2128 format!("{} is waiting for approval", run.name)
2129 } else {
2130 format!("{} is running", run.name)
2131 },
2132 "targetUrl": format!("{SITE}/{}/actions/runs/{}", run.repo, run.id),
2133 "source": "actions",
2134 }),
2135 )
2136 .await?;
2137 match stored {
2138 Outcome::Ok(_) => Ok(()),
2139 Outcome::Fail(failure) => Err(worker::Error::RustError(format!("pending status refused: {}", failure.message))),
2140 }
2141 }
2142
2143 /// Cancels a run: its waiting and queued jobs at once, and its running
2144 /// ones gracefully (`stop_job`), or outright when `force`.
2145 pub async fn cancel_run(&self, run: &RunRow, reason: &str, force: bool) -> Result<()> {
2146 self.db
2147 .prepare("UPDATE runs SET conclusion = 'cancelled' WHERE id = ? AND status != 'completed'")
2148 .bind(&[run.id.as_str().into()])?
2149 .run()
2150 .await?;
2151 for job in self.job_rows(&run.id).await?.iter().filter(|job| job.status != "completed") {
2152 if force {
2153 self.hard_stop(job, reason).await?;
2154 } else {
2155 self.stop_job(job, reason).await?;
2156 }
2157 }
2158 if run.status == "pending" || run.status == "action_required" {
2159 self.db.prepare("UPDATE runs SET status = 'queued' WHERE id = ?").bind(&[run.id.as_str().into()])?.run().await?;
2160 }
2161 self.advance(&run.id).await
2162 }
2163
2164 /// Cancels every run of the repository that has not finished, for
2165 /// `repo.deleted` and `repo.archived`.
2166 pub async fn stop_runs(&self, repo_id: &str) -> Result<()> {
2167 let runs = self
2168 .db
2169 .prepare("SELECT * FROM runs WHERE repo_id = ? AND status != 'completed'")
2170 .bind(&[repo_id.into()])?
2171 .all()
2172 .await?
2173 .results::<RunRow>()?;
2174 for run in runs {
2175 self.cancel_run(&run, "The repository was archived or deleted.", true).await?;
2176 }
2177 Ok(())
2178 }
2179
2180 pub async fn cancel(&self, a: RunActionArgs) -> Result<Outcome<WorkflowRun>> {
2181 if let Outcome::Fail(refused) = self.may(&a.actor, &a.repo, Capability::Run).await? {
2182 return Ok(Outcome::Fail(refused));
2183 }
2184 let run = check!(self.run_in(&a.repo, &a.id).await?);
2185 if run.status == "completed" {
2186 return Ok(fail(FailureCode::Conflict, "The run has already finished."));
2187 }
2188 // Cancelling a run that is already cancelling stops its jobs
2189 // outright, without waiting for their cleanup steps.
2190 let force = a.force || run.conclusion.as_deref() == Some("cancelled");
2191 let reason = if force {
2192 format!("{} stopped the run without waiting for its cleanup steps.", a.actor.username)
2193 } else {
2194 format!("{} cancelled the run.", a.actor.username)
2195 };
2196 self.cancel_run(&run, &reason, force).await?;
2197 self.run_summary(&run.id).await
2198 }
2199
2200 /// Runs again, as a new attempt: every job, with `failed_only` those
2201 /// that did not succeed, or with `job` that one; each with the jobs that
2202 /// need them. The attempt that ends is kept, its jobs and their logs and
2203 /// summaries with it (`job_attempts`, `run_attempts`).
2204 pub async fn rerun(&self, a: RunActionArgs) -> Result<Outcome<WorkflowRun>> {
2205 if let Outcome::Fail(refused) = self.may(&a.actor, &a.repo, Capability::Run).await? {
2206 return Ok(Outcome::Fail(refused));
2207 }
2208 // A job alone (`POST …/jobs/{job}/rerun`) names its run.
2209 let run_id = match (&a.job, a.id.is_empty()) {
2210 (Some(job), true) => {
2211 #[derive(Deserialize)]
2212 struct Of {
2213 run_id: String,
2214 }
2215 let of = self.db.prepare("SELECT run_id FROM jobs WHERE id = ?").bind(&[job.as_str().into()])?.first::<Of>(None).await?;
2216 match of {
2217 Some(of) => of.run_id,
2218 None => return Ok(fail(FailureCode::NotFound, "No such job.")),
2219 }
2220 }
2221 _ => a.id.clone(),
2222 };
2223 let run = check!(self.run_in(&a.repo, &run_id).await?);
2224 if run.status != "completed" {
2225 return Ok(fail(FailureCode::Conflict, "The run is still going: cancel it first."));
2226 }
2227 // Nothing starts again on an archived repository.
2228 match self.visible_repo(&a.repo, &Some(a.actor.clone())).await? {
2229 Some(repo) if repo.archived() => {
2230 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
2231 }
2232 Some(repo) if !self.actions_on(&repo).await? => {
2233 return Ok(fail(FailureCode::Forbidden, g1t_contracts::actions::actions_disabled_message(&repo.namespace, &repo.name)));
2234 }
2235 Some(_) => {}
2236 None => return Ok(fail(FailureCode::NotFound, "There is no such repository.")),
2237 }
2238 if run.error.is_some() {
2239 return Ok(fail(FailureCode::Conflict, "This run never started: fix the workflow file and push again."));
2240 }
2241 let jobs = self.job_rows(&run.id).await?;
2242 let workflow = workflow::parse(&run.source).ok();
2243 let target = match &a.job {
2244 Some(id) => match jobs.iter().find(|job| &job.id == id) {
2245 Some(job) => Some(top_key(&job.key).to_owned()),
2246 None => return Ok(fail(FailureCode::NotFound, "That job is not in the run's latest attempt.")),
2247 },
2248 None => None,
2249 };
2250 let which = match (&target, a.failed_only) {
2251 (Some(key), _) => Rerun::Job(key),
2252 (None, true) => Rerun::Failed,
2253 (None, false) => Rerun::All,
2254 };
2255 let order = workflow.as_ref().map(|w| w.job_order()).unwrap_or_default();
2256 let again = rerun_keys(
2257 &order,
2258 |key| jobs.iter().find(|j| j.key == key).map(JobRow::needs).unwrap_or_default(),
2259 |key| jobs.iter().filter(|j| j.key == key).all(|j| j.conclusion.as_deref() == Some("success")),
2260 which,
2261 );
2262 if again.is_empty() {
2263 return Ok(fail(FailureCode::Conflict, "Every job succeeded: there is nothing to run again."));
2264 }
2265 // The jobs that run again, a called workflow's with the job calling it.
2266 let rerun_ids: Vec<&str> = jobs.iter().filter(|job| again.iter().any(|key| key == top_key(&job.key))).map(|job| job.id.as_str()).collect();
2267 let ids = serde_json::to_string(&rerun_ids)?;
2268 let ended = run.attempt.to_string();
2269 let ended = ended.as_str();
2270 let mut statements = vec![
2271 // The attempt that ends, as it ended.
2272 self.db
2273 .prepare(
2274 "INSERT OR REPLACE INTO run_attempts (run_id, attempt, repo_id, conclusion, actor, debug, started_at, finished_at)
2275 SELECT id, attempt, repo_id, conclusion, COALESCE(triggering_actor, actor), debug, started_at, finished_at FROM runs WHERE id = ?",
2276 )
2277 .bind(&[run.id.as_str().into()])?,
2278 // Earlier attempts that showed a job's logs from where it ran
2279 // then now find them where they move to.
2280 self.db
2281 .prepare("UPDATE job_attempts SET log_id = log_id || '.' || ?1 WHERE run_id = ?2 AND log_id IN (SELECT value FROM json_each(?3))")
2282 .bind(&[ended.into(), run.id.as_str().into(), ids.as_str().into()])?,
2283 // Each of its jobs: one that runs again keeps its logs under
2284 // `{id}.{attempt}`; one left alone is still the live job's.
2285 self.db
2286 .prepare(
2287 "INSERT OR REPLACE INTO job_attempts (id, run_id, repo_id, attempt, job_id, log_id, key, ordinal, name, needs, status, conclusion,
2288 steps, annotations, reason, environment, labels, runner_name, started_at, finished_at)
2289 SELECT id || '.' || ?1, run_id, repo_id, ?1, id,
2290 CASE WHEN id IN (SELECT value FROM json_each(?3)) THEN id || '.' || ?1 ELSE id END,
2291 key, ordinal, name, needs, status, conclusion, steps, annotations, reason, environment, labels, runner_name, started_at, finished_at
2292 FROM jobs WHERE run_id = ?2 ORDER BY rowid",
2293 )
2294 .bind(&[ended.into(), run.id.as_str().into(), ids.as_str().into()])?,
2295 self.db
2296 .prepare("UPDATE logs SET job_id = job_id || '.' || ?1 WHERE job_id IN (SELECT value FROM json_each(?2))")
2297 .bind(&[ended.into(), ids.as_str().into()])?,
2298 self.db
2299 .prepare("UPDATE job_summaries SET job_id = job_id || '.' || ?1 WHERE job_id IN (SELECT value FROM json_each(?2))")
2300 .bind(&[ended.into(), ids.as_str().into()])?,
2301 ];
2302 for key in &again {
2303 statements.push(self.db.prepare("DELETE FROM jobs WHERE run_id = ? AND key = ? AND ordinal > 0").bind(&[run.id.as_str().into(), key.as_str().into()])?);
2304 // The jobs of a workflow it called (each matrix combination's
2305 // under `key[i]/`) are made again when it calls it again.
2306 statements.push(
2307 self.db
2308 .prepare("DELETE FROM jobs WHERE run_id = ? AND (key LIKE ? OR key LIKE ?)")
2309 .bind(&[run.id.as_str().into(), format!("{key}/%").into(), format!("{key}[%").into()])?,
2310 );
2311 statements.push(
2312 self.db
2313 .prepare(
2314 "UPDATE jobs SET status = 'waiting', conclusion = NULL, steps = '[]', annotations = '[]', outputs = '{}', reason = NULL,
2315 matrix = NULL, call = NULL, token_hash = NULL, first_token_hash = NULL, seen_at = NULL, started_at = NULL, finished_at = NULL,
2316 labels = NULL, queued_at = NULL, runner_id = NULL, runner_name = NULL, environment = NULL,
2317 concurrency_group = NULL, cancel_in_progress = 0, cancel_requested_at = NULL WHERE run_id = ? AND key = ?",
2318 )
2319 .bind(&[run.id.as_str().into(), key.as_str().into()])?,
2320 );
2321 }
2322 statements.push(
2323 self.db
2324 .prepare(
2325 "UPDATE runs SET status = 'queued', conclusion = NULL, attempt = attempt + 1, started_at = NULL, finished_at = NULL,
2326 triggering_actor = ?, debug = ? WHERE id = ?",
2327 )
2328 .bind(&[a.actor.username.as_str().into(), u32::from(a.debug).into(), run.id.as_str().into()])?,
2329 );
2330 self.db.batch(statements).await?;
2331 if let Some(run) = self.run_row(&run.id).await? {
2332 self.report_pending(&run).await?;
2333 }
2334 self.advance(&run.id).await?;
2335 // A page left open on the attempt that ended, which asks for nothing
2336 // while its run is over, hears that it is going again: re-run from
2337 // the API, the MCP tool, a pull request or another tab, as well as
2338 // from that page, it offers Cancel run and not the re-runs.
2339 self.tell_live(&run.repo_id, &run.id, Some(&run.sha), run.pull).await;
2340 self.run_summary(&run.id).await
2341 }
2342
2343 pub async fn run_in(&self, repo: &RepoPath, id: &str) -> Result<Outcome<RunRow>> {
2344 let row = self
2345 .db
2346 .prepare("SELECT * FROM runs WHERE id = ? AND lower(repo) = lower(?)")
2347 .bind(&[id.into(), format!("{}/{}", repo.namespace, repo.name).into()])?
2348 .first::<RunRow>(None)
2349 .await?;
2350 Ok(row.map_or_else(|| fail(FailureCode::NotFound, "No such run."), Outcome::Ok))
2351 }
2352
2353 // --- The sandbox's side -----------------------------------------------------
2354
2355 pub(crate) async fn job_for_token(&self, a: &JobCallArgs) -> Result<Outcome<JobRow>> {
2356 self.job_for(a, false).await
2357 }
2358
2359 /// As [`Self::job_for_token`], and also with the token the job started
2360 /// with after its harness swapped it (`job_spec` with `rotate`): for
2361 /// `brokered_secrets` alone, which the runner Worker asks with the
2362 /// token it was given at the start, and which no API route passes on.
2363 pub(crate) async fn job_for_started_token(&self, a: &JobCallArgs) -> Result<Outcome<JobRow>> {
2364 self.job_for(a, true).await
2365 }
2366
2367 async fn job_for(&self, a: &JobCallArgs, started: bool) -> Result<Outcome<JobRow>> {
2368 let job = self.db.prepare("SELECT * FROM jobs WHERE id = ?").bind(&[a.job.as_str().into()])?.first::<JobRow>(None).await?;
2369 Ok(match job {
2370 Some(job) if job.status == "in_progress" && token_opens(job.token_hash.as_deref(), job.first_token_hash.as_deref(), &a.token, started) => Outcome::Ok(job),
2371 _ => fail(FailureCode::Unauthenticated, "That job is not running, or the token is not its."),
2372 })
2373 }
2374
2375 /// `job_auth`: which run and repository a running job's token is for,
2376 /// so the API can keep its artifacts and cache.
2377 pub async fn job_auth(&self, a: JobCallArgs) -> Result<Outcome<Value>> {
2378 let job = check!(self.job_for_token(&a).await?);
2379 Ok(Outcome::Ok(json!({ "run": job.run_id, "repoId": job.repo_id })))
2380 }
2381
2382 /// `job_spec`: everything the sandbox needs to run the job.
2383 pub async fn job_spec(&self, a: JobCallArgs) -> Result<Outcome<Value>> {
2384 let job = check!(self.job_for_token(&a).await?);
2385 // Asked to, the token the harness asked with is spent here: it gets
2386 // a new one with the spec, for everything after, so a copy of the
2387 // first left on the runner's computer (a Windows job's script, a
2388 // container's environment) cannot fetch the secrets again. The new
2389 // token is made now, as the runtime token is signed with its hash,
2390 // and swapped in last, so a spec that could not be made leaves the
2391 // old one working.
2392 let next = a.rotate.then(|| random_hex(24));
2393 let token_hash = match &next {
2394 Some(next) => sha256_hex(next),
2395 None => job.token_hash.clone().unwrap_or_default(),
2396 };
2397 let Some(run) = self.run_row(&job.run_id).await? else {
2398 return Ok(fail(FailureCode::NotFound, "No such run."));
2399 };
2400 let Ok(caller) = workflow::parse(&run.source) else {
2401 return Ok(fail(FailureCode::Invalid, "The workflow no longer reads."));
2402 };
2403 // A called workflow's job runs as that workflow defines it.
2404 let callee = job.callee();
2405 let (workflow, spec, call_inputs) = match callee {
2406 Some((called, spec, call)) => (called, spec, Some(call["inputs"].clone())),
2407 None => match caller.jobs.iter().find(|j| j.id == job.key) {
2408 Some(spec) => (caller.clone(), spec.clone(), None),
2409 None => return Ok(fail(FailureCode::NotFound, "The job is not in the workflow.")),
2410 },
2411 };
2412 let spec = &spec;
2413 let repo = repo_path(&run.repo);
2414 let trusted = run.trusted != 0;
2415 // The job's `environment:`, by name, as read when its needs were done
2416 // (an expression included), once the environment's protection rules
2417 // let it start: entries with a value for it give that value instead
2418 // of their default, as GitHub's environment secrets do.
2419 let environment: Option<String> = job.environment.clone();
2420 // What its token may do: its `permissions:` (a called workflow's
2421 // jobs no more than the job that calls it), else the repository's
2422 // default; read-only for a pull request from outside.
2423 // The repository's default, its workspace's taken in, and whether
2424 // its jobs may open and approve pull requests.
2425 let (default, pull_requests) = self.token_policy(&run.repo_id).await?;
2426 let mut permissions = spec.permissions(&workflow, default);
2427 if let Some(parent) = &job.call().filter(|c| c["role"] == "callee").and_then(|c| c["parent"].as_str().map(str::to_owned)) {
2428 let top = top_key(parent);
2429 if let Some(caller_job) = caller.jobs.iter().find(|j| j.id == top) {
2430 permissions = permissions.capped_by(&caller_job.permissions(&caller, default));
2431 }
2432 }
2433 if !trusted {
2434 permissions = permissions.read_only();
2435 }
2436 // G1T_TOKEN, and GITHUB_TOKEN as its alias: a token of the
2437 // workspace's that reaches this repository only, with the scopes
2438 // its permissions give, until the job ends.
2439 let token = match self.workspace_actor(&repo.namespace).await? {
2440 Some(workspace) => {
2441 let created: CreatedAccessToken = g1t_kit::call(
2442 &self.identity,
2443 "create_job_token",
2444 &CreateJobTokenArgs {
2445 workspace,
2446 repo: repo.clone(),
2447 run_id: run.id.clone(),
2448 job_id: job.id.clone(),
2449 name: format!("G1T_TOKEN for {} run {}", run.repo, run.number),
2450 ttl_seconds: u64::from(job.timeout_minutes) * 60 + 600,
2451 scopes: permissions.scopes().into_iter().map(str::to_owned).collect(),
2452 pull_requests: pull_requests && trusted,
2453 },
2454 )
2455 .await?;
2456 created.token
2457 }
2458 None => String::new(),
2459 };
2460 // A run that is not trusted (a pull request from outside the
2461 // workspace) gets no secrets and an empty token.
2462 let passed = job.call().filter(|c| c["role"] == "callee").and_then(|c| c.get("secrets").cloned());
2463 // Brokered secrets among them (broker.rs), whatever keys they reach
2464 // the job under.
2465 let mut brokers: Vec<Broker> = Vec::new();
2466 let mut secrets = match (trusted, passed) {
2467 (false, _) => Map::new(),
2468 (true, None) => {
2469 let resolved = self.secrets_for(&run.repo_id, &run.repo, environment.as_deref(), true).await?;
2470 brokers.extend(resolved.brokers());
2471 resolved.values
2472 }
2473 // A called workflow's job: what its callers passed it (reach.rs),
2474 // and its own environment's secrets over them.
2475 (true, Some(plan)) => {
2476 let base = self.secrets_for(&run.repo_id, &run.repo, None, true).await?;
2477 brokers.extend(base.brokers());
2478 let base = base.values;
2479 let vars = self.variables_for(&run.repo_id, &run.repo, None, true).await?;
2480 let github = run.info().context(&job.key, "", run.action.as_deref());
2481 let mut passed = crate::reach::resolve_secrets(&plan, &base, &github, &vars);
2482 if let Some(name) = environment.as_deref() {
2483 let own = self.secrets_for(&run.repo_id, &run.repo, Some(name), true).await?;
2484 brokers.extend(own.brokers());
2485 for (key, value) in own.values {
2486 if base.get(&key) != Some(&value) {
2487 passed.insert(key, value);
2488 }
2489 }
2490 }
2491 passed
2492 }
2493 };
2494 // A brokered secret's value never reaches the sandbox: the job gets
2495 // a stand-in, which the runner Worker fills in on its requests to
2496 // the secret's hosts. A self-hosted runner's requests never pass
2497 // the Worker: a harness there that brokers is given each stand-in's
2498 // hosts, and passes its job's requests to them through g1t
2499 // (broker.rs); any other keeps a stand-in that does nothing, and
2500 // the log says so.
2501 let stand_ins = broker::substitute(&mut secrets, &brokers, broker::stand_in);
2502 let relayed = job.runner_id.is_some() && a.broker && !stand_ins.is_empty();
2503 if !stand_ins.is_empty() {
2504 self.keep_stand_ins(&job.id, job.timeout_minutes, &stand_ins).await?;
2505 if job.runner_id.is_some() {
2506 let mut made: Vec<&broker::StandIn> = stand_ins.iter().collect();
2507 made.sort_unstable_by(|a, b| a.broker.name.cmp(&b.broker.name));
2508 let notes: String = made
2509 .iter()
2510 .map(|made| {
2511 let note = if relayed { broker::brokered_note(&made.broker.name, &made.broker.hosts) } else { broker::self_hosted_note(&made.broker.name) };
2512 note + "\n"
2513 })
2514 .collect();
2515 self.note_log(&job.id, 0, &notes).await?;
2516 }
2517 }
2518 secrets.insert("G1T_TOKEN".into(), Value::String(token.clone()));
2519 secrets.insert("GITHUB_TOKEN".into(), Value::String(token.clone()));
2520 // Each secret as it is, a line at a time, base64 and JSON-escaped.
2521 let mut masks: Vec<String> = g1t_actions::mask::all_variants(secrets.values().filter_map(|v| v.as_str()));
2522 let vars = self.variables_for(&run.repo_id, &run.repo, environment.as_deref(), trusted).await?;
2523 // The toolkit's runtime token (runtime.rs), for as long as the job
2524 // may run; the API puts it and the toolkit's addresses in the
2525 // job's variables.
2526 let runtime_token = crate::runtime::runtime_token(
2527 &job.id,
2528 &job.run_id,
2529 &token_hash,
2530 now_ms() / 1000,
2531 u64::from(job.timeout_minutes) * 60 + 600,
2532 );
2533 masks.push(runtime_token.clone());
2534 let retention_days = self.retention_setting(&run.repo_id).await?;
2535
2536 let jobs = self.job_rows(&run.id).await?;
2537 let mut needs = Map::new();
2538 // In a called workflow, its jobs' keys sit under the job that called it.
2539 let parent = job.call().filter(|c| c["role"] == "callee").and_then(|c| c["parent"].as_str().map(str::to_owned));
2540 for need in &spec.needs {
2541 let key = match &parent {
2542 Some(parent) => format!("{parent}/{need}"),
2543 None => need.clone(),
2544 };
2545 let rows: Vec<&JobRow> = jobs.iter().filter(|row| row.key == key).collect();
2546 let mut outputs = Map::new();
2547 for row in &rows {
2548 if let Ok(Value::Object(more)) = serde_json::from_str::<Value>(&row.outputs) {
2549 outputs.extend(more);
2550 }
2551 }
2552 needs.insert(need.clone(), json!({ "result": key_result(&rows), "outputs": outputs }));
2553 }
2554 let siblings = jobs.iter().filter(|row| row.key == job.key).count();
2555 let matrix: Value = job.matrix.as_deref().and_then(|m| serde_json::from_str(m).ok()).unwrap_or(json!({}));
2556 let info = run.info();
2557 let mut github = info.context(&job.key, &token, run.action.as_deref());
2558 github["token"] = json!(token);
2559 github["retention_days"] = json!(retention_days);
2560 // On a self-hosted runner, `runner` and `RUNNER_*` describe that
2561 // machine rather than g1t's sandbox.
2562 let mut variables = info.variables(&job.key);
2563 variables.insert("GITHUB_RETENTION_DAYS".into(), json!(retention_days.to_string()));
2564 let mut runner = match &job.runner_id {
2565 Some(id) => self.runner_context_for(id, &mut variables).await?,
2566 None => runner_context(),
2567 };
2568 // A re-run with debug logging: what GitHub sets for one.
2569 if run.debug != 0 {
2570 debug_logging(&mut variables, &mut runner);
2571 }
2572
2573 // Where to check out: the repository, which holds a pull request's
2574 // test merge commit; a pull request's fork when the run builds its
2575 // head instead (`run.sha` is the head, `info.sha` what is built).
2576 let clone_url = match run.pull {
2577 Some(number) if run.event.starts_with("pull_request") && run.event != "pull_request_target" && info.sha == run.sha => {
2578 let located: Outcome<g1t_contracts::work::PullDetail> = g1t_kit::call(
2579 &self.work,
2580 "get_pull",
2581 &g1t_contracts::work::ViewArgs {
2582 repo: repo.clone(),
2583 number,
2584 viewer: self.workspace_actor(&repo.namespace).await?,
2585 after_seq: 0,
2586 },
2587 )
2588 .await?;
2589 match located {
2590 Outcome::Ok(detail) => match detail.pull.fork.or(detail.pull.head_repo) {
2591 Some(fork) => format!("{SITE}/{}/{}.git", fork.namespace, fork.name),
2592 None => format!("{SITE}/{}.git", run.repo),
2593 },
2594 Outcome::Fail(_) => format!("{SITE}/{}.git", run.repo),
2595 }
2596 }
2597 _ => format!("{SITE}/{}.git", run.repo),
2598 };
2599
2600 // Only one fetch with a token gets its spec: of two at once, the
2601 // second finds the hash already changed and is refused.
2602 if next.is_some() {
2603 let swapped = self
2604 .db
2605 .prepare(TOKEN_ROTATE)
2606 .bind(&[token_hash.as_str().into(), job.id.as_str().into(), job.token_hash.as_deref().unwrap_or_default().into()])?
2607 .first::<Value>(None)
2608 .await?;
2609 if swapped.is_none() {
2610 return Ok(fail(FailureCode::Unauthenticated, "That job is not running, or the token is not its."));
2611 }
2612 }
2613
2614 let mut spec = json!({
2615 "job": job.id,
2616 "run": run.id,
2617 "key": job.key,
2618 "name": job.name,
2619 "spec": spec.raw,
2620 "workflow": {
2621 "env": workflow.env,
2622 "defaults": workflow.raw.get("defaults").cloned().unwrap_or(Value::Null),
2623 },
2624 "github": github,
2625 "variables": variables,
2626 "event": info.event,
2627 "contexts": {
2628 "vars": vars,
2629 "secrets": secrets,
2630 "inputs": call_inputs.unwrap_or_else(|| Value::Object(run.inputs())),
2631 "matrix": matrix,
2632 "needs": needs,
2633 "strategy": {
2634 "fail-fast": spec.fail_fast,
2635 "job-index": job.ordinal,
2636 "job-total": siblings,
2637 "max-parallel": spec.max_parallel.unwrap_or(siblings as u32),
2638 },
2639 "runner": runner,
2640 },
2641 "checkout": {
2642 "repository": run.repo,
2643 "url": clone_url,
2644 "sha": info.sha,
2645 "ref": run.git_ref,
2646 "token": token,
2647 },
2648 "timeoutMinutes": job.timeout_minutes,
2649 "masks": masks,
2650 // As the job's log lists them at its start.
2651 "permissions": permissions.listed().into_iter().map(|(name, access)| (name.to_owned(), json!(access.as_str()))).collect::<Map<String, Value>>(),
2652 // Whether the job may ask for an OIDC token decides whether it
2653 // is told where to.
2654 "runtime": {
2655 "token": runtime_token,
2656 "idToken": self.oidc_allowed(&run, &job),
2657 },
2658 });
2659 if let Some(next) = next {
2660 spec["nextToken"] = json!(next);
2661 }
2662 if relayed {
2663 spec["brokered"] = broker::spec_entries(&stand_ins);
2664 }
2665 Ok(Outcome::Ok(spec))
2666 }
2667
2668 /// `job_report`: the sandbox telling how the job is going.
2669 pub async fn job_report(&self, a: JobCallArgs) -> Result<Outcome<Value>> {
2670 let job = check!(self.job_for_token(&a).await?);
2671 let report = &a.report;
2672 let at = now();
2673 match report["kind"].as_str().unwrap_or_default() {
2674 "steps" => {
2675 // The list can grow as the job goes (post steps), so steps
2676 // already reported keep where they stand.
2677 let known: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
2678 let steps: Vec<Value> = report["steps"]
2679 .as_array()
2680 .map(|names| {
2681 names
2682 .iter()
2683 .enumerate()
2684 .map(|(i, name)| match known.get(i) {
2685 Some(step) if step["status"] != "queued" => step.clone(),
2686 _ => json!({ "number": i + 1, "name": expr::to_text(name), "status": "queued", "conclusion": null, "startedAt": null, "finishedAt": null }),
2687 })
2688 .collect()
2689 })
2690 .unwrap_or_default();
2691 self.db
2692 .prepare("UPDATE jobs SET steps = ?, seen_at = ? WHERE id = ?")
2693 .bind(&[serde_json::to_string(&steps)?.into(), at.as_str().into(), job.id.as_str().into()])?
2694 .run()
2695 .await?;
2696 }
2697 "step" => {
2698 let number = report["number"].as_u64().unwrap_or(0) as usize;
2699 let mut steps: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
2700 if let Some(step) = number.checked_sub(1).and_then(|i| steps.get_mut(i)) {
2701 let status = report["status"].as_str().unwrap_or("in_progress");
2702 step["status"] = json!(status);
2703 if status == "in_progress" {
2704 step["startedAt"] = json!(at);
2705 }
2706 if status == "completed" {
2707 step["finishedAt"] = json!(at);
2708 step["conclusion"] = report["conclusion"].clone();
2709 }
2710 if let Some(name) = report["name"].as_str() {
2711 step["name"] = json!(name);
2712 }
2713 }
2714 self.db
2715 .prepare("UPDATE jobs SET steps = ?, seen_at = ? WHERE id = ?")
2716 .bind(&[serde_json::to_string(&steps)?.into(), at.as_str().into(), job.id.as_str().into()])?
2717 .run()
2718 .await?;
2719 }
2720 // A line from g1t itself, not the job: the runner Worker's note
2721 // that a brokered secret went to a host it is not for. Put
2722 // under the step that is running.
2723 "note" => {
2724 let text = report["text"].as_str().unwrap_or_default().chars().take(1000).collect::<String>();
2725 let steps: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
2726 let step = steps.iter().rev().find(|step| step["status"] == "in_progress").and_then(|step| step["number"].as_u64()).unwrap_or(0);
2727 if !text.trim().is_empty() {
2728 self.note_log(&job.id, step as u32, &text).await?;
2729 }
2730 }
2731 "log" => {
2732 let mut text = report["text"].as_str().unwrap_or_default().to_owned();
2733 // A brokered secret's value never enters the sandbox, but an
2734 // answer that echoed it whole could carry it in; it is
2735 // masked here, where the value is known.
2736 if job.brokered != 0 {
2737 let values: Vec<String> = self.stand_ins_of(&job.id).await?.into_iter().map(|secret| secret.value).collect();
2738 if !values.is_empty() {
2739 text = g1t_actions::mask::apply(&text, &g1t_actions::mask::all_variants(values.iter().map(String::as_str)));
2740 }
2741 }
2742 if text.len() > MAX_CHUNK_BYTES {
2743 let mut cut = MAX_CHUNK_BYTES;
2744 while !text.is_char_boundary(cut) {
2745 cut -= 1;
2746 }
2747 text.truncate(cut);
2748 }
2749 #[derive(Deserialize)]
2750 struct Size {
2751 n: Option<f64>,
2752 }
2753 let size = self
2754 .db
2755 .prepare("SELECT SUM(LENGTH(text)) AS n FROM logs WHERE job_id = ?")
2756 .bind(&[job.id.as_str().into()])?
2757 .first::<Size>(None)
2758 .await?;
2759 let used = size.and_then(|s| s.n).unwrap_or(0.0) as usize;
2760 if used < MAX_LOG_BYTES {
2761 if used + text.len() >= MAX_LOG_BYTES {
2762 text.push_str("\n… The log reached its limit of 4 MB; the rest is not kept.\n");
2763 }
2764 // The next `seq` is taken in the insert itself, so two
2765 // batches at once (a report sent again while the first
2766 // was still being written) never reach for the same one
2767 // and lose a chunk to the primary key.
2768 self.db
2769 .prepare(LOG_INSERT)
2770 .bind(&[
2771 job.id.as_str().into(),
2772 (report["step"].as_u64().unwrap_or(0) as u32).into(),
2773 text.into(),
2774 report["chunk"].as_u64().map_or(worker::wasm_bindgen::JsValue::NULL, |n| (n as f64).into()),
2775 ])?
2776 .run()
2777 .await?;
2778 }
2779 self.db.prepare("UPDATE jobs SET seen_at = ? WHERE id = ?").bind(&[at.into(), job.id.as_str().into()])?.run().await?;
2780 }
2781 "summary" => {
2782 // `$GITHUB_STEP_SUMMARY`, masked by the runner: added to the
2783 // step's summary, up to 1 MiB a step and 20 steps a job.
2784 let step = report["step"].as_u64().unwrap_or(0) as u32;
2785 let markdown = report["markdown"].as_str().unwrap_or_default();
2786 #[derive(Deserialize)]
2787 struct Held {
2788 steps: u32,
2789 mine: Option<f64>,
2790 }
2791 let held = self
2792 .db
2793 .prepare("SELECT COUNT(*) AS steps, MAX(CASE WHEN step = ? THEN LENGTH(markdown) END) AS mine FROM job_summaries WHERE job_id = ?")
2794 .bind(&[step.into(), job.id.as_str().into()])?
2795 .first::<Held>(None)
2796 .await?;
2797 let (steps, mine) = held.map_or((0, None), |held| (held.steps, held.mine.map(|n| n as usize)));
2798 if summary_fits(steps, mine, markdown.len()) {
2799 self.db
2800 .prepare(
2801 "INSERT INTO job_summaries (job_id, step, markdown) VALUES (?, ?, ?)
2802 ON CONFLICT (job_id, step) DO UPDATE SET markdown = job_summaries.markdown || excluded.markdown",
2803 )
2804 .bind(&[job.id.as_str().into(), step.into(), markdown.into()])?
2805 .run()
2806 .await?;
2807 }
2808 self.db.prepare("UPDATE jobs SET seen_at = ? WHERE id = ?").bind(&[at.into(), job.id.as_str().into()])?.run().await?;
2809 }
2810 "annotation" => {
2811 let mut annotations: Vec<Value> = serde_json::from_str(&job.annotations).unwrap_or_default();
2812 if annotations.len() < MAX_ANNOTATIONS {
2813 annotations.push(json!({
2814 "level": report["level"].as_str().unwrap_or("notice"),
2815 "message": report["message"].as_str().unwrap_or_default().chars().take(4000).collect::<String>(),
2816 "title": report["title"],
2817 "file": report["file"],
2818 "line": report["line"],
2819 }));
2820 self.db
2821 .prepare("UPDATE jobs SET annotations = ?, seen_at = ? WHERE id = ?")
2822 .bind(&[serde_json::to_string(&annotations)?.into(), at.as_str().into(), job.id.as_str().into()])?
2823 .run()
2824 .await?;
2825 }
2826 }
2827 // Nothing to tell; the answer says whether to stop.
2828 "ping" => {
2829 self.db.prepare("UPDATE jobs SET seen_at = ? WHERE id = ?").bind(&[at.into(), job.id.as_str().into()])?.run().await?;
2830 }
2831 "done" => {
2832 // A job told to stop ends cancelled, however its cleanup went.
2833 let conclusion = if job.cancel_requested_at.is_some() {
2834 "cancelled"
2835 } else {
2836 report["conclusion"]
2837 .as_str()
2838 .filter(|c| matches!(*c, "success" | "failure" | "cancelled"))
2839 .unwrap_or("failure")
2840 };
2841 let outputs = report["outputs"].as_object().cloned();
2842 Box::pin(self.finish_job(&job.id, conclusion, report["reason"].as_str(), outputs.as_ref())).await?;
2843 }
2844 other => return Ok(fail(FailureCode::Invalid, format!("There is no report called `{other}`."))),
2845 }
2846 // `cancelled`: the run was cancelled, and the runner should stop
2847 // the step it is on and run only its cleanup steps.
2848 Ok(Outcome::Ok(json!({ "ok": true, "cancelled": job.cancel_requested_at.is_some() })))
2849 }
2850
2851 // --- Every minute ---------------------------------------------------------------
2852
2853 pub async fn on_minute(&self, now_ms: u64) -> Result<()> {
2854 let minute = now_ms / 60_000 * 60_000;
2855 // Repositories a workspace's managed workflows changed in, beyond
2856 // those synced at once (managed.rs): their schedules wait for it.
2857 if let Err(error) = self.catch_up_syncs().await {
2858 worker::console_error!("actions: catching up syncs failed: {error}");
2859 }
2860 // Staff (or billing's usage watcher) paused scheduled runs across
2861 // g1t: this minute's schedules are skipped, not queued for later.
2862 // Kept 30 seconds in the isolate (g1t_kit::pause).
2863 if g1t_kit::pause::paused(&self.billing, g1t_contracts::billing::PauseLevel::Schedules).await {
2864 worker::console_log!("actions: schedules are paused across g1t; skipped this minute's");
2865 } else if let Err(error) = self.run_schedules(minute).await {
2866 worker::console_error!("actions: schedules failed: {error}");
2867 }
2868 // Jobs whose sandbox went quiet or ran past their time.
2869 let running = self.db.prepare("SELECT * FROM jobs WHERE status = 'in_progress'").all().await?.results::<JobRow>()?;
2870 for job in running {
2871 // Times in g1t's format compare as text.
2872 let before = |ms: u64| rfc3339(now_ms.saturating_sub(ms));
2873 let silent = job.seen_at.as_deref().is_some_and(|seen| seen < before(SILENT_MS).as_str());
2874 let limit = (u64::from(job.timeout_minutes) * 60 + 120) * 1000;
2875 let over = job.started_at.as_deref().is_some_and(|started| started < before(limit).as_str());
2876 let cancel_overdue = job.cancel_requested_at.as_deref().is_some_and(|at| at < before(CANCEL_GRACE_MS).as_str());
2877 if cancel_overdue {
2878 // Cancelled, and still going after its grace period.
2879 self.hard_stop(&job, "It was cancelled, and did not finish its cleanup steps within 5 minutes.").await?;
2880 self.advance(&job.run_id).await?;
2881 } else if over {
2882 let reason = format!("It ran longer than its time limit of {} minutes.", job.timeout_minutes);
2883 // A self-hosted runner is told to stop on its next poll.
2884 if job.runner_id.is_none() {
2885 let _: Result<Value> = g1t_kit::call(&self.runner, "stop_actions_job", &json!({ "job": job.id })).await;
2886 }
2887 self.finish_job(&job.id, "failure", Some(&reason), None).await?;
2888 } else if silent {
2889 let reason = match &job.runner_name {
2890 Some(name) => format!("The self-hosted runner {name} stopped answering."),
2891 None => "The runner stopped answering.".to_owned(),
2892 };
2893 self.finish_job(&job.id, "failure", Some(&reason), None).await?;
2894 }
2895 }
2896 // Calls of reusable workflows waiting in a concurrency group, in
2897 // case the job they waited for was cancelled in another run.
2898 #[derive(Deserialize)]
2899 struct RunId {
2900 run_id: String,
2901 }
2902 let held = self
2903 .db
2904 .prepare("SELECT DISTINCT run_id FROM jobs WHERE status = 'waiting' AND concurrency_group IS NOT NULL LIMIT 20")
2905 .all()
2906 .await?
2907 .results::<RunId>()?;
2908 for run in held {
2909 self.advance(&run.run_id).await?;
2910 }
2911 if let Err(error) = self.sweep_runners(now_ms).await {
2912 worker::console_error!("actions: the runners' sweep failed: {error}");
2913 }
2914 // Jobs held at an environment whose wait timer has run out.
2915 if let Err(error) = self.release_gates().await {
2916 worker::console_error!("actions: environments' gates failed: {error}");
2917 }
2918 // Once an hour: the cache's expired entries, and its storage.
2919 if (now_ms / 60_000) % 60 == 7
2920 && let Err(error) = self.sweep_cache(now_ms).await
2921 {
2922 worker::console_error!("actions: the cache's sweep failed: {error}");
2923 }
2924 // And the archives of GitHub's actions no job uses any more.
2925 if (now_ms / 60_000) % 60 == 47
2926 && let Err(error) = self.sweep_action_archives(now_ms).await
2927 {
2928 worker::console_error!("actions: the action archives' sweep failed: {error}");
2929 }
2930 // And artifacts past their time, and the toolkit's abandoned parts.
2931 if (now_ms / 60_000) % 60 == 37 {
2932 if let Err(error) = self.sweep_artifacts(now_ms).await {
2933 worker::console_error!("actions: the artifacts' sweep failed: {error}");
2934 }
2935 if let Err(error) = self.sweep_blob_parts(now_ms).await {
2936 worker::console_error!("actions: the blob parts' sweep failed: {error}");
2937 }
2938 }
2939 // And logs of jobs that finished longer ago than LOG_RETENTION_DAYS.
2940 if (now_ms / 60_000) % 60 == 17
2941 && let Err(error) = self.sweep_logs(now_ms).await
2942 {
2943 worker::console_error!("actions: the logs' sweep failed: {error}");
2944 }
2945 self.start_queued().await
2946 }
2947}
2948
2949
2950#[cfg(test)]
2951mod log_chunks {
2952 use rusqlite::{Connection, params};
2953
2954 use super::LOG_INSERT;
2955
2956 /// The logs table as the migrations leave it.
2957 fn database() -> Connection {
2958 let db = Connection::open_in_memory().unwrap();
2959 for name in ["0001_init.sql", "0016_log_chunks.sql"] {
2960 let path = format!("{}/migrations/{name}", env!("CARGO_MANIFEST_DIR"));
2961 db.execute_batch(&std::fs::read_to_string(path).unwrap()).unwrap();
2962 }
2963 db
2964 }
2965
2966 fn log(db: &Connection, job: &str) -> Vec<(i64, i64, String)> {
2967 let mut rows = db.prepare("SELECT seq, step, text FROM logs WHERE job_id = ? ORDER BY seq").unwrap();
2968 rows.query_map([job], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?))).unwrap().map(Result::unwrap).collect()
2969 }
2970
2971 #[test]
2972 fn a_batch_sent_again_is_kept_once() {
2973 let db = database();
2974 let insert = |job: &str, step: i64, text: &str, chunk: Option<i64>| db.execute(LOG_INSERT, params![job, step, text, chunk]).unwrap();
2975 assert_eq!(insert("job_1", 0, "one\n", Some(1)), 1);
2976 // The runner did not hear the answer and sent the batch again.
2977 assert_eq!(insert("job_1", 0, "one\n", Some(1)), 0);
2978 assert_eq!(insert("job_1", 1, "two\n", Some(2)), 1);
2979 // Another job numbers its batches from 1 too.
2980 assert_eq!(insert("job_2", 0, "other\n", Some(1)), 1);
2981 // A runner that numbers nothing has every batch kept, as before.
2982 assert_eq!(insert("job_3", 0, "a\n", None), 1);
2983 assert_eq!(insert("job_3", 0, "a\n", None), 1);
2984 assert_eq!(log(&db, "job_1"), [(1, 0, "one\n".into()), (2, 1, "two\n".into())]);
2985 assert_eq!(log(&db, "job_2"), [(1, 0, "other\n".into())]);
2986 assert_eq!(log(&db, "job_3").len(), 2);
2987 // A job run again moves its log aside (`{id}.{attempt}`), and the
2988 // new attempt's runner numbers from 1 again.
2989 db.execute("UPDATE logs SET job_id = job_id || '.1' WHERE job_id = 'job_1'", []).unwrap();
2990 assert_eq!(insert("job_1", 0, "again\n", Some(1)), 1);
2991 assert_eq!(log(&db, "job_1"), [(1, 0, "again\n".into())]);
2992 assert_eq!(log(&db, "job_1.1").len(), 2);
2993 }
2994}
2995
2996#[cfg(test)]
2997mod token_rotation {
2998 use g1t_secrets::sha256_hex;
2999 use rusqlite::{Connection, OptionalExtension, params};
3000
3001 use super::{TOKEN_ROTATE, token_opens};
3002
3003 fn database() -> Connection {
3004 let db = Connection::open_in_memory().unwrap();
3005 for name in ["0001_init.sql", "0020_job_token_rotation.sql"] {
3006 let path = format!("{}/migrations/{name}", env!("CARGO_MANIFEST_DIR"));
3007 db.execute_batch(&std::fs::read_to_string(path).unwrap()).unwrap();
3008 }
3009 db.execute(
3010 "INSERT INTO jobs (id, run_id, repo_id, namespace, key, name, status, token_hash) VALUES ('job_1', 'run_1', 'repo_1', 'acme', 'build', 'build', 'in_progress', ?1)",
3011 [sha256_hex("first")],
3012 )
3013 .unwrap();
3014 db
3015 }
3016
3017 fn rotate(db: &Connection, next: &str, shown: &str) -> bool {
3018 db.query_row(TOKEN_ROTATE, params![sha256_hex(next), "job_1", sha256_hex(shown)], |row| row.get::<_, String>(0))
3019 .optional()
3020 .unwrap()
3021 .is_some()
3022 }
3023
3024 /// The job's current token's hash, and the one it started with.
3025 fn hashes(db: &Connection) -> (Option<String>, Option<String>) {
3026 db.query_row("SELECT token_hash, first_token_hash FROM jobs WHERE id = 'job_1'", [], |row| Ok((row.get(0)?, row.get(1)?))).unwrap()
3027 }
3028
3029 #[test]
3030 fn a_job_token_fetches_its_spec_once() {
3031 let db = database();
3032 assert!(rotate(&db, "second", "first"));
3033 assert_eq!(hashes(&db), (Some(sha256_hex("second")), Some(sha256_hex("first"))));
3034 // The first token, shown again (a copy left on the computer, or a
3035 // second fetch racing the first), swaps nothing and is refused.
3036 assert!(!rotate(&db, "third", "first"));
3037 assert_eq!(hashes(&db).0, Some(sha256_hex("second")));
3038 // A job that ended has no token to swap.
3039 db.execute("UPDATE jobs SET status = 'completed', token_hash = NULL, first_token_hash = NULL", []).unwrap();
3040 assert!(!rotate(&db, "fourth", "second"));
3041 assert_eq!(hashes(&db), (None, None));
3042 }
3043
3044 #[test]
3045 fn the_worker_finds_brokered_secrets_with_the_token_the_job_started_with() {
3046 let db = database();
3047 let opens = |db: &Connection, token: &str, started: bool| {
3048 let (current, first) = hashes(db);
3049 token_opens(current.as_deref(), first.as_deref(), token, started)
3050 };
3051 // Before any swap, the job's one token opens everything.
3052 assert!(opens(&db, "first", false) && opens(&db, "first", true));
3053 assert!(rotate(&db, "second", "first"));
3054 // The harness's new token opens everything.
3055 assert!(opens(&db, "second", false) && opens(&db, "second", true));
3056 // The token it started with, which the runner Worker holds, still
3057 // finds the job's brokered secrets, and opens nothing else.
3058 assert!(opens(&db, "first", true));
3059 assert!(!opens(&db, "first", false));
3060 assert!(!opens(&db, "other", true));
3061 // Another swap keeps the token it started with, not the one between.
3062 assert!(rotate(&db, "third", "second"));
3063 assert!(opens(&db, "first", true));
3064 assert!(!opens(&db, "second", true));
3065 }
3066
3067 #[test]
3068 fn the_runtime_token_is_signed_for_the_token_that_replaces_the_first() {
3069 let now = 1_800_000_000;
3070 let token = crate::runtime::runtime_token("job_1", "run_1", &sha256_hex("second"), now, 600);
3071 assert!(crate::runtime::runtime_valid(&token, "job_1", &sha256_hex("second"), now));
3072 assert!(!crate::runtime::runtime_valid(&token, "job_1", &sha256_hex("first"), now));
3073 }
3074}
3075
3076#[cfg(test)]
3077mod stopping {
3078 use super::stops_runs;
3079 use g1t_contracts::events::Event;
3080 use serde_json::{Value, json};
3081
3082 fn event(kind: &str, data: Value) -> Event {
3083 Event {
3084 id: "evt_1".into(),
3085 kind: kind.into(),
3086 source: "repos".into(),
3087 time: "2026-10-05T00:00:00Z".into(),
3088 repo_id: Some("rep_1".into()),
3089 actor: None,
3090 data,
3091 }
3092 }
3093
3094 #[test]
3095 fn deleting_or_archiving_stops_runs() {
3096 assert_eq!(stops_runs(&event("repo.deleted", json!({ "repoId": "rep_1" }))).as_deref(), Some("rep_1"));
3097 assert_eq!(stops_runs(&event("repo.archived", json!({ "archived": true }))).as_deref(), Some("rep_1"));
3098 assert_eq!(stops_runs(&event("repo.unarchived", json!({ "archived": false }))), None);
3099 assert_eq!(stops_runs(&event("repo.restored", json!({}))), None);
3100 assert_eq!(stops_runs(&event("git.push", json!({}))), None);
3101 }
3102}
3103
3104#[cfg(test)]
3105mod status_of_needs {
3106 use std::collections::HashMap;
3107
3108 use super::ancestor_failed;
3109
3110 /// check -> plan -> (migrate) -> core -> edge, as deploy.yml has them,
3111 /// and a job that needs only the last.
3112 fn graph() -> HashMap<&'static str, Vec<&'static str>> {
3113 HashMap::from([
3114 ("check", vec![]),
3115 ("plan", vec!["check"]),
3116 ("migrate", vec!["plan"]),
3117 ("core", vec!["plan", "migrate"]),
3118 ("edge", vec!["plan", "migrate", "core"]),
3119 ("notify", vec!["edge"]),
3120 ])
3121 }
3122
3123 #[test]
3124 fn a_failure_is_seen_however_far_back() {
3125 let needs = graph();
3126 let failed = |which: &'static str| move |key: &str| key == which;
3127 // check failed; plan, and everything after, was skipped for it.
3128 assert!(ancestor_failed(&needs, "notify", failed("check")));
3129 assert!(ancestor_failed(&needs, "core", failed("check")));
3130 assert!(ancestor_failed(&needs, "edge", failed("core")));
3131 // Nothing before a job failed: a skipped migrate is not a failure.
3132 assert!(!ancestor_failed(&needs, "edge", |_| false));
3133 assert!(!ancestor_failed(&needs, "core", failed("edge")));
3134 assert!(!ancestor_failed(&needs, "check", failed("check")));
3135 }
3136
3137 #[test]
3138 fn cycles_and_unknown_keys_end() {
3139 let needs = HashMap::from([("a", vec!["b"]), ("b", vec!["a"])]);
3140 assert!(!ancestor_failed(&needs, "a", |_| false));
3141 assert!(!ancestor_failed(&needs, "missing", |_| true));
3142 }
3143}
3144
3145#[cfg(test)]
3146mod deployments {
3147 use serde_json::{Map, Value, json};
3148
3149 use super::{JobEnvironment, deployment_outcome, environment_of};
3150
3151 #[test]
3152 fn a_jobs_environment_is_read_for_deployments() {
3153 let contexts: Map<String, Value> = serde_json::from_value(json!({
3154 "github": { "ref_name": "main", "repository": "acme/web" },
3155 "inputs": { "target": "staging" },
3156 "matrix": {},
3157 }))
3158 .unwrap();
3159 let read = |raw: Value| environment_of(&raw, &contexts);
3160 assert_eq!(read(json!({})), None);
3161 assert_eq!(
3162 read(json!({ "environment": "production" })),
3163 Some(JobEnvironment { name: "production".into(), url: None, deploys: true })
3164 );
3165 assert_eq!(
3166 read(json!({ "environment": { "name": "production", "url": "https://g1t.sh" } })),
3167 Some(JobEnvironment { name: "production".into(), url: Some("https://g1t.sh".into()), deploys: true })
3168 );
3169 // Expressions are filled in from the run.
3170 assert_eq!(
3171 read(json!({ "environment": { "name": "${{ inputs.target }}", "url": "https://${{ github.ref_name }}.example.com" } })),
3172 Some(JobEnvironment { name: "staging".into(), url: Some("https://main.example.com".into()), deploys: true })
3173 );
3174 // Secrets only: no deployment.
3175 assert!(!read(json!({ "environment": { "name": "production", "deployment": false } })).unwrap().deploys);
3176 // The same, said in the job's g1t settings.
3177 assert!(!read(json!({ "environment": "production", "g1t": { "deployment": false } })).unwrap().deploys);
3178 assert!(!read(json!({ "environment": { "name": "production" }, "g1t": { "deployment": false } })).unwrap().deploys);
3179 // Only http(s) addresses.
3180 assert_eq!(read(json!({ "environment": { "name": "production", "url": "javascript:alert(1)" } })).unwrap().url, None);
3181 }
3182
3183 #[test]
3184 fn a_runs_outcome_for_an_environment() {
3185 let of = |list: &[&str]| deployment_outcome(&list.iter().map(|c| Some((*c).to_owned())).collect::<Vec<_>>());
3186 assert_eq!(of(&["success", "skipped"]), Some("success"));
3187 assert_eq!(of(&["success", "failure"]), Some("failure"));
3188 assert_eq!(of(&["success", "cancelled"]), Some("error"));
3189 assert_eq!(of(&["skipped"]), None);
3190 assert_eq!(deployment_outcome(&[None]), None);
3191 }
3192}
3193
3194#[cfg(test)]
3195mod reruns {
3196 use serde_json::{Map, Value, json};
3197
3198 use super::{MAX_SUMMARIES, MAX_SUMMARY_BYTES, Rerun, Scope, Status, call_allowed, call_prefix, debug_logging, rerun_keys, shown_name, summary_fits, top_key};
3199
3200 /// build ← test ← deploy, and lint on its own.
3201 fn keys(which: Rerun, failed: &[&str]) -> Vec<String> {
3202 let order = ["build", "lint", "test", "deploy"];
3203 let needs = |key: &str| -> Vec<String> {
3204 match key {
3205 "test" => vec!["build".into()],
3206 "deploy" => vec!["test".into()],
3207 _ => Vec::new(),
3208 }
3209 };
3210 rerun_keys(&order, needs, |key| !failed.contains(&key), which)
3211 }
3212
3213 #[test]
3214 fn a_rerun_takes_the_jobs_it_names_and_those_that_need_them() {
3215 assert_eq!(keys(Rerun::All, &[]), ["build", "lint", "test", "deploy"]);
3216 assert_eq!(keys(Rerun::Failed, &["test"]), ["test", "deploy"]);
3217 assert_eq!(keys(Rerun::Failed, &["lint"]), ["lint"]);
3218 assert!(keys(Rerun::Failed, &[]).is_empty());
3219 // One job, whatever it came to, and what depends on it.
3220 assert_eq!(keys(Rerun::Job("build"), &[]), ["build", "test", "deploy"]);
3221 assert_eq!(keys(Rerun::Job("lint"), &["test"]), ["lint"]);
3222 assert_eq!(keys(Rerun::Job("deploy"), &[]), ["deploy"]);
3223 assert!(keys(Rerun::Job("missing"), &[]).is_empty());
3224 }
3225
3226 #[test]
3227 fn a_called_workflows_jobs_run_again_with_the_job_that_calls_it() {
3228 assert_eq!(top_key("build/test"), "build");
3229 assert_eq!(top_key("build/inner/test"), "build");
3230 assert_eq!(top_key("lint"), "lint");
3231 // A matrix's calls each have their own jobs, under `key[i]/`.
3232 assert_eq!(top_key("build[1]/test"), "build");
3233 assert_eq!(top_key("build/inner[0]/test"), "build");
3234 assert_eq!(call_prefix("build", Some(1)), "build[1]");
3235 assert_eq!(call_prefix("build/inner", None), "build/inner");
3236 }
3237
3238 #[test]
3239 fn a_run_connects_ten_levels_of_workflows_and_fifty_reusable_ones() {
3240 assert!(call_allowed(1, &[], "a.yml").is_ok());
3241 assert!(call_allowed(9, &[], "a.yml").is_ok());
3242 let deep = call_allowed(10, &[], "a.yml").unwrap_err();
3243 assert!(deep.contains("at most ten") && deep.contains("nine levels"), "{deep}");
3244 let names: Vec<String> = (0..50).map(|n| format!("w{n}.yml")).collect();
3245 let fifty: Vec<&str> = names.iter().map(String::as_str).collect();
3246 // A workflow called again, as by each combination of a matrix, is one.
3247 assert!(call_allowed(1, &fifty, "w3.yml").is_ok());
3248 assert!(call_allowed(1, &fifty, "another.yml").unwrap_err().contains("at most 50 different"));
3249 }
3250
3251 #[test]
3252 fn a_matrixs_calls_are_named_by_the_caller_and_its_values() {
3253 let workflow = super::workflow::parse(
3254 "on: push\njobs:\n build:\n name: Build\n strategy:\n matrix: { os: [linux], node: [20] }\n uses: ./.g1t/workflows/b.yml\n plain:\n uses: ./.g1t/workflows/b.yml\n test:\n name: Test ${{ matrix.os }}\n strategy:\n matrix: { os: [linux] }\n runs-on: ubuntu-latest\n steps: [{ run: 'true' }]",
3255 )
3256 .unwrap();
3257 let job = |id: &str| workflow.jobs.iter().find(|job| job.id == id).unwrap();
3258 let combination: Map<String, Value> = serde_json::from_value(json!({ "os": "linux", "node": 20 })).unwrap();
3259 let mut contexts = Map::new();
3260 contexts.insert("matrix".into(), Value::Object(combination.clone()));
3261 let scope = Scope { contexts: &contexts, status: Status::Success, hash_files: None };
3262 assert_eq!(shown_name(job("build"), None, &combination, &scope), "Build (linux, 20)");
3263 assert_eq!(shown_name(job("plain"), None, &Map::new(), &scope), "plain");
3264 // A called workflow's job, under the call that made it.
3265 assert_eq!(shown_name(job("plain"), Some("Build (linux, 20)"), &Map::new(), &scope), "Build (linux, 20) / plain");
3266 assert_eq!(shown_name(job("test"), Some("Build"), &combination, &scope), "Build / Test linux");
3267 }
3268
3269 #[test]
3270 fn a_job_keeps_twenty_steps_summaries_of_a_mebibyte_each() {
3271 assert!(summary_fits(0, None, 10));
3272 assert!(!summary_fits(0, None, 0), "nothing to keep");
3273 assert!(!summary_fits(MAX_SUMMARIES, None, 10), "a twenty-first step's summary is dropped");
3274 assert!(summary_fits(MAX_SUMMARIES, Some(10), 10), "a step that has one may add to it");
3275 assert!(summary_fits(1, Some(MAX_SUMMARY_BYTES - 10), 10));
3276 assert!(!summary_fits(1, Some(MAX_SUMMARY_BYTES - 10), 11));
3277 assert!(!summary_fits(0, None, MAX_SUMMARY_BYTES + 1));
3278 }
3279
3280 #[test]
3281 fn a_debug_rerun_sets_what_github_sets() {
3282 let mut variables = Map::new();
3283 let mut runner = json!({ "name": "g1t", "debug": "" });
3284 debug_logging(&mut variables, &mut runner);
3285 assert_eq!(variables["RUNNER_DEBUG"], "1");
3286 assert_eq!(variables["ACTIONS_STEP_DEBUG"], "true");
3287 assert_eq!(variables["ACTIONS_RUNNER_DEBUG"], "true");
3288 assert_eq!(runner["debug"], Value::String("1".into()));
3289 assert_eq!(runner["name"], "g1t");
3290 }
3291}
3292
3293#[cfg(test)]
3294mod machines {
3295 use serde_json::json;
3296
3297 use super::{RunInfo, RunRow, run_is_public};
3298
3299 fn run(event: serde_json::Value) -> RunRow {
3300 let info = serde_json::to_string(&RunInfo { repository: "acme/web".into(), event, ..RunInfo::default() }).unwrap();
3301 serde_json::from_value(json!({
3302 "id": "run_1", "workflow_id": "wf_1", "repo_id": "rep_1", "repo": "acme/web", "path": ".g1t/workflows/ci.yml", "name": "CI",
3303 "title": "CI", "number": 1, "attempt": 1, "event": "push", "git_ref": "refs/heads/main", "sha": "abc", "status": "queued",
3304 "source": "", "info": info, "inputs": "{}", "trusted": 1, "created_at": "2026-10-18T00:00:00Z",
3305 }))
3306 .unwrap()
3307 }
3308
3309 #[test]
3310 fn a_runs_repository_is_public_only_when_its_event_says_so() {
3311 assert!(run_is_public(&run(json!({ "repository": { "private": false } }))));
3312 assert!(!run_is_public(&run(json!({ "repository": { "private": true } }))));
3313 // An event that doesn't say is taken as private: the standard machine.
3314 assert!(!run_is_public(&run(json!({}))));
3315 }
3316}