Skip to content

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

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