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