Skip to content
2,529 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::protection::Gate;
23use crate::sync::WorkflowRow;
24use crate::{Actions, Count, MAX_TIMEOUT_MINUTES, RUNNING_PER_WORKSPACE, SELF_HOSTED_MAX_TIMEOUT_MINUTES, SILENT_MS, SITE, check, fail, optional, repo_path};
25use g1t_contracts::runners::{Wanted, waiting_reason};
26
27/// The most log one job keeps, in bytes; past it, the log says so and stops.
28const MAX_LOG_BYTES: usize = 4 * 1024 * 1024;
29/// The most a single log report may add.
30const MAX_CHUNK_BYTES: usize = 256 * 1024;
31const MAX_ANNOTATIONS: usize = 50;
32/// The most one step's job summary keeps, in bytes, and how many steps of a
33/// job may have one, as on GitHub.
34pub(crate) const MAX_SUMMARY_BYTES: usize = 1024 * 1024;
35pub(crate) const MAX_SUMMARIES: u32 = 20;
36
37/// Whether a step's summary of `adding` bytes is kept: a job keeps up to
38/// 20 steps' summaries (`steps` it has, `mine` this step's bytes so far)
39/// of up to 1 MiB each.
40pub(crate) fn summary_fits(steps: u32, mine: Option<usize>, adding: usize) -> bool {
41 if adding == 0 {
42 return false;
43 }
44 match mine {
45 Some(used) => used + adding <= MAX_SUMMARY_BYTES,
46 None => steps < MAX_SUMMARIES && adding <= MAX_SUMMARY_BYTES,
47 }
48}
49
50/// The repository whose unfinished runs `event` stops, by id: one deleted,
51/// or archived (not unarchived).
52pub fn stops_runs(event: &g1t_contracts::events::Event) -> Option<String> {
53 let stops = match event.kind.as_str() {
54 "repo.deleted" => true,
55 "repo.archived" => event.data["archived"].as_bool() != Some(false),
56 _ => false,
57 };
58 if !stops {
59 return None;
60 }
61 event.repo_id.clone().or_else(|| event.data["repoId"].as_str().map(str::to_owned))
62}
63
64pub struct NewRun {
65 pub repo: Repo,
66 pub path: String,
67 pub source: String,
68 pub workflow: Workflow,
69 pub info: RunInfo,
70 pub action: Option<String>,
71 pub pull: Option<u32>,
72 pub title: String,
73 pub inputs: Map<String, Value>,
74 pub event_key: String,
75 pub actor_id: Option<String>,
76 pub actor: Option<String>,
77 pub trusted: bool,
78 /// Why the run waits for someone with the Write role to approve it
79 /// before anything starts: a pull request from outside (protection.rs).
80 pub approval: Option<String>,
81}
82
83#[derive(Clone, Deserialize)]
84pub struct RunRow {
85 pub id: String,
86 pub workflow_id: String,
87 pub repo_id: String,
88 pub repo: String,
89 pub path: String,
90 pub name: String,
91 pub title: String,
92 pub number: u64,
93 pub attempt: u64,
94 pub event: String,
95 pub action: Option<String>,
96 pub git_ref: String,
97 pub sha: String,
98 pub pull: Option<u32>,
99 pub status: String,
100 pub conclusion: Option<String>,
101 pub error: Option<String>,
102 pub actor: Option<String>,
103 pub actor_id: Option<String>,
104 pub source: String,
105 pub info: String,
106 pub inputs: String,
107 pub trusted: u32,
108 pub concurrency_group: Option<String>,
109 pub created_at: String,
110 pub started_at: Option<String>,
111 pub finished_at: Option<String>,
112 /// JSON `RunApproval`, for a run that needed approval (migration 0006).
113 #[serde(default)]
114 pub approval: Option<String>,
115 /// Whether its concurrency group cancels what it replaces.
116 #[serde(default)]
117 pub cancel_in_progress: u32,
118 /// Who started the current attempt, once it is re-run (migration 0009).
119 #[serde(default)]
120 pub triggering_actor: Option<String>,
121 /// The current attempt runs with debug logging.
122 #[serde(default)]
123 pub debug: u32,
124}
125
126impl RunRow {
127 pub fn approval(&self) -> Option<RunApproval> {
128 self.approval.as_deref().and_then(|text| serde_json::from_str(text).ok())
129 }
130
131 pub fn info(&self) -> RunInfo {
132 let mut info: RunInfo = serde_json::from_str(&self.info).unwrap_or_default();
133 info.run_id = self.id.clone();
134 info.run_number = self.number;
135 info.run_attempt = self.attempt;
136 info.workflow_path = self.path.clone();
137 if info.workflow.is_empty() {
138 info.workflow = self.name.clone();
139 }
140 info
141 }
142
143 pub fn inputs(&self) -> Map<String, Value> {
144 serde_json::from_str(&self.inputs).unwrap_or_default()
145 }
146
147 pub fn summary(&self) -> WorkflowRun {
148 WorkflowRun {
149 id: self.id.clone(),
150 workflow_id: self.workflow_id.clone(),
151 path: self.path.clone(),
152 name: self.name.clone(),
153 title: self.title.clone(),
154 number: self.number,
155 attempt: self.attempt,
156 event: self.event.clone(),
157 git_ref: self.git_ref.clone(),
158 sha: self.sha.clone(),
159 pull: self.pull,
160 status: self.status.clone(),
161 conclusion: self.conclusion.clone(),
162 error: self.error.clone(),
163 actor: self.actor.clone(),
164 created_at: self.created_at.clone(),
165 started_at: self.started_at.clone(),
166 finished_at: self.finished_at.clone(),
167 }
168 }
169}
170
171#[derive(Clone, Deserialize)]
172pub struct JobRow {
173 pub id: String,
174 pub run_id: String,
175 pub repo_id: String,
176 pub namespace: String,
177 pub key: String,
178 pub ordinal: u32,
179 pub name: String,
180 pub needs: String,
181 pub matrix: Option<String>,
182 pub status: String,
183 pub conclusion: Option<String>,
184 pub steps: String,
185 pub annotations: String,
186 pub outputs: String,
187 pub reason: Option<String>,
188 pub token_hash: Option<String>,
189 pub timeout_minutes: u32,
190 pub continue_on_error: u32,
191 pub max_parallel: Option<u32>,
192 /// Set for a job that calls a reusable workflow, and for that
193 /// workflow's jobs (see migration 0002).
194 pub call: Option<String>,
195 pub seen_at: Option<String>,
196 pub started_at: Option<String>,
197 pub finished_at: Option<String>,
198 /// For a job whose `runs-on` names self-hosted runners: what it asks
199 /// for, as a JSON array (see `g1t_contracts::runners::Wanted`), when it
200 /// started waiting, and the runner that took it (migration 0004).
201 #[serde(default)]
202 pub labels: Option<String>,
203 #[serde(default)]
204 pub queued_at: Option<String>,
205 #[serde(default)]
206 pub runner_id: Option<String>,
207 #[serde(default)]
208 pub runner_name: Option<String>,
209 /// The environment it names, read when its needs were done; a job its
210 /// rules hold is `pending` (migration 0006).
211 #[serde(default)]
212 pub environment: Option<String>,
213 /// Its own `concurrency` group, and whether that cancels what it replaces.
214 #[serde(default)]
215 pub concurrency_group: Option<String>,
216 #[serde(default)]
217 pub cancel_in_progress: u32,
218 /// When it was told to stop, while it runs its cleanup steps
219 /// (migration 0009).
220 #[serde(default)]
221 pub cancel_requested_at: Option<String>,
222}
223
224/// How long a cancelled job has to run its `if: always()` and `cancelled()`
225/// steps and its post steps before it is stopped outright, as on GitHub.
226pub const CANCEL_GRACE_MS: u64 = 5 * 60 * 1000;
227
228/// Which jobs a re-run runs again.
229#[derive(Clone, Copy, Debug, PartialEq)]
230pub enum Rerun<'a> {
231 All,
232 /// Those that did not succeed.
233 Failed,
234 /// One job's key.
235 Job(&'a str),
236}
237
238/// The keys a re-run runs again, in `order`: those `which` names and,
239/// transitively, every key that needs one of them. `needs` gives a key's
240/// needs; `succeeded` whether every job of a key succeeded.
241pub fn rerun_keys(order: &[&str], needs: impl Fn(&str) -> Vec<String>, succeeded: impl Fn(&str) -> bool, which: Rerun) -> Vec<String> {
242 let mut again: Vec<String> = Vec::new();
243 for key in order {
244 let named = match which {
245 Rerun::All => true,
246 Rerun::Failed => !succeeded(key),
247 Rerun::Job(job) => *key == job,
248 };
249 if named || needs(key).iter().any(|need| again.contains(need)) {
250 again.push((*key).to_owned());
251 }
252 }
253 again
254}
255
256/// The key under `jobs:` a job belongs to: a called workflow's jobs
257/// (`build/test`) run again with the job that calls it (`build`).
258pub fn top_key(key: &str) -> &str {
259 key.split('/').next().unwrap_or(key)
260}
261
262/// Debug logging for a job, as a re-run with it turned on gives GitHub's:
263/// `RUNNER_DEBUG=1` and `runner.debug`, and `ACTIONS_STEP_DEBUG` and
264/// `ACTIONS_RUNNER_DEBUG` set, which the runner reads as the secrets of
265/// those names (`::debug::` lines shown, and how each step's `if` read).
266pub fn debug_logging(variables: &mut Map<String, Value>, runner: &mut Value) {
267 variables.insert("RUNNER_DEBUG".into(), json!("1"));
268 variables.insert("ACTIONS_STEP_DEBUG".into(), json!("true"));
269 variables.insert("ACTIONS_RUNNER_DEBUG".into(), json!("true"));
270 runner["debug"] = json!("1");
271}
272
273impl JobRow {
274 pub fn needs(&self) -> Vec<String> {
275 serde_json::from_str(&self.needs).unwrap_or_default()
276 }
277
278 pub fn call(&self) -> Option<Value> {
279 self.call.as_deref().and_then(|call| serde_json::from_str(call).ok())
280 }
281
282 /// For a job of a called workflow: that workflow, the job's own id in
283 /// it, and the job.
284 pub fn callee(&self) -> Option<(Workflow, workflow::Job, Value)> {
285 let call = self.call().filter(|call| call["role"] == "callee")?;
286 let called = workflow::parse(call["source"].as_str()?).ok()?;
287 let job = called.jobs.iter().find(|job| call["job"].as_str() == Some(job.id.as_str()))?.clone();
288 Some((called, job, call))
289 }
290}
291
292/// A job to decide on: its key, its definition, and what it needs, as
293/// (name in `needs`, key of the jobs).
294type Unit = (String, workflow::Job, Vec<(String, String)>);
295
296/// How deep reusable workflows may call one another, as on GitHub.
297const MAX_CALL_DEPTH: u64 = 4;
298
299/// What the jobs of one key came to, for `needs.<key>`.
300fn key_result(rows: &[&JobRow]) -> &'static str {
301 let failed = |row: &&&JobRow| row.conclusion.as_deref() == Some("failure") && row.continue_on_error == 0;
302 if rows.iter().any(|row| failed(&row)) {
303 "failure"
304 } else if rows.iter().any(|row| row.conclusion.as_deref() == Some("cancelled")) {
305 "cancelled"
306 } else if rows.iter().all(|row| row.conclusion.as_deref() == Some("skipped")) {
307 "skipped"
308 } else {
309 "success"
310 }
311}
312
313/// Whether any job before `key` failed: one it needs, or one those need,
314/// however far back. A job after a skipped one still sees the failure
315/// that skipped it, as GitHub's failure() does. `needs_of`: each key's
316/// needs, as keys; `failed`: whether a key's jobs came to a failure.
317fn ancestor_failed(needs_of: &std::collections::HashMap<&str, Vec<&str>>, key: &str, failed: impl Fn(&str) -> bool) -> bool {
318 let mut seen = std::collections::HashSet::new();
319 let mut stack: Vec<&str> = needs_of.get(key).cloned().unwrap_or_default();
320 while let Some(next) = stack.pop() {
321 if !seen.insert(next) {
322 continue;
323 }
324 if failed(next) {
325 return true;
326 }
327 stack.extend(needs_of.get(next).into_iter().flatten().copied());
328 }
329 false
330}
331
332/// A job's `environment:`, as deployments read it: its name, the address in
333/// `environment.url` once its expressions are filled in from the run, and
334/// whether the job deploys to it. A job with `deployment: false` only reads
335/// the environment's secrets and variables, and makes no deployment.
336#[derive(Clone, Debug, Default, PartialEq)]
337pub(crate) struct JobEnvironment {
338 pub(crate) name: String,
339 pub(crate) url: Option<String>,
340 pub(crate) deploys: bool,
341}
342
343/// The environment `environment:` names, as written in `raw` (a job), with
344/// `contexts` to fill in expressions: null when it names none, or only
345/// through an expression this cannot read before the job runs.
346pub(crate) fn environment_of(raw: &Value, contexts: &Map<String, Value>) -> Option<JobEnvironment> {
347 let scope = Scope { contexts, status: Status::Success, hash_files: None };
348 let plain = |value: &Value| -> Option<String> {
349 let text = match value {
350 Value::String(text) if text.contains("${{") => expr::interpolate_value(value, &scope).ok().map(|v| expr::to_text(&v))?,
351 Value::String(text) => text.clone(),
352 _ => return None,
353 };
354 let text = text.trim().to_owned();
355 (!text.is_empty()).then_some(text)
356 };
357 match raw.get("environment")? {
358 name @ Value::String(_) => Some(JobEnvironment { name: plain(name)?, url: None, deploys: workflow::records_deployment(raw) }),
359 Value::Object(env) => {
360 let name = plain(env.get("name")?)?;
361 let url = env
362 .get("url")
363 .and_then(plain)
364 .filter(|url| url.starts_with("https://") || url.starts_with("http://"));
365 Some(JobEnvironment { name, url, deploys: workflow::records_deployment(raw) })
366 }
367 _ => None,
368 }
369}
370
371/// The contexts a job's `runs-on` and `environment` are read with before it
372/// runs: the run's `github`, its inputs, and the job's matrix.
373fn start_contexts(run: &RunRow, job: &JobRow, key: &str) -> Map<String, Value> {
374 let mut contexts = Map::new();
375 contexts.insert("github".into(), run.info().context(key, "", run.action.as_deref()));
376 contexts.insert("inputs".into(), Value::Object(run.inputs()));
377 contexts.insert("matrix".into(), job.matrix.as_deref().and_then(|m| serde_json::from_str(m).ok()).unwrap_or_else(|| json!({})));
378 contexts
379}
380
381/// The job as its workflow (or the workflow it calls) defines it.
382fn job_spec(run: &RunRow, job: &JobRow) -> Option<workflow::Job> {
383 match job.callee() {
384 Some((_, spec, _)) => Some(spec),
385 None => workflow::parse(&run.source).ok().and_then(|w| w.jobs.into_iter().find(|j| j.id == job.key)),
386 }
387}
388
389/// The environment a job deploys to, if it deploys: by the name read when
390/// its needs were done (which may have needed their outputs), else as
391/// its `environment:` reads now.
392pub(crate) fn deploys_to(run: &RunRow, job: &JobRow) -> Option<JobEnvironment> {
393 let spec = job_spec(run, job)?;
394 let read = environment_of(&spec.raw, &start_contexts(run, job, &spec.id));
395 let env = match (read, &job.environment) {
396 (Some(env), Some(name)) => Some(JobEnvironment { name: name.clone(), ..env }),
397 (Some(env), None) => Some(env),
398 (None, Some(name)) => Some(JobEnvironment { name: name.clone(), url: None, deploys: workflow::records_deployment(&spec.raw) }),
399 (None, None) => None,
400 };
401 env.filter(|env| env.deploys)
402}
403
404/// What the runner is told about a job it starts, from its workflow: the
405/// environment it names plainly, and the machine its `runs-on` asks for
406/// (`instance_for`; none for the standard one).
407#[derive(Default)]
408struct StartDetails {
409 environment: Option<String>,
410 instance: Option<String>,
411}
412
413fn start_details(run: &RunRow, job: &JobRow) -> StartDetails {
414 let spec = match job.callee() {
415 Some((_, spec, _)) => spec,
416 None => match workflow::parse(&run.source).ok().and_then(|w| w.jobs.into_iter().find(|j| j.id == job.key)) {
417 Some(spec) => spec,
418 None => return StartDetails::default(),
419 },
420 };
421 // As read when its needs were done, an expression's included.
422 let environment = job.environment.clone();
423 // `runs-on` as the job was queued with: its matrix and the run's
424 // inputs. A label that needs more than those is the standard machine.
425 let contexts = start_contexts(run, job, &spec.id);
426 let scope = Scope { contexts: &contexts, status: Status::Success, hash_files: None };
427 let labels: Vec<String> = match expr::interpolate_value(&spec.runs_on, &scope).unwrap_or(Value::Null) {
428 Value::String(label) => vec![label],
429 Value::Array(labels) => labels.iter().map(expr::to_text).collect(),
430 Value::Object(given) => match given.get("labels") {
431 Some(Value::Array(labels)) => labels.iter().map(expr::to_text).collect(),
432 Some(label) => vec![expr::to_text(label)],
433 None => Vec::new(),
434 },
435 _ => Vec::new(),
436 };
437 let instance = g1t_contracts::actions::instance_for(&labels);
438 StartDetails {
439 environment,
440 instance: (instance != g1t_contracts::actions::STANDARD_INSTANCE).then(|| instance.label.to_owned()),
441 }
442}
443
444fn now() -> String {
445 rfc3339(now_ms())
446}
447
448/// How a finished run went for one environment, from the conclusions of
449/// the jobs that deploy to it: failed if any failed, an error if any was
450/// cancelled, else a success; nothing when none ran (all skipped).
451pub(crate) fn deployment_outcome(conclusions: &[Option<String>]) -> Option<&'static str> {
452 let ran: Vec<&str> = conclusions.iter().flatten().map(String::as_str).filter(|c| *c != "skipped").collect();
453 if ran.is_empty() {
454 return None;
455 }
456 if ran.iter().any(|c| *c == "failure" || *c == "timed_out") {
457 return Some("failure");
458 }
459 if ran.contains(&"cancelled") {
460 return Some("error");
461 }
462 Some("success")
463}
464
465impl Actions {
466 pub async fn run_row(&self, id: &str) -> Result<Option<RunRow>> {
467 self.db.prepare("SELECT * FROM runs WHERE id = ?").bind(&[id.into()])?.first::<RunRow>(None).await
468 }
469
470 pub async fn job_rows(&self, run_id: &str) -> Result<Vec<JobRow>> {
471 self.db
472 .prepare("SELECT * FROM jobs WHERE run_id = ? ORDER BY rowid")
473 .bind(&[run_id.into()])?
474 .all()
475 .await?
476 .results::<JobRow>()
477 }
478
479 pub async fn run_summary(&self, id: &str) -> Result<Outcome<WorkflowRun>> {
480 Ok(match self.run_row(id).await? {
481 Some(row) => Outcome::Ok(row.summary()),
482 None => fail(FailureCode::NotFound, "No such run."),
483 })
484 }
485
486 /// The contexts every expression outside a job's steps may use.
487 fn base_contexts(run: &RunRow, vars: &Map<String, Value>, job: &str) -> Map<String, Value> {
488 let mut contexts = Map::new();
489 contexts.insert("github".into(), run.info().context(job, "", run.action.as_deref()));
490 contexts.insert("inputs".into(), Value::Object(run.inputs()));
491 contexts.insert("vars".into(), Value::Object(vars.clone()));
492 contexts.insert("needs".into(), json!({}));
493 contexts.insert("runner".into(), runner_context());
494 contexts
495 }
496
497 /// Makes a run and its jobs, and starts what can start. `None` when the
498 /// event already started this workflow.
499 pub async fn create_run(&self, new: NewRun) -> Result<Option<String>> {
500 // Nothing starts on an archived repository. A deleted one is never
501 // found to start anything on.
502 if new.repo.archived() {
503 return Ok(None);
504 }
505 let workflow_row = self.workflow_row(&new.repo, &new.path, &new.workflow.display_name(&new.path), &new.source).await?;
506 let numbered = self
507 .db
508 .prepare("UPDATE workflows SET run_count = run_count + 1 WHERE id = ? RETURNING run_count AS n")
509 .bind(&[workflow_row.id.as_str().into()])?
510 .first::<Count>(None)
511 .await?
512 .map_or(1, |count| count.n);
513 let id = new_id("run", now_ms());
514 let mut info = new.info.clone();
515 info.workflow = new.workflow.display_name(&new.path);
516 info.workflow_path = new.path.clone();
517 info.run_id = id.clone();
518 info.run_number = u64::from(numbered);
519 let vars = self
520 .variables_for(&new.repo.id, &format!("{}/{}", new.repo.namespace, new.repo.name), None, new.trusted)
521 .await?;
522
523 // run-name and the concurrency group read github, inputs and vars.
524 let mut contexts = Map::new();
525 contexts.insert("github".into(), info.context("", "", new.action.as_deref()));
526 contexts.insert("inputs".into(), Value::Object(new.inputs.clone()));
527 contexts.insert("vars".into(), Value::Object(vars));
528 let scope = Scope {
529 contexts: &contexts,
530 status: Status::Success,
531 hash_files: None,
532 };
533 let title = new
534 .workflow
535 .run_name
536 .as_deref()
537 .and_then(|run_name| expr::interpolate(run_name, &scope).ok())
538 .filter(|title| !title.trim().is_empty())
539 .unwrap_or(new.title.clone());
540 let group = new.workflow.concurrency.as_ref().and_then(|c| expr::interpolate(&c.group, &scope).ok());
541 let cancel_in_progress = new
542 .workflow
543 .concurrency
544 .as_ref()
545 .and_then(|c| expr::interpolate_value(&c.cancel_in_progress, &scope).ok())
546 .is_some_and(|value| expr::truthy(&value));
547
548 let approval = new.approval.as_ref().map(|reason| RunApproval { state: "required".into(), reason: reason.clone(), approved_by: None });
549 let inserted = self
550 .db
551 .prepare(
552 "INSERT OR IGNORE INTO runs (id, workflow_id, repo_id, repo, path, name, title, number, event, action, git_ref, sha,
553 pull, status, actor, actor_id, source, info, inputs, trusted, concurrency_group, event_key, created_at,
554 approval, cancel_in_progress)
555 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
556 )
557 .bind(&[
558 id.as_str().into(),
559 workflow_row.id.as_str().into(),
560 new.repo.id.as_str().into(),
561 format!("{}/{}", new.repo.namespace, new.repo.name).into(),
562 new.path.as_str().into(),
563 info.workflow.as_str().into(),
564 title.as_str().into(),
565 numbered.into(),
566 info.event_name.as_str().into(),
567 optional(new.action.as_deref()),
568 info.git_ref.as_str().into(),
569 info.sha.as_str().into(),
570 new.pull.map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
571 if approval.is_some() { "action_required" } else { "queued" }.into(),
572 optional(new.actor.as_deref()),
573 optional(new.actor_id.as_deref()),
574 new.source.as_str().into(),
575 serde_json::to_string(&info)?.into(),
576 serde_json::to_string(&new.inputs)?.into(),
577 u32::from(new.trusted).into(),
578 optional(group.as_deref()),
579 new.event_key.as_str().into(),
580 now().into(),
581 approval.as_ref().map(serde_json::to_string).transpose()?.as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
582 u32::from(cancel_in_progress).into(),
583 ])?
584 .first::<Value>(None)
585 .await?;
586 if inserted.is_none() {
587 return Ok(None);
588 }
589 if let Some(run) = self.run_row(&id).await? {
590 self.report_pending(&run).await?;
591 }
592
593 // Every job, waiting; each is expanded when the jobs it needs are done.
594 let mut statements = Vec::new();
595 for job in &new.workflow.jobs {
596 statements.push(
597 self.db
598 .prepare(
599 "INSERT INTO jobs (id, run_id, repo_id, namespace, key, name, needs, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting')",
600 )
601 .bind(&[
602 new_id("job", now_ms()).into(),
603 id.as_str().into(),
604 new.repo.id.as_str().into(),
605 new.repo.namespace.as_str().into(),
606 job.id.as_str().into(),
607 job.name.clone().filter(|n| !expr::has_expression(n)).unwrap_or(job.id.clone()).into(),
608 serde_json::to_string(&job.needs)?.into(),
609 ])?,
610 );
611 }
612 self.db.batch(statements).await?;
613
614 // A pull request's run from outside waits to be approved; it joins
615 // its concurrency group once it is (protection.rs, approve_run).
616 if approval.is_some() {
617 return Ok(Some(id));
618 }
619 if let Some(run) = self.run_row(&id).await? {
620 self.enter_group(&run).await?;
621 }
622 Ok(Some(id))
623 }
624
625 /// A run about to start: one run at a time per concurrency group, as on
626 /// GitHub. A newer run replaces one that waits in the group, and with
627 /// `cancel-in-progress` the one that runs; otherwise it waits as
628 /// `pending` for the one that runs. Then it moves along.
629 pub(crate) async fn enter_group(&self, run: &RunRow) -> Result<()> {
630 if let Some(group) = &run.concurrency_group {
631 let cancel_in_progress = run.cancel_in_progress != 0;
632 let others = self
633 .db
634 .prepare(
635 "SELECT * FROM runs WHERE repo_id = ? AND concurrency_group = ? AND id != ? AND status NOT IN ('completed', 'action_required') ORDER BY id",
636 )
637 .bind(&[run.repo_id.as_str().into(), group.as_str().into(), run.id.as_str().into()])?
638 .all()
639 .await?
640 .results::<RunRow>()?;
641 for other in &others {
642 if cancel_in_progress || other.status == "pending" {
643 // A newer run replaces a waiting one, as on GitHub.
644 self.cancel_run(other, "A newer run in the same concurrency group replaced it.", false).await?;
645 }
646 }
647 if !cancel_in_progress && others.iter().any(|other| other.status != "pending") {
648 self.db
649 .prepare("UPDATE runs SET status = 'pending' WHERE id = ?")
650 .bind(&[run.id.as_str().into()])?
651 .run()
652 .await?;
653 return Ok(());
654 }
655 }
656 self.advance(&run.id).await
657 }
658
659 /// A run that could not start, such as for a workflow file that does not read.
660 #[allow(clippy::too_many_arguments)]
661 pub async fn record_failed_run(
662 &self,
663 row: &WorkflowRow,
664 git_ref: &str,
665 sha: &str,
666 event_key: &str,
667 actor_id: Option<&str>,
668 actor: &str,
669 problem: &str,
670 ) -> Result<()> {
671 let numbered = self
672 .db
673 .prepare("UPDATE workflows SET run_count = run_count + 1 WHERE id = ? RETURNING run_count AS n")
674 .bind(&[row.id.as_str().into()])?
675 .first::<Count>(None)
676 .await?
677 .map_or(1, |count| count.n);
678 let at = now();
679 self.db
680 .prepare(
681 "INSERT OR IGNORE INTO runs (id, workflow_id, repo_id, repo, path, name, title, number, event, git_ref, sha, status,
682 conclusion, error, actor, actor_id, source, info, event_key, created_at, finished_at)
683 VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'push', ?, ?, 'completed', 'failure', ?, ?, ?, ?, '{}', ?, ?, ?)",
684 )
685 .bind(&[
686 new_id("run", now_ms()).into(),
687 row.id.as_str().into(),
688 row.repo_id.as_str().into(),
689 row.repo.as_str().into(),
690 row.path.as_str().into(),
691 row.path.as_str().into(),
692 "Invalid workflow file".into(),
693 numbered.into(),
694 git_ref.into(),
695 sha.into(),
696 problem.into(),
697 actor.into(),
698 optional(actor_id),
699 row.source.as_str().into(),
700 event_key.into(),
701 at.as_str().into(),
702 at.as_str().into(),
703 ])?
704 .run()
705 .await?;
706 Ok(())
707 }
708
709 /// Moves a run along: jobs whose needs are done are decided on, and
710 /// jobs that can start are started.
711 pub async fn advance(&self, run_id: &str) -> Result<()> {
712 // Each pass may finish jobs (skipped ones), which may free others.
713 for _ in 0..20 {
714 let Some(run) = self.run_row(run_id).await? else { return Ok(()) };
715 if matches!(run.status.as_str(), "completed" | "pending" | "action_required") {
716 return Ok(());
717 }
718 let workflow = match workflow::parse(&run.source) {
719 Ok(workflow) => workflow,
720 Err(problem) => {
721 self.finish_run(&run, Some(&problem)).await?;
722 return Ok(());
723 }
724 };
725 let jobs = self.job_rows(run_id).await?;
726 let mut changed = false;
727 // What to decide on: the workflow's jobs, and the jobs of the
728 // workflows they call, each with its needs as (name, key).
729 let mut units: Vec<Unit> = workflow
730 .jobs
731 .iter()
732 .map(|job| (job.id.clone(), job.clone(), job.needs.iter().map(|n| (n.clone(), n.clone())).collect()))
733 .collect();
734 let mut seen = std::collections::HashSet::new();
735 for row in &jobs {
736 if !seen.insert(row.key.clone()) {
737 continue;
738 }
739 if let Some((_, job, call)) = row.callee() {
740 let parent = call["parent"].as_str().unwrap_or_default().to_owned();
741 let needs = job.needs.iter().map(|n| (n.clone(), format!("{parent}/{n}"))).collect();
742 units.push((row.key.clone(), job, needs));
743 }
744 }
745 // Each key's needs, as keys, to look back through for failure().
746 let needs_of: std::collections::HashMap<&str, Vec<&str>> =
747 units.iter().map(|(key, _, needs)| (key.as_str(), needs.iter().map(|(_, need)| need.as_str()).collect())).collect();
748 let key_failed = |key: &str| key_result(&jobs.iter().filter(|row| row.key == key).collect::<Vec<_>>()) == "failure";
749 for (key, job, needs) in &units {
750 let rows: Vec<&JobRow> = jobs.iter().filter(|row| &row.key == key).collect();
751 if rows.is_empty() || !rows.iter().all(|row| row.status == "waiting") {
752 continue;
753 }
754 let needed: Vec<(&String, Vec<&JobRow>)> =
755 needs.iter().map(|(name, need)| (name, jobs.iter().filter(|row| &row.key == need).collect())).collect();
756 if !needed.iter().all(|(_, rows)| rows.iter().all(|row| row.status == "completed")) {
757 continue;
758 }
759 let failed_before = ancestor_failed(&needs_of, key, key_failed);
760 self.decide(&run, job, rows[0], &needed, failed_before).await?;
761 changed = true;
762 }
763 // A job that called a workflow finishes with that workflow's jobs.
764 for row in jobs.iter().filter(|row| row.status == "calling") {
765 let children: Vec<&JobRow> = jobs
766 .iter()
767 .filter(|child| child.call().is_some_and(|call| call["role"] == "callee" && call["parent"].as_str() == Some(row.key.as_str())))
768 .collect();
769 if !children.is_empty() && children.iter().all(|child| child.status == "completed") {
770 self.finish_call(row, &children).await?;
771 changed = true;
772 }
773 }
774 if !changed {
775 break;
776 }
777 }
778 self.start_queued().await?;
779 self.finish_if_done(run_id).await
780 }
781
782 /// Decides on one job whose needs are done: skip it, fail it, or expand
783 /// it into its matrix and queue it. `failed_before`: whether any job
784 /// before it failed, however far back (`ancestor_failed`).
785 async fn decide(&self, run: &RunRow, job: &workflow::Job, row: &JobRow, needed: &[(&String, Vec<&JobRow>)], failed_before: bool) -> Result<()> {
786 let vars = self.variables_for(&run.repo_id, &run.repo, None, run.trusted != 0).await?;
787 let mut contexts = Self::base_contexts(run, &vars, &job.id);
788 // A called workflow's jobs read the inputs they were called with.
789 let call = row.call();
790 let parent = call.as_ref().filter(|c| c["role"] == "callee").and_then(|c| c["parent"].as_str().map(str::to_owned));
791 if let Some(call) = call.as_ref().filter(|c| c["role"] == "callee") {
792 contexts.insert("inputs".into(), call["inputs"].clone());
793 }
794 let mut needs = Map::new();
795 let mut results = Vec::new();
796 for (key, rows) in needed {
797 let result = key_result(rows);
798 let mut outputs = Map::new();
799 for row in rows {
800 if let Ok(Value::Object(more)) = serde_json::from_str::<Value>(&row.outputs) {
801 outputs.extend(more);
802 }
803 }
804 results.push(result);
805 needs.insert((*key).clone(), json!({ "result": result, "outputs": outputs }));
806 }
807 // As on GitHub: a need that was skipped makes success() false but
808 // not failure(); failure() is a failure anywhere before the job.
809 let status = expr::job_status(results, failed_before, run.conclusion.as_deref() == Some("cancelled"));
810 contexts.insert("needs".into(), Value::Object(needs));
811 let scope = Scope {
812 contexts: &contexts,
813 status,
814 hash_files: None,
815 };
816 let condition = job.condition.as_deref().unwrap_or_default();
817 match expr::condition(condition, &scope) {
818 Ok(true) => {}
819 Ok(false) => return self.skip_job(row, None).await,
820 Err(problem) => return self.fail_job(row, &format!("Its `if` does not read: {problem}")).await,
821 }
822 if let Some(uses) = &job.uses {
823 return self.call_workflow(run, job, row, uses, &scope).await;
824 }
825
826 // Its matrix, which may come from a needed job's outputs.
827 let combinations = match &job.matrix {
828 None => vec![Map::new()],
829 Some(matrix) => {
830 let value = match expr::interpolate_value(matrix, &scope) {
831 Ok(value) => value,
832 Err(problem) => return self.fail_job(row, &format!("Its matrix does not read: {problem}")).await,
833 };
834 match matrix::expand(&value) {
835 Ok(combinations) if !combinations.is_empty() => combinations,
836 Ok(_) => return self.fail_job(row, "Its matrix makes no jobs.").await,
837 Err(problem) => return self.fail_job(row, &problem).await,
838 }
839 }
840 };
841 let total = combinations.len();
842 let raw = job.raw.as_object().cloned().unwrap_or_default();
843 // Whether pull requests from forks may use self-hosted runners here,
844 // asked once, and only for a run that is not trusted.
845 let mut forks_allowed: Option<bool> = None;
846 // Each concurrency group its jobs join, and whether it cancels.
847 let mut groups: Vec<(String, bool)> = Vec::new();
848 let mut statements = Vec::new();
849 for (index, combination) in combinations.iter().enumerate() {
850 let mut contexts = contexts.clone();
851 contexts.insert("matrix".into(), Value::Object(combination.clone()));
852 contexts.insert(
853 "strategy".into(),
854 json!({ "fail-fast": job.fail_fast, "job-index": index, "job-total": total, "max-parallel": job.max_parallel.unwrap_or(total as u32) }),
855 );
856 let scope = Scope {
857 contexts: &contexts,
858 status: Status::Success,
859 hash_files: None,
860 };
861 let base_name = job.name.clone().unwrap_or(job.id.clone());
862 // A called workflow's job is shown under the job that called it.
863 let base_name = match &parent {
864 Some(parent) => format!("{} / {base_name}", parent.replace('/', " / ")),
865 None => base_name,
866 };
867 let name = if expr::has_expression(&base_name) {
868 expr::interpolate(&base_name, &scope).unwrap_or(base_name)
869 } else if job.matrix.is_some() {
870 matrix::job_name(&base_name, combination)
871 } else {
872 base_name
873 };
874 let runs_on = expr::interpolate_value(&job.runs_on, &scope).unwrap_or(Value::Null);
875 let labels = match &runs_on {
876 Value::String(label) => vec![label.clone()],
877 Value::Array(labels) => labels.iter().map(expr::to_text).collect(),
878 Value::Object(spec) => spec.get("labels").map(|l| match l {
879 Value::Array(labels) => labels.iter().map(expr::to_text).collect(),
880 other => vec![expr::to_text(other)],
881 }).unwrap_or_default(),
882 _ => Vec::new(),
883 };
884 // `runs-on: self-hosted` (or a group): the workspace's own
885 // machines, which may run any OS. Otherwise g1t's Linux sandboxes.
886 let group = match &runs_on {
887 Value::Object(spec) => spec.get("group").map(expr::to_text),
888 _ => None,
889 };
890 let wanted = Wanted::of(&labels, group.as_deref());
891 let mut reason = if wanted.self_hosted {
892 None
893 } else {
894 labels
895 .iter()
896 .find(|label| {
897 let lower = label.to_ascii_lowercase();
898 lower.contains("windows") || lower.contains("macos")
899 })
900 .map(|label| {
901 let os = if label.to_ascii_lowercase().contains("windows") { "windows" } else { "macos" };
902 format!("`runs-on: {label}`: g1t's own runners are Linux. A self-hosted runner can run it: `runs-on: [self-hosted, {os}]`.")
903 })
904 };
905 // A pull request from a fork runs code anyone could write: never
906 // on the workspace's machines unless it said they may.
907 if wanted.self_hosted && run.trusted == 0 {
908 let allowed = match forks_allowed {
909 Some(allowed) => allowed,
910 None => {
911 let allowed = self.effective_runner_settings(&row.namespace, Some(&run.repo_id)).await?.fork_pull_requests;
912 forks_allowed = Some(allowed);
913 allowed
914 }
915 };
916 if !allowed {
917 reason = Some(
918 "Pull requests from forks do not run on self-hosted runners here. An admin can allow it under Settings, Runners.".to_owned(),
919 );
920 }
921 }
922 let max_minutes = if wanted.self_hosted { SELF_HOSTED_MAX_TIMEOUT_MINUTES } else { MAX_TIMEOUT_MINUTES };
923 let timeout = raw
924 .get("timeout-minutes")
925 .and_then(|value| expr::interpolate_value(value, &scope).ok())
926 .and_then(|value| value.as_f64().or_else(|| expr::to_text(&value).parse().ok()))
927 .map_or(MAX_TIMEOUT_MINUTES, |minutes| (minutes.ceil() as u32).clamp(1, max_minutes));
928 let continue_on_error = raw
929 .get("continue-on-error")
930 .and_then(|value| expr::interpolate_value(value, &scope).ok())
931 .is_some_and(|value| expr::truthy(&value));
932 let (mut status, mut conclusion, mut finished) = match &reason {
933 Some(_) => ("completed", Some("failure"), Some(now())),
934 None => ("queued", None, None),
935 };
936 // A self-hosted job waits, saying for what, until a runner takes it.
937 let (labels_json, queued_at) = if wanted.self_hosted && reason.is_none() {
938 reason = Some(waiting_reason(&wanted));
939 (Some(serde_json::to_string(&wanted.stored())?), Some(now()))
940 } else {
941 (None, None)
942 };
943 // The environment it names, an expression read now, and what
944 // that environment's protection rules say: it starts, waits as
945 // `pending` (protection.rs), or may not deploy there.
946 let environment = environment_of(&job.raw, &contexts).map(|env| env.name);
947 if status == "queued"
948 && let Some(name) = &environment
949 {
950 match self.gate(run, name).await? {
951 Gate::Open => {}
952 Gate::Held(why) => {
953 status = "pending";
954 reason = Some(why);
955 }
956 Gate::Refused(why) => {
957 (status, conclusion, finished) = ("completed", Some("failure"), Some(now()));
958 reason = Some(why);
959 }
960 }
961 }
962 // Its own concurrency group.
963 let job_group = job
964 .concurrency
965 .as_ref()
966 .and_then(|c| expr::interpolate(&c.group, &scope).ok())
967 .map(|group| group.trim().to_owned())
968 .filter(|group| !group.is_empty());
969 let job_cancel = job
970 .concurrency
971 .as_ref()
972 .and_then(|c| expr::interpolate_value(&c.cancel_in_progress, &scope).ok())
973 .is_some_and(|value| expr::truthy(&value));
974 if status != "completed"
975 && let Some(group) = &job_group
976 && !groups.iter().any(|(known, _)| known == group)
977 {
978 groups.push((group.clone(), job_cancel));
979 }
980 let values: Vec<worker::wasm_bindgen::JsValue> = vec![
981 name.into(),
982 serde_json::to_string(combination)?.into(),
983 status.into(),
984 optional(conclusion),
985 optional(reason.as_deref()),
986 timeout.into(),
987 u32::from(continue_on_error).into(),
988 job.max_parallel.map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
989 optional(finished.as_deref()),
990 optional(labels_json.as_deref()),
991 optional(queued_at.as_deref()),
992 optional(environment.as_deref()),
993 optional(job_group.as_deref()),
994 u32::from(job_cancel).into(),
995 ];
996 if index == 0 {
997 let mut bound = values;
998 bound.push(row.id.as_str().into());
999 statements.push(
1000 self.db
1001 .prepare(
1002 "UPDATE jobs SET name = ?, matrix = ?, status = ?, conclusion = ?, reason = ?, timeout_minutes = ?,
1003 continue_on_error = ?, max_parallel = ?, finished_at = ?, labels = ?, queued_at = ?, environment = ?,
1004 concurrency_group = ?, cancel_in_progress = ? WHERE id = ?",
1005 )
1006 .bind(&bound)?,
1007 );
1008 } else {
1009 let mut bound: Vec<worker::wasm_bindgen::JsValue> = vec![
1010 new_id("job", now_ms()).into(),
1011 row.run_id.as_str().into(),
1012 row.repo_id.as_str().into(),
1013 row.namespace.as_str().into(),
1014 row.key.as_str().into(),
1015 (index as u32).into(),
1016 row.needs.as_str().into(),
1017 optional(row.call.as_deref()),
1018 ];
1019 bound.extend(values);
1020 statements.push(
1021 self.db
1022 .prepare(
1023 "INSERT INTO jobs (id, run_id, repo_id, namespace, key, ordinal, needs, call, name, matrix, status, conclusion, reason,
1024 timeout_minutes, continue_on_error, max_parallel, finished_at, labels, queued_at, environment,
1025 concurrency_group, cancel_in_progress)
1026 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1027 )
1028 .bind(&bound)?,
1029 );
1030 }
1031 }
1032 self.db.batch(statements).await?;
1033 self.replace_in_groups(run, &row.key, &groups).await
1034 }
1035
1036 /// A job queued in its own concurrency group: with `cancel-in-progress`
1037 /// it cancels the group's other jobs; otherwise it replaces any that
1038 /// are queued and not started, and waits for the one running
1039 /// (`start_queued` starts one of a group at a time). As on GitHub.
1040 async fn replace_in_groups(&self, run: &RunRow, key: &str, groups: &[(String, bool)]) -> Result<()> {
1041 if groups.is_empty() {
1042 return Ok(());
1043 }
1044 #[derive(Deserialize)]
1045 struct Id {
1046 id: String,
1047 }
1048 let mine: Vec<String> = self
1049 .db
1050 .prepare("SELECT id FROM jobs WHERE run_id = ? AND key = ?")
1051 .bind(&[run.id.as_str().into(), key.into()])?
1052 .all()
1053 .await?
1054 .results::<Id>()?
1055 .into_iter()
1056 .map(|row| row.id)
1057 .collect();
1058 let mut moved: Vec<String> = Vec::new();
1059 for (group, cancel) in groups {
1060 let others = self
1061 .db
1062 .prepare("SELECT * FROM jobs WHERE repo_id = ? AND concurrency_group = ? AND status IN ('queued', 'pending', 'in_progress')")
1063 .bind(&[run.repo_id.as_str().into(), group.as_str().into()])?
1064 .all()
1065 .await?
1066 .results::<JobRow>()?;
1067 for other in others.iter().filter(|other| !mine.contains(&other.id)) {
1068 if *cancel || other.status == "queued" {
1069 self.stop_job(other, "A newer job in the same concurrency group replaced it.").await?;
1070 if !moved.contains(&other.run_id) {
1071 moved.push(other.run_id.clone());
1072 }
1073 }
1074 }
1075 }
1076 for other_run in moved.iter().filter(|id| **id != run.id) {
1077 Box::pin(self.advance(other_run)).await?;
1078 }
1079 Ok(())
1080 }
1081
1082 /// A job that calls a reusable workflow, in the repository or another
1083 /// (reach.rs): that workflow's jobs join the run under it, with the
1084 /// inputs and secrets it passes.
1085 async fn call_workflow(&self, run: &RunRow, job: &workflow::Job, row: &JobRow, uses: &str, scope: &Scope<'_>) -> Result<()> {
1086 let depth = row.call().and_then(|c| c["depth"].as_u64()).unwrap_or(0) + 1;
1087 if depth > MAX_CALL_DEPTH {
1088 return self.fail_job(row, &format!("Reusable workflows call each other more than {MAX_CALL_DEPTH} deep.")).await;
1089 }
1090 let (file, source, origin) = match self.called_workflow(run, row, uses).await? {
1091 Ok(found) => found,
1092 Err(why) => return self.fail_job(row, &why).await,
1093 };
1094 let called = match workflow::parse(&source) {
1095 Ok(called) => called,
1096 Err(problem) => return self.fail_job(row, &format!("`{file}` does not read: {problem}")).await,
1097 };
1098 let Some(trigger) = called.trigger("workflow_call") else {
1099 return self.fail_job(row, &format!("`{file}` cannot be called: it has no `on: workflow_call`.")).await;
1100 };
1101 // Inputs: what the caller passes, else the called workflow's defaults.
1102 let given = match job.raw.get("with") {
1103 Some(with) => match expr::interpolate_value(with, scope) {
1104 Ok(Value::Object(given)) => given,
1105 Ok(_) => Map::new(),
1106 Err(problem) => return self.fail_job(row, &format!("Its `with` does not read: {problem}")).await,
1107 },
1108 None => Map::new(),
1109 };
1110 let mut inputs = Map::new();
1111 for (name, spec) in &trigger.inputs {
1112 let value = given.get(name).cloned().or_else(|| spec.get("default").cloned()).unwrap_or(Value::Null);
1113 if value.is_null() && spec.get("required").and_then(Value::as_bool) == Some(true) {
1114 return self.fail_job(row, &format!("`{file}` needs the input `{name}`.")).await;
1115 }
1116 inputs.insert(name.clone(), value);
1117 }
1118 for (name, value) in given {
1119 inputs.entry(name).or_insert(value);
1120 }
1121 // Secrets: none but the job's token unless `secrets:` passes them,
1122 // by name or with `inherit`; read when each job starts (job_spec).
1123 let outer = row.call().filter(|c| c["role"] == "callee").and_then(|c| c.get("secrets").cloned());
1124 let secrets = crate::reach::secrets_plan(&job.raw, scope.contexts, outer);
1125 if let Some(name) = crate::reach::missing_secrets(&called.raw, &secrets).first() {
1126 return self.fail_job(row, &format!("`{file}` needs the secret `{name}`: pass it under `secrets:`, or use `secrets: inherit`.")).await;
1127 }
1128 let mut statements = Vec::new();
1129 for called_job in &called.jobs {
1130 let needs: Vec<String> = called_job.needs.iter().map(|n| format!("{}/{n}", row.key)).collect();
1131 let call = json!({
1132 "role": "callee", "parent": row.key, "job": called_job.id, "path": file,
1133 "source": source, "inputs": inputs, "depth": depth, "origin": origin, "secrets": secrets,
1134 });
1135 statements.push(
1136 self.db
1137 .prepare("INSERT INTO jobs (id, run_id, repo_id, namespace, key, name, needs, status, call) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting', ?)")
1138 .bind(&[
1139 new_id("job", now_ms()).into(),
1140 row.run_id.as_str().into(),
1141 row.repo_id.as_str().into(),
1142 row.namespace.as_str().into(),
1143 format!("{}/{}", row.key, called_job.id).into(),
1144 format!("{} / {}", row.name, called_job.name.clone().unwrap_or(called_job.id.clone())).into(),
1145 serde_json::to_string(&needs)?.into(),
1146 serde_json::to_string(&call)?.into(),
1147 ])?,
1148 );
1149 }
1150 statements.push(
1151 self.db
1152 .prepare("UPDATE jobs SET status = 'calling', call = ?, reason = ?, started_at = ? WHERE id = ?")
1153 .bind(&[
1154 serde_json::to_string(&json!({ "role": "caller", "path": file, "source": source }))?.into(),
1155 format!("Calls `{file}`.").into(),
1156 now().into(),
1157 row.id.as_str().into(),
1158 ])?,
1159 );
1160 self.db.batch(statements).await?;
1161 Ok(())
1162 }
1163
1164 /// A job that called a workflow, finished with its jobs: their result,
1165 /// and the outputs the workflow declares.
1166 async fn finish_call(&self, row: &JobRow, children: &[&JobRow]) -> Result<()> {
1167 let call = row.call().unwrap_or_default();
1168 let called = call["source"].as_str().and_then(|s| workflow::parse(s).ok());
1169 let mut jobs_context = Map::new();
1170 let mut by_key: std::collections::BTreeMap<String, Vec<&JobRow>> = std::collections::BTreeMap::new();
1171 for child in children {
1172 by_key.entry(child.key.clone()).or_default().push(child);
1173 }
1174 for (key, rows) in &by_key {
1175 let mut outputs = Map::new();
1176 for child in rows {
1177 if let Ok(Value::Object(more)) = serde_json::from_str::<Value>(&child.outputs) {
1178 outputs.extend(more);
1179 }
1180 }
1181 let id = key.rsplit('/').next().unwrap_or(key);
1182 jobs_context.insert(id.to_owned(), json!({ "result": key_result(rows), "outputs": outputs }));
1183 }
1184 let inputs = children.first().and_then(|c| c.call()).map(|c| c["inputs"].clone()).unwrap_or(json!({}));
1185 let mut contexts = Map::new();
1186 contexts.insert("jobs".into(), Value::Object(jobs_context));
1187 contexts.insert("inputs".into(), inputs);
1188 let scope = Scope { contexts: &contexts, status: Status::Success, hash_files: None };
1189 let mut outputs = Map::new();
1190 if let Some(Value::Object(declared)) = called.as_ref().map(|w| {
1191 let on = w.raw.get("on").or_else(|| w.raw.get("true")).cloned().unwrap_or(Value::Null);
1192 on.get("workflow_call").and_then(|c| c.get("outputs")).cloned().unwrap_or(Value::Null)
1193 }) {
1194 for (name, spec) in declared {
1195 if let Some(value) = spec.get("value") {
1196 let value = expr::interpolate_value(value, &scope).unwrap_or(Value::Null);
1197 outputs.insert(name, Value::String(expr::to_text(&value)));
1198 }
1199 }
1200 }
1201 let conclusion = key_result(children);
1202 self.db
1203 .prepare("UPDATE jobs SET status = 'completed', conclusion = ?, outputs = ?, finished_at = ? WHERE id = ? AND status = 'calling'")
1204 .bind(&[conclusion.into(), serde_json::to_string(&outputs)?.into(), now().into(), row.id.as_str().into()])?
1205 .run()
1206 .await?;
1207 Ok(())
1208 }
1209
1210 /// A file's text at a commit, if it is there.
1211 pub(crate) async fn read_file(&self, path: &RepoPath, ws: &g1t_contracts::User, sha: &str, file: &str) -> Result<Option<String>> {
1212 let blob: Outcome<g1t_contracts::repos::BlobView> = g1t_kit::call(
1213 &self.repos,
1214 "blob",
1215 &g1t_contracts::repos::BlobArgs {
1216 path: path.clone(),
1217 viewer: Some(ws.clone()),
1218 git_ref: sha.to_owned(),
1219 file_path: file.to_owned(),
1220 },
1221 )
1222 .await?;
1223 Ok(match blob {
1224 Outcome::Ok(view) => view.text,
1225 Outcome::Fail(_) => None,
1226 })
1227 }
1228
1229 async fn skip_job(&self, row: &JobRow, reason: Option<&str>) -> Result<()> {
1230 self.db
1231 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'skipped', reason = ?, finished_at = ? WHERE id = ?")
1232 .bind(&[optional(reason), now().into(), row.id.as_str().into()])?
1233 .run()
1234 .await?;
1235 Ok(())
1236 }
1237
1238 async fn fail_job(&self, row: &JobRow, reason: &str) -> Result<()> {
1239 self.db
1240 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'failure', reason = ?, finished_at = ? WHERE id = ? AND status != 'completed'")
1241 .bind(&[reason.into(), now().into(), row.id.as_str().into()])?
1242 .run()
1243 .await?;
1244 Ok(())
1245 }
1246
1247 /// Starts queued jobs, oldest first, while their workspace has room.
1248 pub async fn start_queued(&self) -> Result<()> {
1249 let queued = self
1250 .db
1251 // Self-hosted jobs are taken by their runners (runners.rs).
1252 .prepare("SELECT * FROM jobs WHERE status = 'queued' AND labels IS NULL ORDER BY rowid LIMIT 50")
1253 .all()
1254 .await?
1255 .results::<JobRow>()?;
1256 let mut running: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
1257 for job in queued {
1258 let in_workspace = match running.get(&job.namespace) {
1259 Some(n) => *n,
1260 None => {
1261 let n = self
1262 .db
1263 // Only g1t's own sandboxes count against the workspace's room.
1264 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE status = 'in_progress' AND namespace = ? AND runner_id IS NULL")
1265 .bind(&[job.namespace.as_str().into()])?
1266 .first::<Count>(None)
1267 .await?
1268 .map_or(0, |count| count.n);
1269 running.insert(job.namespace.clone(), n);
1270 n
1271 }
1272 };
1273 if in_workspace >= RUNNING_PER_WORKSPACE {
1274 continue;
1275 }
1276 if let Some(max) = job.max_parallel {
1277 let siblings = self
1278 .db
1279 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE run_id = ? AND key = ? AND status = 'in_progress'")
1280 .bind(&[job.run_id.as_str().into(), job.key.as_str().into()])?
1281 .first::<Count>(None)
1282 .await?
1283 .map_or(0, |count| count.n);
1284 if siblings >= max {
1285 continue;
1286 }
1287 }
1288 // One job of a concurrency group runs at a time.
1289 if let Some(group) = &job.concurrency_group {
1290 let running = self
1291 .db
1292 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE repo_id = ? AND concurrency_group = ? AND status = 'in_progress' AND id != ?")
1293 .bind(&[job.repo_id.as_str().into(), group.as_str().into(), job.id.as_str().into()])?
1294 .first::<Count>(None)
1295 .await?
1296 .map_or(0, |count| count.n);
1297 if running > 0 {
1298 continue;
1299 }
1300 }
1301 let token = random_hex(24);
1302 let at = now();
1303 let claimed = self
1304 .db
1305 .prepare(
1306 "UPDATE jobs SET status = 'in_progress', token_hash = ?, started_at = ?, seen_at = ? WHERE id = ? AND status = 'queued' RETURNING id",
1307 )
1308 .bind(&[sha256_hex(&token).into(), at.as_str().into(), at.as_str().into(), job.id.as_str().into()])?
1309 .first::<Value>(None)
1310 .await?;
1311 if claimed.is_none() {
1312 continue;
1313 }
1314 running.insert(job.namespace.clone(), in_workspace + 1);
1315 self.db
1316 .prepare("UPDATE runs SET status = 'in_progress', started_at = COALESCE(started_at, ?) WHERE id = ? AND status = 'queued'")
1317 .bind(&[at.as_str().into(), job.run_id.as_str().into()])?
1318 .run()
1319 .await?;
1320 let run = self.run_row(&job.run_id).await?;
1321 let repo: RepoPath = run.as_ref().map(|run| repo_path(&run.repo)).unwrap_or(RepoPath {
1322 namespace: job.namespace.clone(),
1323 name: String::new(),
1324 });
1325 // Its environment and the machine it asked for, for the runner.
1326 let details = run.as_ref().map(|run| start_details(run, &job)).unwrap_or_default();
1327 let started: Outcome<Value> = g1t_kit::call(
1328 &self.runner,
1329 "start_actions_job",
1330 &StartJobArgs {
1331 job: job.id.clone(),
1332 token,
1333 repo,
1334 timeout_minutes: job.timeout_minutes,
1335 workflow: run.as_ref().map(|run| run.path.clone()),
1336 environment: details.environment,
1337 trusted: run.as_ref().is_some_and(|run| run.trusted != 0),
1338 instance: details.instance,
1339 },
1340 )
1341 .await
1342 .unwrap_or_else(|error| fail(FailureCode::Conflict, format!("The runner could not be reached: {error}")));
1343 if let Outcome::Fail(refused) = started {
1344 // Billing would not pay for a scheduled run's job: the
1345 // schedule waits rather than making runs only to refuse them.
1346 if refused.code == FailureCode::PaymentRequired
1347 && let Some(run) = run.as_ref().filter(|run| run.event == "schedule")
1348 {
1349 self.db
1350 .prepare("UPDATE workflows SET schedule_refused_until = ? WHERE id = ?")
1351 .bind(&[rfc3339(now_ms() + crate::SCHEDULE_REFUSED_MS).into(), run.workflow_id.as_str().into()])?
1352 .run()
1353 .await?;
1354 }
1355 Box::pin(self.finish_job(&job.id, "failure", Some(&refused.message), None)).await?;
1356 } else {
1357 self.job_started(&job.id).await?;
1358 }
1359 }
1360 Ok(())
1361 }
1362
1363 /// Finishes a job and moves its run along.
1364 pub async fn finish_job(&self, job_id: &str, conclusion: &str, reason: Option<&str>, outputs: Option<&Map<String, Value>>) -> Result<()> {
1365 let finished = self
1366 .db
1367 .prepare(
1368 "UPDATE jobs SET status = 'completed', conclusion = ?, reason = COALESCE(?, reason), outputs = COALESCE(?, outputs),
1369 finished_at = ?, token_hash = NULL WHERE id = ? AND status != 'completed' RETURNING *",
1370 )
1371 .bind(&[
1372 conclusion.into(),
1373 optional(reason),
1374 outputs.map(|o| serde_json::to_string(o).unwrap_or_default()).as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
1375 now().into(),
1376 job_id.into(),
1377 ])?
1378 .first::<JobRow>(None)
1379 .await?;
1380 let Some(job) = finished else { return Ok(()) };
1381 // Its G1T_TOKEN stops working with it.
1382 self.revoke_job_tokens(&job.id).await;
1383 // A job that deploys failed: so did its run's deployment, now.
1384 if conclusion == "failure" && job.continue_on_error == 0 && job.started_at.is_some()
1385 && let Some(run) = self.run_row(&job.run_id).await?
1386 && let Some(env) = deploys_to(&run, &job)
1387 {
1388 self.report_deployment(&run, &env, "failure", false).await;
1389 }
1390 // A self-hosted runner's job: the runner is free again, and its time
1391 // is recorded, at nothing.
1392 if job.runner_id.is_some() {
1393 self.released(&job).await?;
1394 }
1395 // Steps still marked as going are not going any more.
1396 let mut steps: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
1397 let mut touched = false;
1398 for step in steps.iter_mut() {
1399 if step["status"] != "completed" {
1400 let was_running = step["status"] == "in_progress";
1401 step["status"] = json!("completed");
1402 step["conclusion"] = json!(if was_running { conclusion } else { "skipped" });
1403 touched = true;
1404 }
1405 }
1406 if touched {
1407 self.db
1408 .prepare("UPDATE jobs SET steps = ? WHERE id = ?")
1409 .bind(&[serde_json::to_string(&steps)?.into(), job.id.as_str().into()])?
1410 .run()
1411 .await?;
1412 }
1413 // fail-fast: one failed combination stops the rest of its matrix.
1414 if conclusion == "failure" && job.continue_on_error == 0 && job.matrix.as_deref().is_some_and(|m| m != "{}") {
1415 let run = self.run_row(&job.run_id).await?;
1416 let fail_fast = run
1417 .as_ref()
1418 .and_then(|run| workflow::parse(&run.source).ok())
1419 .and_then(|workflow| workflow.jobs.into_iter().find(|j| j.id == job.key))
1420 .is_none_or(|j| j.fail_fast);
1421 if fail_fast {
1422 let siblings = self
1423 .db
1424 .prepare("SELECT * FROM jobs WHERE run_id = ? AND key = ? AND status != 'completed'")
1425 .bind(&[job.run_id.as_str().into(), job.key.as_str().into()])?
1426 .all()
1427 .await?
1428 .results::<JobRow>()?;
1429 for sibling in siblings {
1430 self.stop_job(&sibling, "Another job of its matrix failed, and the matrix is fail-fast.").await?;
1431 }
1432 }
1433 }
1434 Box::pin(self.advance(&job.run_id)).await
1435 }
1436
1437 /// Cancels a job. One that is running is told to stop (the answer to
1438 /// its next report), and runs its `if: always()` and `cancelled()`
1439 /// steps and its post steps before it ends `cancelled`; one that has
1440 /// not started is cancelled at once.
1441 async fn stop_job(&self, job: &JobRow, reason: &str) -> Result<()> {
1442 if job.status == "in_progress" && job.started_at.is_some() {
1443 self.db
1444 .prepare("UPDATE jobs SET cancel_requested_at = COALESCE(cancel_requested_at, ?), reason = ? WHERE id = ? AND status = 'in_progress'")
1445 .bind(&[now().into(), reason.into(), job.id.as_str().into()])?
1446 .run()
1447 .await?;
1448 return Ok(());
1449 }
1450 self.hard_stop(job, reason).await
1451 }
1452
1453 /// Cancels a job outright, stopping its sandbox if it has one.
1454 async fn hard_stop(&self, job: &JobRow, reason: &str) -> Result<()> {
1455 // A self-hosted runner hears it was cancelled on its next poll.
1456 if job.status == "in_progress" && job.runner_id.is_none() {
1457 let _: Result<Value> = g1t_kit::call(&self.runner, "stop_actions_job", &json!({ "job": job.id })).await;
1458 }
1459 let stopped = self
1460 .db
1461 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'cancelled', reason = ?, finished_at = ?, token_hash = NULL WHERE id = ? AND status != 'completed' RETURNING *")
1462 .bind(&[reason.into(), now().into(), job.id.as_str().into()])?
1463 .first::<JobRow>(None)
1464 .await?;
1465 if stopped.as_ref().is_some_and(|row| row.started_at.is_some()) {
1466 self.revoke_job_tokens(&job.id).await;
1467 }
1468 if let Some(stopped) = stopped.filter(|row| row.runner_id.is_some()) {
1469 self.released(&stopped).await?;
1470 }
1471 Ok(())
1472 }
1473
1474 /// Ends a job's tokens at once. A failure is logged: the token expires
1475 /// on its own soon after the job's time limit.
1476 async fn revoke_job_tokens(&self, job_id: &str) {
1477 let revoked: Result<bool> =
1478 g1t_kit::call(&self.identity, "revoke_job_tokens", &RevokeJobTokensArgs { job_id: job_id.to_owned() }).await;
1479 if let Err(error) = revoked {
1480 worker::console_error!("actions: the tokens of job {job_id} were not revoked: {error}");
1481 }
1482 }
1483
1484 /// Finishes the run when every job has.
1485 async fn finish_if_done(&self, run_id: &str) -> Result<()> {
1486 let Some(run) = self.run_row(run_id).await? else { return Ok(()) };
1487 if matches!(run.status.as_str(), "completed" | "pending" | "action_required") {
1488 return Ok(());
1489 }
1490 let jobs = self.job_rows(run_id).await?;
1491 if !jobs.iter().all(|job| job.status == "completed") {
1492 return Ok(());
1493 }
1494 self.finish_run(&run, None).await
1495 }
1496
1497 async fn finish_run(&self, run: &RunRow, error: Option<&str>) -> Result<()> {
1498 let jobs = self.job_rows(&run.id).await?;
1499 let rows: Vec<&JobRow> = jobs.iter().collect();
1500 let conclusion = if error.is_some() {
1501 "failure"
1502 } else if run.conclusion.as_deref() == Some("cancelled") {
1503 "cancelled"
1504 } else if rows.is_empty() {
1505 "skipped"
1506 } else {
1507 key_result(&rows)
1508 };
1509 let done = self
1510 .db
1511 .prepare("UPDATE runs SET status = 'completed', conclusion = ?, error = COALESCE(?, error), finished_at = ? WHERE id = ? AND status != 'completed' RETURNING id")
1512 .bind(&[conclusion.into(), optional(error), now().into(), run.id.as_str().into()])?
1513 .first::<Value>(None)
1514 .await?;
1515 if done.is_none() {
1516 return Ok(());
1517 }
1518 self.report_status(run, conclusion).await?;
1519 self.settle_deployments(run, &jobs, conclusion == "cancelled").await;
1520 let published: Result<()> = g1t_kit::call(
1521 &self.events,
1522 "publish",
1523 &g1t_contracts::events::Publish {
1524 events: vec![g1t_contracts::events::NewEvent {
1525 kind: "workflow.completed",
1526 source: "actions",
1527 repo_id: Some(run.repo_id.clone()),
1528 actor: run.actor_id.clone(),
1529 data: g1t_contracts::events::WorkflowEvent {
1530 run_id: run.id.clone(),
1531 repo_id: run.repo_id.clone(),
1532 workflow: run.name.clone(),
1533 path: run.path.clone(),
1534 number: run.number,
1535 event: run.event.clone(),
1536 conclusion: conclusion.to_owned(),
1537 git_ref: run.git_ref.clone(),
1538 sha: run.sha.clone(),
1539 pull: run.pull,
1540 },
1541 }],
1542 },
1543 )
1544 .await;
1545 if let Err(error) = published {
1546 worker::console_error!("actions: could not publish workflow.completed: {error}");
1547 }
1548 // The next run waiting in its concurrency group.
1549 if let Some(group) = &run.concurrency_group {
1550 let next = self
1551 .db
1552 .prepare("SELECT * FROM runs WHERE repo_id = ? AND concurrency_group = ? AND status = 'pending' ORDER BY id LIMIT 1")
1553 .bind(&[run.repo_id.as_str().into(), group.as_str().into()])?
1554 .first::<RunRow>(None)
1555 .await?;
1556 if let Some(next) = next {
1557 self.db.prepare("UPDATE runs SET status = 'queued' WHERE id = ?").bind(&[next.id.as_str().into()])?.run().await?;
1558 Box::pin(self.advance(&next.id)).await?;
1559 }
1560 }
1561 Ok(())
1562 }
1563
1564 /// Tells the deployments service how a run's deployment to `env` stands:
1565 /// made when its first job naming the environment starts, failed when one
1566 /// of them fails, and settled (`last`) when the run finishes. Never fails
1567 /// the run: a deployment that could not be recorded is logged.
1568 async fn report_deployment(&self, run: &RunRow, env: &JobEnvironment, state: &str, last: bool) {
1569 let path = repo_path(&run.repo);
1570 let reported: Result<Value> = g1t_kit::call(
1571 &self.deployments,
1572 "actions_deployment",
1573 &json!({
1574 "repoId": run.repo_id,
1575 "repo": { "namespace": path.namespace, "name": path.name },
1576 "runId": run.id,
1577 "attempt": run.attempt,
1578 "runUrl": format!("{SITE}/{}/actions/runs/{}", run.repo, run.id),
1579 "environment": env.name,
1580 "url": env.url,
1581 "ref": run.git_ref,
1582 "sha": run.sha,
1583 "state": state,
1584 "final": last,
1585 "creator": run.actor,
1586 "workflow": run.name,
1587 }),
1588 )
1589 .await;
1590 if let Err(error) = reported {
1591 worker::console_error!("actions: deployment to {} not recorded for run {}: {error}", env.name, run.id);
1592 }
1593 }
1594
1595 /// A job that deploys has started: its run's deployment to the
1596 /// environment is under way.
1597 pub(crate) async fn job_started(&self, job_id: &str) -> Result<()> {
1598 let Some(job) = self.db.prepare("SELECT * FROM jobs WHERE id = ?").bind(&[job_id.into()])?.first::<JobRow>(None).await? else {
1599 return Ok(());
1600 };
1601 let Some(run) = self.run_row(&job.run_id).await? else { return Ok(()) };
1602 if let Some(env) = deploys_to(&run, &job) {
1603 self.report_deployment(&run, &env, "in_progress", false).await;
1604 }
1605 Ok(())
1606 }
1607
1608 /// The run is over: each environment its jobs deployed to takes the
1609 /// outcome of those jobs (`deployment_outcome`).
1610 async fn settle_deployments(&self, run: &RunRow, jobs: &[JobRow], cancelled: bool) {
1611 let mut seen: Vec<(JobEnvironment, Vec<Option<String>>)> = Vec::new();
1612 for job in jobs {
1613 let Some(env) = deploys_to(run, job) else { continue };
1614 let conclusion = if cancelled && job.conclusion.as_deref() != Some("skipped") && job.started_at.is_some() {
1615 Some("cancelled".to_owned())
1616 } else if job.started_at.is_none() {
1617 Some("skipped".to_owned())
1618 } else {
1619 job.conclusion.clone()
1620 };
1621 match seen.iter_mut().find(|(known, _)| known.name.eq_ignore_ascii_case(&env.name)) {
1622 Some((known, conclusions)) => {
1623 if known.url.is_none() {
1624 known.url = env.url.clone();
1625 }
1626 conclusions.push(conclusion);
1627 }
1628 None => seen.push((env, vec![conclusion])),
1629 }
1630 }
1631 for (env, conclusions) in seen {
1632 if let Some(state) = deployment_outcome(&conclusions) {
1633 self.report_deployment(run, &env, state, true).await;
1634 }
1635 }
1636 }
1637
1638 /// Tells the pull request (or commit) how the run went, as a status.
1639 async fn report_status(&self, run: &RunRow, conclusion: &str) -> Result<()> {
1640 let state = match conclusion {
1641 "success" | "skipped" => "success",
1642 "cancelled" => "error",
1643 _ => "failure",
1644 };
1645 let _: Result<Value> = g1t_kit::call(
1646 &self.work,
1647 "set_commit_status",
1648 &json!({
1649 "repoId": run.repo_id,
1650 "sha": run.sha,
1651 "context": format!("{} / {}", run.name, run.event),
1652 "state": state,
1653 "description": format!("{} {}", run.name, match conclusion {
1654 "success" => "passed",
1655 "skipped" => "was skipped",
1656 "cancelled" => "was cancelled",
1657 _ => "failed",
1658 }),
1659 "targetUrl": format!("{SITE}/{}/actions/runs/{}", run.repo, run.id),
1660 "source": "actions",
1661 }),
1662 )
1663 .await;
1664 Ok(())
1665 }
1666
1667 /// Tells the pull request a run has started on its head.
1668 pub async fn report_pending(&self, run: &RunRow) -> Result<()> {
1669 let _: Result<Value> = g1t_kit::call(
1670 &self.work,
1671 "set_commit_status",
1672 &json!({
1673 "repoId": run.repo_id,
1674 "sha": run.sha,
1675 "context": format!("{} / {}", run.name, run.event),
1676 "state": "pending",
1677 "description": if run.status == "action_required" {
1678 format!("{} is waiting for approval", run.name)
1679 } else {
1680 format!("{} is running", run.name)
1681 },
1682 "targetUrl": format!("{SITE}/{}/actions/runs/{}", run.repo, run.id),
1683 "source": "actions",
1684 }),
1685 )
1686 .await;
1687 Ok(())
1688 }
1689
1690 /// Cancels a run: its waiting and queued jobs at once, and its running
1691 /// ones gracefully (`stop_job`), or outright when `force`.
1692 pub async fn cancel_run(&self, run: &RunRow, reason: &str, force: bool) -> Result<()> {
1693 self.db
1694 .prepare("UPDATE runs SET conclusion = 'cancelled' WHERE id = ? AND status != 'completed'")
1695 .bind(&[run.id.as_str().into()])?
1696 .run()
1697 .await?;
1698 for job in self.job_rows(&run.id).await?.iter().filter(|job| job.status != "completed") {
1699 if force {
1700 self.hard_stop(job, reason).await?;
1701 } else {
1702 self.stop_job(job, reason).await?;
1703 }
1704 }
1705 if run.status == "pending" || run.status == "action_required" {
1706 self.db.prepare("UPDATE runs SET status = 'queued' WHERE id = ?").bind(&[run.id.as_str().into()])?.run().await?;
1707 }
1708 self.advance(&run.id).await
1709 }
1710
1711 /// Cancels every run of the repository that has not finished, for
1712 /// `repo.deleted` and `repo.archived`.
1713 pub async fn stop_runs(&self, repo_id: &str) -> Result<()> {
1714 let runs = self
1715 .db
1716 .prepare("SELECT * FROM runs WHERE repo_id = ? AND status != 'completed'")
1717 .bind(&[repo_id.into()])?
1718 .all()
1719 .await?
1720 .results::<RunRow>()?;
1721 for run in runs {
1722 self.cancel_run(&run, "The repository was archived or deleted.", true).await?;
1723 }
1724 Ok(())
1725 }
1726
1727 pub async fn cancel(&self, a: RunActionArgs) -> Result<Outcome<WorkflowRun>> {
1728 if let Outcome::Fail(refused) = self.may(&a.actor, &a.repo, Capability::Run).await? {
1729 return Ok(Outcome::Fail(refused));
1730 }
1731 let run = check!(self.run_in(&a.repo, &a.id).await?);
1732 if run.status == "completed" {
1733 return Ok(fail(FailureCode::Conflict, "The run has already finished."));
1734 }
1735 // Cancelling a run that is already cancelling stops its jobs
1736 // outright, without waiting for their cleanup steps.
1737 let force = a.force || run.conclusion.as_deref() == Some("cancelled");
1738 let reason = if force {
1739 format!("{} stopped the run without waiting for its cleanup steps.", a.actor.username)
1740 } else {
1741 format!("{} cancelled the run.", a.actor.username)
1742 };
1743 self.cancel_run(&run, &reason, force).await?;
1744 self.run_summary(&run.id).await
1745 }
1746
1747 /// Runs again, as a new attempt: every job, with `failed_only` those
1748 /// that did not succeed, or with `job` that one; each with the jobs that
1749 /// need them. The attempt that ends is kept, its jobs and their logs and
1750 /// summaries with it (`job_attempts`, `run_attempts`).
1751 pub async fn rerun(&self, a: RunActionArgs) -> Result<Outcome<WorkflowRun>> {
1752 if let Outcome::Fail(refused) = self.may(&a.actor, &a.repo, Capability::Run).await? {
1753 return Ok(Outcome::Fail(refused));
1754 }
1755 // A job alone (`POST …/jobs/{job}/rerun`) names its run.
1756 let run_id = match (&a.job, a.id.is_empty()) {
1757 (Some(job), true) => {
1758 #[derive(Deserialize)]
1759 struct Of {
1760 run_id: String,
1761 }
1762 let of = self.db.prepare("SELECT run_id FROM jobs WHERE id = ?").bind(&[job.as_str().into()])?.first::<Of>(None).await?;
1763 match of {
1764 Some(of) => of.run_id,
1765 None => return Ok(fail(FailureCode::NotFound, "No such job.")),
1766 }
1767 }
1768 _ => a.id.clone(),
1769 };
1770 let run = check!(self.run_in(&a.repo, &run_id).await?);
1771 if run.status != "completed" {
1772 return Ok(fail(FailureCode::Conflict, "The run is still going: cancel it first."));
1773 }
1774 // Nothing starts again on an archived repository.
1775 match self.visible_repo(&a.repo, &Some(a.actor.clone())).await? {
1776 Some(repo) if repo.archived() => {
1777 return Ok(fail(FailureCode::Forbidden, g1t_contracts::repos::archived_message(&repo.namespace, &repo.name)));
1778 }
1779 Some(_) => {}
1780 None => return Ok(fail(FailureCode::NotFound, "There is no such repository.")),
1781 }
1782 if run.error.is_some() {
1783 return Ok(fail(FailureCode::Conflict, "This run never started: fix the workflow file and push again."));
1784 }
1785 let jobs = self.job_rows(&run.id).await?;
1786 let workflow = workflow::parse(&run.source).ok();
1787 let target = match &a.job {
1788 Some(id) => match jobs.iter().find(|job| &job.id == id) {
1789 Some(job) => Some(top_key(&job.key).to_owned()),
1790 None => return Ok(fail(FailureCode::NotFound, "That job is not in the run's latest attempt.")),
1791 },
1792 None => None,
1793 };
1794 let which = match (&target, a.failed_only) {
1795 (Some(key), _) => Rerun::Job(key),
1796 (None, true) => Rerun::Failed,
1797 (None, false) => Rerun::All,
1798 };
1799 let order = workflow.as_ref().map(|w| w.job_order()).unwrap_or_default();
1800 let again = rerun_keys(
1801 &order,
1802 |key| jobs.iter().find(|j| j.key == key).map(JobRow::needs).unwrap_or_default(),
1803 |key| jobs.iter().filter(|j| j.key == key).all(|j| j.conclusion.as_deref() == Some("success")),
1804 which,
1805 );
1806 if again.is_empty() {
1807 return Ok(fail(FailureCode::Conflict, "Every job succeeded: there is nothing to run again."));
1808 }
1809 // The jobs that run again, a called workflow's with the job calling it.
1810 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();
1811 let ids = serde_json::to_string(&rerun_ids)?;
1812 let ended = run.attempt.to_string();
1813 let ended = ended.as_str();
1814 let mut statements = vec![
1815 // The attempt that ends, as it ended.
1816 self.db
1817 .prepare(
1818 "INSERT OR REPLACE INTO run_attempts (run_id, attempt, repo_id, conclusion, actor, debug, started_at, finished_at)
1819 SELECT id, attempt, repo_id, conclusion, COALESCE(triggering_actor, actor), debug, started_at, finished_at FROM runs WHERE id = ?",
1820 )
1821 .bind(&[run.id.as_str().into()])?,
1822 // Earlier attempts that showed a job's logs from where it ran
1823 // then now find them where they move to.
1824 self.db
1825 .prepare("UPDATE job_attempts SET log_id = log_id || '.' || ?1 WHERE run_id = ?2 AND log_id IN (SELECT value FROM json_each(?3))")
1826 .bind(&[ended.into(), run.id.as_str().into(), ids.as_str().into()])?,
1827 // Each of its jobs: one that runs again keeps its logs under
1828 // `{id}.{attempt}`; one left alone is still the live job's.
1829 self.db
1830 .prepare(
1831 "INSERT OR REPLACE INTO job_attempts (id, run_id, repo_id, attempt, job_id, log_id, key, ordinal, name, needs, status, conclusion,
1832 steps, annotations, reason, environment, labels, runner_name, started_at, finished_at)
1833 SELECT id || '.' || ?1, run_id, repo_id, ?1, id,
1834 CASE WHEN id IN (SELECT value FROM json_each(?3)) THEN id || '.' || ?1 ELSE id END,
1835 key, ordinal, name, needs, status, conclusion, steps, annotations, reason, environment, labels, runner_name, started_at, finished_at
1836 FROM jobs WHERE run_id = ?2 ORDER BY rowid",
1837 )
1838 .bind(&[ended.into(), run.id.as_str().into(), ids.as_str().into()])?,
1839 self.db
1840 .prepare("UPDATE logs SET job_id = job_id || '.' || ?1 WHERE job_id IN (SELECT value FROM json_each(?2))")
1841 .bind(&[ended.into(), ids.as_str().into()])?,
1842 self.db
1843 .prepare("UPDATE job_summaries SET job_id = job_id || '.' || ?1 WHERE job_id IN (SELECT value FROM json_each(?2))")
1844 .bind(&[ended.into(), ids.as_str().into()])?,
1845 ];
1846 for key in &again {
1847 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()])?);
1848 // The jobs of a workflow it called are made again when it calls it again.
1849 statements.push(
1850 self.db
1851 .prepare("DELETE FROM jobs WHERE run_id = ? AND key LIKE ?")
1852 .bind(&[run.id.as_str().into(), format!("{key}/%").into()])?,
1853 );
1854 statements.push(
1855 self.db
1856 .prepare(
1857 "UPDATE jobs SET status = 'waiting', conclusion = NULL, steps = '[]', annotations = '[]', outputs = '{}', reason = NULL,
1858 matrix = NULL, call = NULL, token_hash = NULL, seen_at = NULL, started_at = NULL, finished_at = NULL,
1859 labels = NULL, queued_at = NULL, runner_id = NULL, runner_name = NULL, environment = NULL,
1860 concurrency_group = NULL, cancel_in_progress = 0, cancel_requested_at = NULL WHERE run_id = ? AND key = ?",
1861 )
1862 .bind(&[run.id.as_str().into(), key.as_str().into()])?,
1863 );
1864 }
1865 statements.push(
1866 self.db
1867 .prepare(
1868 "UPDATE runs SET status = 'queued', conclusion = NULL, attempt = attempt + 1, started_at = NULL, finished_at = NULL,
1869 triggering_actor = ?, debug = ? WHERE id = ?",
1870 )
1871 .bind(&[a.actor.username.as_str().into(), u32::from(a.debug).into(), run.id.as_str().into()])?,
1872 );
1873 self.db.batch(statements).await?;
1874 if let Some(run) = self.run_row(&run.id).await? {
1875 self.report_pending(&run).await?;
1876 }
1877 self.advance(&run.id).await?;
1878 self.run_summary(&run.id).await
1879 }
1880
1881 pub async fn run_in(&self, repo: &RepoPath, id: &str) -> Result<Outcome<RunRow>> {
1882 let row = self
1883 .db
1884 .prepare("SELECT * FROM runs WHERE id = ? AND lower(repo) = lower(?)")
1885 .bind(&[id.into(), format!("{}/{}", repo.namespace, repo.name).into()])?
1886 .first::<RunRow>(None)
1887 .await?;
1888 Ok(row.map_or_else(|| fail(FailureCode::NotFound, "No such run."), Outcome::Ok))
1889 }
1890
1891 // --- The sandbox's side -----------------------------------------------------
1892
1893 pub(crate) async fn job_for_token(&self, a: &JobCallArgs) -> Result<Outcome<JobRow>> {
1894 let job = self.db.prepare("SELECT * FROM jobs WHERE id = ?").bind(&[a.job.as_str().into()])?.first::<JobRow>(None).await?;
1895 Ok(match job {
1896 Some(job) if job.status == "in_progress" && job.token_hash.as_deref().is_some_and(|hash| same(hash, &sha256_hex(&a.token))) => {
1897 Outcome::Ok(job)
1898 }
1899 _ => fail(FailureCode::Unauthenticated, "That job is not running, or the token is not its."),
1900 })
1901 }
1902
1903 /// `job_auth`: which run and repository a running job's token is for,
1904 /// so the API can keep its artifacts and cache.
1905 pub async fn job_auth(&self, a: JobCallArgs) -> Result<Outcome<Value>> {
1906 let job = check!(self.job_for_token(&a).await?);
1907 Ok(Outcome::Ok(json!({ "run": job.run_id, "repoId": job.repo_id })))
1908 }
1909
1910 /// `job_spec`: everything the sandbox needs to run the job.
1911 pub async fn job_spec(&self, a: JobCallArgs) -> Result<Outcome<Value>> {
1912 let job = check!(self.job_for_token(&a).await?);
1913 let Some(run) = self.run_row(&job.run_id).await? else {
1914 return Ok(fail(FailureCode::NotFound, "No such run."));
1915 };
1916 let Ok(caller) = workflow::parse(&run.source) else {
1917 return Ok(fail(FailureCode::Invalid, "The workflow no longer reads."));
1918 };
1919 // A called workflow's job runs as that workflow defines it.
1920 let callee = job.callee();
1921 let (workflow, spec, call_inputs) = match callee {
1922 Some((called, spec, call)) => (called, spec, Some(call["inputs"].clone())),
1923 None => match caller.jobs.iter().find(|j| j.id == job.key) {
1924 Some(spec) => (caller.clone(), spec.clone(), None),
1925 None => return Ok(fail(FailureCode::NotFound, "The job is not in the workflow.")),
1926 },
1927 };
1928 let spec = &spec;
1929 let repo = repo_path(&run.repo);
1930 let trusted = run.trusted != 0;
1931 // The job's `environment:`, by name, as read when its needs were done
1932 // (an expression included), once the environment's protection rules
1933 // let it start: entries with a value for it give that value instead
1934 // of their default, as GitHub's environment secrets do.
1935 let environment: Option<String> = job.environment.clone();
1936 // What its token may do: its `permissions:` (a called workflow's
1937 // jobs no more than the job that calls it), else the repository's
1938 // default; read-only for a pull request from outside.
1939 // The repository's default, its workspace's taken in, and whether
1940 // its jobs may open and approve pull requests.
1941 let (default, pull_requests) = self.token_policy(&run.repo_id).await?;
1942 let mut permissions = spec.permissions(&workflow, default);
1943 if let Some(parent) = &job.call().filter(|c| c["role"] == "callee").and_then(|c| c["parent"].as_str().map(str::to_owned)) {
1944 let top = parent.split('/').next().unwrap_or(parent);
1945 if let Some(caller_job) = caller.jobs.iter().find(|j| j.id == top) {
1946 permissions = permissions.capped_by(&caller_job.permissions(&caller, default));
1947 }
1948 }
1949 if !trusted {
1950 permissions = permissions.read_only();
1951 }
1952 // G1T_TOKEN, and GITHUB_TOKEN as its alias: a token of the
1953 // workspace's that reaches this repository only, with the scopes
1954 // its permissions give, until the job ends.
1955 let token = match self.workspace_actor(&repo.namespace).await? {
1956 Some(workspace) => {
1957 let created: CreatedAccessToken = g1t_kit::call(
1958 &self.identity,
1959 "create_job_token",
1960 &CreateJobTokenArgs {
1961 workspace,
1962 repo: repo.clone(),
1963 run_id: run.id.clone(),
1964 job_id: job.id.clone(),
1965 name: format!("G1T_TOKEN for {} run {}", run.repo, run.number),
1966 ttl_seconds: u64::from(job.timeout_minutes) * 60 + 600,
1967 scopes: permissions.scopes().into_iter().map(str::to_owned).collect(),
1968 pull_requests: pull_requests && trusted,
1969 },
1970 )
1971 .await?;
1972 created.token
1973 }
1974 None => String::new(),
1975 };
1976 // A run that is not trusted (a pull request from outside the
1977 // workspace) gets no secrets and an empty token.
1978 let passed = job.call().filter(|c| c["role"] == "callee").and_then(|c| c.get("secrets").cloned());
1979 let mut secrets = match (trusted, passed) {
1980 (false, _) => Map::new(),
1981 (true, None) => self.secrets_for(&run.repo_id, &run.repo, environment.as_deref(), true).await?,
1982 // A called workflow's job: what its callers passed it (reach.rs),
1983 // and its own environment's secrets over them.
1984 (true, Some(plan)) => {
1985 let base = self.secrets_for(&run.repo_id, &run.repo, None, true).await?;
1986 let vars = self.variables_for(&run.repo_id, &run.repo, None, true).await?;
1987 let github = run.info().context(&job.key, "", run.action.as_deref());
1988 let mut passed = crate::reach::resolve_secrets(&plan, &base, &github, &vars);
1989 if let Some(name) = environment.as_deref() {
1990 let own = self.secrets_for(&run.repo_id, &run.repo, Some(name), true).await?;
1991 for (key, value) in own {
1992 if base.get(&key) != Some(&value) {
1993 passed.insert(key, value);
1994 }
1995 }
1996 }
1997 passed
1998 }
1999 };
2000 secrets.insert("G1T_TOKEN".into(), Value::String(token.clone()));
2001 secrets.insert("GITHUB_TOKEN".into(), Value::String(token.clone()));
2002 // Each secret as it is, a line at a time, base64 and JSON-escaped.
2003 let mut masks: Vec<String> = g1t_actions::mask::all_variants(secrets.values().filter_map(|v| v.as_str()));
2004 let vars = self.variables_for(&run.repo_id, &run.repo, environment.as_deref(), trusted).await?;
2005 // The toolkit's runtime token (runtime.rs), for as long as the job
2006 // may run; the API puts it and the toolkit's addresses in the
2007 // job's variables.
2008 let runtime_token = crate::runtime::runtime_token(
2009 &job.id,
2010 &job.run_id,
2011 job.token_hash.as_deref().unwrap_or_default(),
2012 now_ms() / 1000,
2013 u64::from(job.timeout_minutes) * 60 + 600,
2014 );
2015 masks.push(runtime_token.clone());
2016 let retention_days = self.retention_setting(&run.repo_id).await?;
2017
2018 let jobs = self.job_rows(&run.id).await?;
2019 let mut needs = Map::new();
2020 // In a called workflow, its jobs' keys sit under the job that called it.
2021 let parent = job.call().filter(|c| c["role"] == "callee").and_then(|c| c["parent"].as_str().map(str::to_owned));
2022 for need in &spec.needs {
2023 let key = match &parent {
2024 Some(parent) => format!("{parent}/{need}"),
2025 None => need.clone(),
2026 };
2027 let rows: Vec<&JobRow> = jobs.iter().filter(|row| row.key == key).collect();
2028 let mut outputs = Map::new();
2029 for row in &rows {
2030 if let Ok(Value::Object(more)) = serde_json::from_str::<Value>(&row.outputs) {
2031 outputs.extend(more);
2032 }
2033 }
2034 needs.insert(need.clone(), json!({ "result": key_result(&rows), "outputs": outputs }));
2035 }
2036 let siblings = jobs.iter().filter(|row| row.key == job.key).count();
2037 let matrix: Value = job.matrix.as_deref().and_then(|m| serde_json::from_str(m).ok()).unwrap_or(json!({}));
2038 let info = run.info();
2039 let mut github = info.context(&job.key, &token, run.action.as_deref());
2040 github["token"] = json!(token);
2041 github["retention_days"] = json!(retention_days);
2042 // On a self-hosted runner, `runner` and `RUNNER_*` describe that
2043 // machine rather than g1t's sandbox.
2044 let mut variables = info.variables(&job.key);
2045 variables.insert("GITHUB_RETENTION_DAYS".into(), json!(retention_days.to_string()));
2046 let mut runner = match &job.runner_id {
2047 Some(id) => self.runner_context_for(id, &mut variables).await?,
2048 None => runner_context(),
2049 };
2050 // A re-run with debug logging: what GitHub sets for one.
2051 if run.debug != 0 {
2052 debug_logging(&mut variables, &mut runner);
2053 }
2054
2055 // Where to check out: a pull request's fork, or the repository.
2056 let clone_url = match run.pull {
2057 Some(number) if run.event.starts_with("pull_request") && run.event != "pull_request_target" => {
2058 let located: Outcome<g1t_contracts::work::PullDetail> = g1t_kit::call(
2059 &self.work,
2060 "get_pull",
2061 &g1t_contracts::work::ViewArgs {
2062 repo: repo.clone(),
2063 number,
2064 viewer: self.workspace_actor(&repo.namespace).await?,
2065 after_seq: 0,
2066 },
2067 )
2068 .await?;
2069 match located {
2070 Outcome::Ok(detail) => match detail.pull.fork {
2071 Some(fork) => format!("{SITE}/{}/{}.git", fork.namespace, fork.name),
2072 None => format!("{SITE}/{}.git", run.repo),
2073 },
2074 Outcome::Fail(_) => format!("{SITE}/{}.git", run.repo),
2075 }
2076 }
2077 _ => format!("{SITE}/{}.git", run.repo),
2078 };
2079
2080 Ok(Outcome::Ok(json!({
2081 "job": job.id,
2082 "run": run.id,
2083 "key": job.key,
2084 "name": job.name,
2085 "spec": spec.raw,
2086 "workflow": {
2087 "env": workflow.env,
2088 "defaults": workflow.raw.get("defaults").cloned().unwrap_or(Value::Null),
2089 },
2090 "github": github,
2091 "variables": variables,
2092 "event": info.event,
2093 "contexts": {
2094 "vars": vars,
2095 "secrets": secrets,
2096 "inputs": call_inputs.unwrap_or_else(|| Value::Object(run.inputs())),
2097 "matrix": matrix,
2098 "needs": needs,
2099 "strategy": {
2100 "fail-fast": spec.fail_fast,
2101 "job-index": job.ordinal,
2102 "job-total": siblings,
2103 "max-parallel": spec.max_parallel.unwrap_or(siblings as u32),
2104 },
2105 "runner": runner,
2106 },
2107 "checkout": {
2108 "repository": run.repo,
2109 "url": clone_url,
2110 "sha": run.sha,
2111 "ref": run.git_ref,
2112 "token": token,
2113 },
2114 "timeoutMinutes": job.timeout_minutes,
2115 "masks": masks,
2116 // As the job's log lists them at its start.
2117 "permissions": permissions.listed().into_iter().map(|(name, access)| (name.to_owned(), json!(access.as_str()))).collect::<Map<String, Value>>(),
2118 // Whether the job may ask for an OIDC token decides whether it
2119 // is told where to.
2120 "runtime": {
2121 "token": runtime_token,
2122 "idToken": self.oidc_allowed(&run, &job),
2123 },
2124 })))
2125 }
2126
2127 /// `job_report`: the sandbox telling how the job is going.
2128 pub async fn job_report(&self, a: JobCallArgs) -> Result<Outcome<Value>> {
2129 let job = check!(self.job_for_token(&a).await?);
2130 let report = &a.report;
2131 let at = now();
2132 match report["kind"].as_str().unwrap_or_default() {
2133 "steps" => {
2134 // The list can grow as the job goes (post steps), so steps
2135 // already reported keep where they stand.
2136 let known: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
2137 let steps: Vec<Value> = report["steps"]
2138 .as_array()
2139 .map(|names| {
2140 names
2141 .iter()
2142 .enumerate()
2143 .map(|(i, name)| match known.get(i) {
2144 Some(step) if step["status"] != "queued" => step.clone(),
2145 _ => json!({ "number": i + 1, "name": expr::to_text(name), "status": "queued", "conclusion": null, "startedAt": null, "finishedAt": null }),
2146 })
2147 .collect()
2148 })
2149 .unwrap_or_default();
2150 self.db
2151 .prepare("UPDATE jobs SET steps = ?, seen_at = ? WHERE id = ?")
2152 .bind(&[serde_json::to_string(&steps)?.into(), at.as_str().into(), job.id.as_str().into()])?
2153 .run()
2154 .await?;
2155 }
2156 "step" => {
2157 let number = report["number"].as_u64().unwrap_or(0) as usize;
2158 let mut steps: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
2159 if let Some(step) = number.checked_sub(1).and_then(|i| steps.get_mut(i)) {
2160 let status = report["status"].as_str().unwrap_or("in_progress");
2161 step["status"] = json!(status);
2162 if status == "in_progress" {
2163 step["startedAt"] = json!(at);
2164 }
2165 if status == "completed" {
2166 step["finishedAt"] = json!(at);
2167 step["conclusion"] = report["conclusion"].clone();
2168 }
2169 if let Some(name) = report["name"].as_str() {
2170 step["name"] = json!(name);
2171 }
2172 }
2173 self.db
2174 .prepare("UPDATE jobs SET steps = ?, seen_at = ? WHERE id = ?")
2175 .bind(&[serde_json::to_string(&steps)?.into(), at.as_str().into(), job.id.as_str().into()])?
2176 .run()
2177 .await?;
2178 }
2179 "log" => {
2180 let mut text = report["text"].as_str().unwrap_or_default().to_owned();
2181 if text.len() > MAX_CHUNK_BYTES {
2182 let mut cut = MAX_CHUNK_BYTES;
2183 while !text.is_char_boundary(cut) {
2184 cut -= 1;
2185 }
2186 text.truncate(cut);
2187 }
2188 #[derive(Deserialize)]
2189 struct Size {
2190 n: Option<f64>,
2191 seq: Option<f64>,
2192 }
2193 let size = self
2194 .db
2195 .prepare("SELECT SUM(LENGTH(text)) AS n, MAX(seq) AS seq FROM logs WHERE job_id = ?")
2196 .bind(&[job.id.as_str().into()])?
2197 .first::<Size>(None)
2198 .await?;
2199 let (used, seq) = size.map_or((0, 0.0), |s| (s.n.unwrap_or(0.0) as usize, s.seq.unwrap_or(0.0)));
2200 if used < MAX_LOG_BYTES {
2201 if used + text.len() >= MAX_LOG_BYTES {
2202 text.push_str("\n… The log reached its limit of 4 MB; the rest is not kept.\n");
2203 }
2204 self.db
2205 .prepare("INSERT INTO logs (job_id, seq, step, text) VALUES (?, ?, ?, ?)")
2206 .bind(&[job.id.as_str().into(), // Numbers go to D1 as f64: a u64 would be a BigInt, which it refuses.
2207 (seq + 1.0).into(), (report["step"].as_u64().unwrap_or(0) as u32).into(), text.into()])?
2208 .run()
2209 .await?;
2210 }
2211 self.db.prepare("UPDATE jobs SET seen_at = ? WHERE id = ?").bind(&[at.into(), job.id.as_str().into()])?.run().await?;
2212 }
2213 "summary" => {
2214 // `$GITHUB_STEP_SUMMARY`, masked by the runner: added to the
2215 // step's summary, up to 1 MiB a step and 20 steps a job.
2216 let step = report["step"].as_u64().unwrap_or(0) as u32;
2217 let markdown = report["markdown"].as_str().unwrap_or_default();
2218 #[derive(Deserialize)]
2219 struct Held {
2220 steps: u32,
2221 mine: Option<f64>,
2222 }
2223 let held = self
2224 .db
2225 .prepare("SELECT COUNT(*) AS steps, MAX(CASE WHEN step = ? THEN LENGTH(markdown) END) AS mine FROM job_summaries WHERE job_id = ?")
2226 .bind(&[step.into(), job.id.as_str().into()])?
2227 .first::<Held>(None)
2228 .await?;
2229 let (steps, mine) = held.map_or((0, None), |held| (held.steps, held.mine.map(|n| n as usize)));
2230 if summary_fits(steps, mine, markdown.len()) {
2231 self.db
2232 .prepare(
2233 "INSERT INTO job_summaries (job_id, step, markdown) VALUES (?, ?, ?)
2234 ON CONFLICT (job_id, step) DO UPDATE SET markdown = job_summaries.markdown || excluded.markdown",
2235 )
2236 .bind(&[job.id.as_str().into(), step.into(), markdown.into()])?
2237 .run()
2238 .await?;
2239 }
2240 self.db.prepare("UPDATE jobs SET seen_at = ? WHERE id = ?").bind(&[at.into(), job.id.as_str().into()])?.run().await?;
2241 }
2242 "annotation" => {
2243 let mut annotations: Vec<Value> = serde_json::from_str(&job.annotations).unwrap_or_default();
2244 if annotations.len() < MAX_ANNOTATIONS {
2245 annotations.push(json!({
2246 "level": report["level"].as_str().unwrap_or("notice"),
2247 "message": report["message"].as_str().unwrap_or_default().chars().take(4000).collect::<String>(),
2248 "title": report["title"],
2249 "file": report["file"],
2250 "line": report["line"],
2251 }));
2252 self.db
2253 .prepare("UPDATE jobs SET annotations = ?, seen_at = ? WHERE id = ?")
2254 .bind(&[serde_json::to_string(&annotations)?.into(), at.as_str().into(), job.id.as_str().into()])?
2255 .run()
2256 .await?;
2257 }
2258 }
2259 // Nothing to tell; the answer says whether to stop.
2260 "ping" => {
2261 self.db.prepare("UPDATE jobs SET seen_at = ? WHERE id = ?").bind(&[at.into(), job.id.as_str().into()])?.run().await?;
2262 }
2263 "done" => {
2264 // A job told to stop ends cancelled, however its cleanup went.
2265 let conclusion = if job.cancel_requested_at.is_some() {
2266 "cancelled"
2267 } else {
2268 report["conclusion"]
2269 .as_str()
2270 .filter(|c| matches!(*c, "success" | "failure" | "cancelled"))
2271 .unwrap_or("failure")
2272 };
2273 let outputs = report["outputs"].as_object().cloned();
2274 Box::pin(self.finish_job(&job.id, conclusion, report["reason"].as_str(), outputs.as_ref())).await?;
2275 }
2276 other => return Ok(fail(FailureCode::Invalid, format!("There is no report called `{other}`."))),
2277 }
2278 // `cancelled`: the run was cancelled, and the runner should stop
2279 // the step it is on and run only its cleanup steps.
2280 Ok(Outcome::Ok(json!({ "ok": true, "cancelled": job.cancel_requested_at.is_some() })))
2281 }
2282
2283 // --- Every minute ---------------------------------------------------------------
2284
2285 pub async fn on_minute(&self, now_ms: u64) -> Result<()> {
2286 let minute = now_ms / 60_000 * 60_000;
2287 // Staff (or billing's usage watcher) paused scheduled runs across
2288 // g1t: this minute's schedules are skipped, not queued for later.
2289 // Kept 30 seconds in the isolate (g1t_kit::pause).
2290 if g1t_kit::pause::paused(&self.billing, g1t_contracts::billing::PauseLevel::Schedules).await {
2291 worker::console_log!("actions: schedules are paused across g1t; skipped this minute's");
2292 } else if let Err(error) = self.run_schedules(minute).await {
2293 worker::console_error!("actions: schedules failed: {error}");
2294 }
2295 // Jobs whose sandbox went quiet or ran past their time.
2296 let running = self.db.prepare("SELECT * FROM jobs WHERE status = 'in_progress'").all().await?.results::<JobRow>()?;
2297 for job in running {
2298 // Times in g1t's format compare as text.
2299 let before = |ms: u64| rfc3339(now_ms.saturating_sub(ms));
2300 let silent = job.seen_at.as_deref().is_some_and(|seen| seen < before(SILENT_MS).as_str());
2301 let limit = (u64::from(job.timeout_minutes) * 60 + 120) * 1000;
2302 let over = job.started_at.as_deref().is_some_and(|started| started < before(limit).as_str());
2303 let cancel_overdue = job.cancel_requested_at.as_deref().is_some_and(|at| at < before(CANCEL_GRACE_MS).as_str());
2304 if cancel_overdue {
2305 // Cancelled, and still going after its grace period.
2306 self.hard_stop(&job, "It was cancelled, and did not finish its cleanup steps within 5 minutes.").await?;
2307 self.advance(&job.run_id).await?;
2308 } else if over {
2309 let reason = format!("It ran longer than its time limit of {} minutes.", job.timeout_minutes);
2310 // A self-hosted runner is told to stop on its next poll.
2311 if job.runner_id.is_none() {
2312 let _: Result<Value> = g1t_kit::call(&self.runner, "stop_actions_job", &json!({ "job": job.id })).await;
2313 }
2314 self.finish_job(&job.id, "failure", Some(&reason), None).await?;
2315 } else if silent {
2316 let reason = match &job.runner_name {
2317 Some(name) => format!("The self-hosted runner {name} stopped answering."),
2318 None => "The runner stopped answering.".to_owned(),
2319 };
2320 self.finish_job(&job.id, "failure", Some(&reason), None).await?;
2321 }
2322 }
2323 if let Err(error) = self.sweep_runners(now_ms).await {
2324 worker::console_error!("actions: the runners' sweep failed: {error}");
2325 }
2326 // Jobs held at an environment whose wait timer has run out.
2327 if let Err(error) = self.release_gates().await {
2328 worker::console_error!("actions: environments' gates failed: {error}");
2329 }
2330 // Once an hour: the cache's expired entries, and its storage.
2331 if (now_ms / 60_000) % 60 == 7
2332 && let Err(error) = self.sweep_cache(now_ms).await
2333 {
2334 worker::console_error!("actions: the cache's sweep failed: {error}");
2335 }
2336 // And artifacts past their time, and the toolkit's abandoned parts.
2337 if (now_ms / 60_000) % 60 == 37 {
2338 if let Err(error) = self.sweep_artifacts(now_ms).await {
2339 worker::console_error!("actions: the artifacts' sweep failed: {error}");
2340 }
2341 if let Err(error) = self.sweep_blob_parts(now_ms).await {
2342 worker::console_error!("actions: the blob parts' sweep failed: {error}");
2343 }
2344 }
2345 self.start_queued().await
2346 }
2347}
2348
2349
2350#[cfg(test)]
2351mod stopping {
2352 use super::stops_runs;
2353 use g1t_contracts::events::Event;
2354 use serde_json::{Value, json};
2355
2356 fn event(kind: &str, data: Value) -> Event {
2357 Event {
2358 id: "evt_1".into(),
2359 kind: kind.into(),
2360 source: "repos".into(),
2361 time: "2026-10-05T00:00:00Z".into(),
2362 repo_id: Some("rep_1".into()),
2363 actor: None,
2364 data,
2365 }
2366 }
2367
2368 #[test]
2369 fn deleting_or_archiving_stops_runs() {
2370 assert_eq!(stops_runs(&event("repo.deleted", json!({ "repoId": "rep_1" }))).as_deref(), Some("rep_1"));
2371 assert_eq!(stops_runs(&event("repo.archived", json!({ "archived": true }))).as_deref(), Some("rep_1"));
2372 assert_eq!(stops_runs(&event("repo.unarchived", json!({ "archived": false }))), None);
2373 assert_eq!(stops_runs(&event("repo.restored", json!({}))), None);
2374 assert_eq!(stops_runs(&event("git.push", json!({}))), None);
2375 }
2376}
2377
2378#[cfg(test)]
2379mod status_of_needs {
2380 use std::collections::HashMap;
2381
2382 use super::ancestor_failed;
2383
2384 /// check -> plan -> (migrate) -> core -> edge, as deploy.yml has them,
2385 /// and a job that needs only the last.
2386 fn graph() -> HashMap<&'static str, Vec<&'static str>> {
2387 HashMap::from([
2388 ("check", vec![]),
2389 ("plan", vec!["check"]),
2390 ("migrate", vec!["plan"]),
2391 ("core", vec!["plan", "migrate"]),
2392 ("edge", vec!["plan", "migrate", "core"]),
2393 ("notify", vec!["edge"]),
2394 ])
2395 }
2396
2397 #[test]
2398 fn a_failure_is_seen_however_far_back() {
2399 let needs = graph();
2400 let failed = |which: &'static str| move |key: &str| key == which;
2401 // check failed; plan, and everything after, was skipped for it.
2402 assert!(ancestor_failed(&needs, "notify", failed("check")));
2403 assert!(ancestor_failed(&needs, "core", failed("check")));
2404 assert!(ancestor_failed(&needs, "edge", failed("core")));
2405 // Nothing before a job failed: a skipped migrate is not a failure.
2406 assert!(!ancestor_failed(&needs, "edge", |_| false));
2407 assert!(!ancestor_failed(&needs, "core", failed("edge")));
2408 assert!(!ancestor_failed(&needs, "check", failed("check")));
2409 }
2410
2411 #[test]
2412 fn cycles_and_unknown_keys_end() {
2413 let needs = HashMap::from([("a", vec!["b"]), ("b", vec!["a"])]);
2414 assert!(!ancestor_failed(&needs, "a", |_| false));
2415 assert!(!ancestor_failed(&needs, "missing", |_| true));
2416 }
2417}
2418
2419#[cfg(test)]
2420mod deployments {
2421 use serde_json::{Map, Value, json};
2422
2423 use super::{JobEnvironment, deployment_outcome, environment_of};
2424
2425 #[test]
2426 fn a_jobs_environment_is_read_for_deployments() {
2427 let contexts: Map<String, Value> = serde_json::from_value(json!({
2428 "github": { "ref_name": "main", "repository": "acme/web" },
2429 "inputs": { "target": "staging" },
2430 "matrix": {},
2431 }))
2432 .unwrap();
2433 let read = |raw: Value| environment_of(&raw, &contexts);
2434 assert_eq!(read(json!({})), None);
2435 assert_eq!(
2436 read(json!({ "environment": "production" })),
2437 Some(JobEnvironment { name: "production".into(), url: None, deploys: true })
2438 );
2439 assert_eq!(
2440 read(json!({ "environment": { "name": "production", "url": "https://g1t.sh" } })),
2441 Some(JobEnvironment { name: "production".into(), url: Some("https://g1t.sh".into()), deploys: true })
2442 );
2443 // Expressions are filled in from the run.
2444 assert_eq!(
2445 read(json!({ "environment": { "name": "${{ inputs.target }}", "url": "https://${{ github.ref_name }}.example.com" } })),
2446 Some(JobEnvironment { name: "staging".into(), url: Some("https://main.example.com".into()), deploys: true })
2447 );
2448 // Secrets only: no deployment.
2449 assert!(!read(json!({ "environment": { "name": "production", "deployment": false } })).unwrap().deploys);
2450 // The same, said in the job's g1t settings.
2451 assert!(!read(json!({ "environment": "production", "g1t": { "deployment": false } })).unwrap().deploys);
2452 assert!(!read(json!({ "environment": { "name": "production" }, "g1t": { "deployment": false } })).unwrap().deploys);
2453 // Only http(s) addresses.
2454 assert_eq!(read(json!({ "environment": { "name": "production", "url": "javascript:alert(1)" } })).unwrap().url, None);
2455 }
2456
2457 #[test]
2458 fn a_runs_outcome_for_an_environment() {
2459 let of = |list: &[&str]| deployment_outcome(&list.iter().map(|c| Some((*c).to_owned())).collect::<Vec<_>>());
2460 assert_eq!(of(&["success", "skipped"]), Some("success"));
2461 assert_eq!(of(&["success", "failure"]), Some("failure"));
2462 assert_eq!(of(&["success", "cancelled"]), Some("error"));
2463 assert_eq!(of(&["skipped"]), None);
2464 assert_eq!(deployment_outcome(&[None]), None);
2465 }
2466}
2467
2468#[cfg(test)]
2469mod reruns {
2470 use serde_json::{Map, Value, json};
2471
2472 use super::{MAX_SUMMARIES, MAX_SUMMARY_BYTES, Rerun, debug_logging, rerun_keys, summary_fits, top_key};
2473
2474 /// build ← test ← deploy, and lint on its own.
2475 fn keys(which: Rerun, failed: &[&str]) -> Vec<String> {
2476 let order = ["build", "lint", "test", "deploy"];
2477 let needs = |key: &str| -> Vec<String> {
2478 match key {
2479 "test" => vec!["build".into()],
2480 "deploy" => vec!["test".into()],
2481 _ => Vec::new(),
2482 }
2483 };
2484 rerun_keys(&order, needs, |key| !failed.contains(&key), which)
2485 }
2486
2487 #[test]
2488 fn a_rerun_takes_the_jobs_it_names_and_those_that_need_them() {
2489 assert_eq!(keys(Rerun::All, &[]), ["build", "lint", "test", "deploy"]);
2490 assert_eq!(keys(Rerun::Failed, &["test"]), ["test", "deploy"]);
2491 assert_eq!(keys(Rerun::Failed, &["lint"]), ["lint"]);
2492 assert!(keys(Rerun::Failed, &[]).is_empty());
2493 // One job, whatever it came to, and what depends on it.
2494 assert_eq!(keys(Rerun::Job("build"), &[]), ["build", "test", "deploy"]);
2495 assert_eq!(keys(Rerun::Job("lint"), &["test"]), ["lint"]);
2496 assert_eq!(keys(Rerun::Job("deploy"), &[]), ["deploy"]);
2497 assert!(keys(Rerun::Job("missing"), &[]).is_empty());
2498 }
2499
2500 #[test]
2501 fn a_called_workflows_jobs_run_again_with_the_job_that_calls_it() {
2502 assert_eq!(top_key("build/test"), "build");
2503 assert_eq!(top_key("build/inner/test"), "build");
2504 assert_eq!(top_key("lint"), "lint");
2505 }
2506
2507 #[test]
2508 fn a_job_keeps_twenty_steps_summaries_of_a_mebibyte_each() {
2509 assert!(summary_fits(0, None, 10));
2510 assert!(!summary_fits(0, None, 0), "nothing to keep");
2511 assert!(!summary_fits(MAX_SUMMARIES, None, 10), "a twenty-first step's summary is dropped");
2512 assert!(summary_fits(MAX_SUMMARIES, Some(10), 10), "a step that has one may add to it");
2513 assert!(summary_fits(1, Some(MAX_SUMMARY_BYTES - 10), 10));
2514 assert!(!summary_fits(1, Some(MAX_SUMMARY_BYTES - 10), 11));
2515 assert!(!summary_fits(0, None, MAX_SUMMARY_BYTES + 1));
2516 }
2517
2518 #[test]
2519 fn a_debug_rerun_sets_what_github_sets() {
2520 let mut variables = Map::new();
2521 let mut runner = json!({ "name": "g1t", "debug": "" });
2522 debug_logging(&mut variables, &mut runner);
2523 assert_eq!(variables["RUNNER_DEBUG"], "1");
2524 assert_eq!(variables["ACTIONS_STEP_DEBUG"], "true");
2525 assert_eq!(variables["ACTIONS_RUNNER_DEBUG"], "true");
2526 assert_eq!(runner["debug"], Value::String("1".into()));
2527 assert_eq!(runner["name"], "g1t");
2528 }
2529}