g1t/services/actions/src/plan.rs

1,212 lines53,565 bytesCodeBlame
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::actions::{JobCallArgs, RunActionArgs, StartJobArgs, WorkflowRun};
11use g1t_contracts::identity::{CreateAccessTokenArgs, CreatedAccessToken};
12use g1t_contracts::repos::{Repo, RepoPath};
13use g1t_contracts::time::rfc3339;
14use g1t_contracts::{FailureCode, Outcome, new_id};
15use g1t_kit::now_ms;
16use g1t_secrets::{random_hex, same, sha256_hex};
17use serde::Deserialize;
18use serde_json::{Map, Value, json};
19use worker::Result;
20
21use crate::sync::WorkflowRow;
22use crate::{Actions, Count, MAX_TIMEOUT_MINUTES, RUNNING_PER_WORKSPACE, SILENT_MS, SITE, check, fail, optional, repo_path};
23
24/// The most log one job keeps, in bytes; past it, the log says so and stops.
25const MAX_LOG_BYTES: usize = 4 * 1024 * 1024;
26/// The most a single log report may add.
27const MAX_CHUNK_BYTES: usize = 256 * 1024;
28const MAX_ANNOTATIONS: usize = 50;
29
30pub struct NewRun {
31 pub repo: Repo,
32 pub path: String,
33 pub source: String,
34 pub workflow: Workflow,
35 pub info: RunInfo,
36 pub action: Option<String>,
37 pub pull: Option<u32>,
38 pub title: String,
39 pub inputs: Map<String, Value>,
40 pub event_key: String,
41 pub actor_id: Option<String>,
42 pub actor: Option<String>,
43 pub trusted: bool,
44}
45
46#[derive(Clone, Deserialize)]
47pub struct RunRow {
48 pub id: String,
49 pub workflow_id: String,
50 pub repo_id: String,
51 pub repo: String,
52 pub path: String,
53 pub name: String,
54 pub title: String,
55 pub number: u64,
56 pub attempt: u64,
57 pub event: String,
58 pub action: Option<String>,
59 pub git_ref: String,
60 pub sha: String,
61 pub pull: Option<u32>,
62 pub status: String,
63 pub conclusion: Option<String>,
64 pub error: Option<String>,
65 pub actor: Option<String>,
66 pub actor_id: Option<String>,
67 pub source: String,
68 pub info: String,
69 pub inputs: String,
70 pub trusted: u32,
71 pub concurrency_group: Option<String>,
72 pub created_at: String,
73 pub started_at: Option<String>,
74 pub finished_at: Option<String>,
75}
76
77impl RunRow {
78 pub fn info(&self) -> RunInfo {
79 let mut info: RunInfo = serde_json::from_str(&self.info).unwrap_or_default();
80 info.run_id = self.id.clone();
81 info.run_number = self.number;
82 info.run_attempt = self.attempt;
83 info.workflow_path = self.path.clone();
84 if info.workflow.is_empty() {
85 info.workflow = self.name.clone();
86 }
87 info
88 }
89
90 pub fn inputs(&self) -> Map<String, Value> {
91 serde_json::from_str(&self.inputs).unwrap_or_default()
92 }
93
94 pub fn summary(&self) -> WorkflowRun {
95 WorkflowRun {
96 id: self.id.clone(),
97 workflow_id: self.workflow_id.clone(),
98 path: self.path.clone(),
99 name: self.name.clone(),
100 title: self.title.clone(),
101 number: self.number,
102 attempt: self.attempt,
103 event: self.event.clone(),
104 git_ref: self.git_ref.clone(),
105 sha: self.sha.clone(),
106 pull: self.pull,
107 status: self.status.clone(),
108 conclusion: self.conclusion.clone(),
109 error: self.error.clone(),
110 actor: self.actor.clone(),
111 created_at: self.created_at.clone(),
112 started_at: self.started_at.clone(),
113 finished_at: self.finished_at.clone(),
114 }
115 }
116}
117
118#[derive(Clone, Deserialize)]
119pub struct JobRow {
120 pub id: String,
121 pub run_id: String,
122 pub repo_id: String,
123 pub namespace: String,
124 pub key: String,
125 pub ordinal: u32,
126 pub name: String,
127 pub needs: String,
128 pub matrix: Option<String>,
129 pub status: String,
130 pub conclusion: Option<String>,
131 pub steps: String,
132 pub annotations: String,
133 pub outputs: String,
134 pub reason: Option<String>,
135 pub token_hash: Option<String>,
136 pub timeout_minutes: u32,
137 pub continue_on_error: u32,
138 pub max_parallel: Option<u32>,
139 pub seen_at: Option<String>,
140 pub started_at: Option<String>,
141 pub finished_at: Option<String>,
142}
143
144impl JobRow {
145 pub fn needs(&self) -> Vec<String> {
146 serde_json::from_str(&self.needs).unwrap_or_default()
147 }
148}
149
150/// What the jobs of one key came to, for `needs.<key>`.
151fn key_result(rows: &[&JobRow]) -> &'static str {
152 let failed = |row: &&&JobRow| row.conclusion.as_deref() == Some("failure") && row.continue_on_error == 0;
153 if rows.iter().any(|row| failed(&row)) {
154 "failure"
155 } else if rows.iter().any(|row| row.conclusion.as_deref() == Some("cancelled")) {
156 "cancelled"
157 } else if rows.iter().all(|row| row.conclusion.as_deref() == Some("skipped")) {
158 "skipped"
159 } else {
160 "success"
161 }
162}
163
164fn now() -> String {
165 rfc3339(now_ms())
166}
167
168impl Actions {
169 pub async fn run_row(&self, id: &str) -> Result<Option<RunRow>> {
170 self.db.prepare("SELECT * FROM runs WHERE id = ?").bind(&[id.into()])?.first::<RunRow>(None).await
171 }
172
173 pub async fn job_rows(&self, run_id: &str) -> Result<Vec<JobRow>> {
174 self.db
175 .prepare("SELECT * FROM jobs WHERE run_id = ? ORDER BY rowid")
176 .bind(&[run_id.into()])?
177 .all()
178 .await?
179 .results::<JobRow>()
180 }
181
182 pub async fn run_summary(&self, id: &str) -> Result<Outcome<WorkflowRun>> {
183 Ok(match self.run_row(id).await? {
184 Some(row) => Outcome::Ok(row.summary()),
185 None => fail(FailureCode::NotFound, "No such run."),
186 })
187 }
188
189 /// The contexts every expression outside a job's steps may use.
190 fn base_contexts(run: &RunRow, vars: &Map<String, Value>, job: &str) -> Map<String, Value> {
191 let mut contexts = Map::new();
192 contexts.insert("github".into(), run.info().context(job, "", run.action.as_deref()));
193 contexts.insert("inputs".into(), Value::Object(run.inputs()));
194 contexts.insert("vars".into(), Value::Object(vars.clone()));
195 contexts.insert("needs".into(), json!({}));
196 contexts.insert("runner".into(), runner_context());
197 contexts
198 }
199
200 /// Makes a run and its jobs, and starts what can start. `None` when the
201 /// event already started this workflow.
202 pub async fn create_run(&self, new: NewRun) -> Result<Option<String>> {
203 let workflow_row = self.workflow_row(&new.repo, &new.path, &new.workflow.display_name(&new.path), &new.source).await?;
204 let numbered = self
205 .db
206 .prepare("UPDATE workflows SET run_count = run_count + 1 WHERE id = ? RETURNING run_count AS n")
207 .bind(&[workflow_row.id.as_str().into()])?
208 .first::<Count>(None)
209 .await?
210 .map_or(1, |count| count.n);
211 let id = new_id("run", now_ms());
212 let mut info = new.info.clone();
213 info.workflow = new.workflow.display_name(&new.path);
214 info.workflow_path = new.path.clone();
215 info.run_id = id.clone();
216 info.run_number = u64::from(numbered);
217 let vars = self.variables_for(&new.repo.id, &new.repo.namespace).await?;
218
219 // run-name and the concurrency group read github, inputs and vars.
220 let mut contexts = Map::new();
221 contexts.insert("github".into(), info.context("", "", new.action.as_deref()));
222 contexts.insert("inputs".into(), Value::Object(new.inputs.clone()));
223 contexts.insert("vars".into(), Value::Object(vars));
224 let scope = Scope {
225 contexts: &contexts,
226 status: Status::Success,
227 hash_files: None,
228 };
229 let title = new
230 .workflow
231 .run_name
232 .as_deref()
233 .and_then(|run_name| expr::interpolate(run_name, &scope).ok())
234 .filter(|title| !title.trim().is_empty())
235 .unwrap_or(new.title.clone());
236 let group = new.workflow.concurrency.as_ref().and_then(|c| expr::interpolate(&c.group, &scope).ok());
237 let cancel_in_progress = new
238 .workflow
239 .concurrency
240 .as_ref()
241 .and_then(|c| expr::interpolate_value(&c.cancel_in_progress, &scope).ok())
242 .is_some_and(|value| expr::truthy(&value));
243
244 let inserted = self
245 .db
246 .prepare(
247 "INSERT OR IGNORE INTO runs (id, workflow_id, repo_id, repo, path, name, title, number, event, action, git_ref, sha,
248 pull, status, actor, actor_id, source, info, inputs, trusted, concurrency_group, event_key, created_at)
249 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
250 )
251 .bind(&[
252 id.as_str().into(),
253 workflow_row.id.as_str().into(),
254 new.repo.id.as_str().into(),
255 format!("{}/{}", new.repo.namespace, new.repo.name).into(),
256 new.path.as_str().into(),
257 info.workflow.as_str().into(),
258 title.as_str().into(),
259 numbered.into(),
260 info.event_name.as_str().into(),
261 optional(new.action.as_deref()),
262 info.git_ref.as_str().into(),
263 info.sha.as_str().into(),
264 new.pull.map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
265 optional(new.actor.as_deref()),
266 optional(new.actor_id.as_deref()),
267 new.source.as_str().into(),
268 serde_json::to_string(&info)?.into(),
269 serde_json::to_string(&new.inputs)?.into(),
270 u32::from(new.trusted).into(),
271 optional(group.as_deref()),
272 new.event_key.as_str().into(),
273 now().into(),
274 ])?
275 .first::<Value>(None)
276 .await?;
277 if inserted.is_none() {
278 return Ok(None);
279 }
280 if let Some(run) = self.run_row(&id).await? {
281 self.report_pending(&run).await?;
282 }
283
284 // Every job, waiting; each is expanded when the jobs it needs are done.
285 let mut statements = Vec::new();
286 for job in &new.workflow.jobs {
287 statements.push(
288 self.db
289 .prepare(
290 "INSERT INTO jobs (id, run_id, repo_id, namespace, key, name, needs, status) VALUES (?, ?, ?, ?, ?, ?, ?, 'waiting')",
291 )
292 .bind(&[
293 new_id("job", now_ms()).into(),
294 id.as_str().into(),
295 new.repo.id.as_str().into(),
296 new.repo.namespace.as_str().into(),
297 job.id.as_str().into(),
298 job.name.clone().filter(|n| !expr::has_expression(n)).unwrap_or(job.id.clone()).into(),
299 serde_json::to_string(&job.needs)?.into(),
300 ])?,
301 );
302 }
303 self.db.batch(statements).await?;
304
305 // One run at a time per concurrency group.
306 if let Some(group) = &group {
307 let others = self
308 .db
309 .prepare("SELECT * FROM runs WHERE repo_id = ? AND concurrency_group = ? AND id != ? AND status != 'completed' ORDER BY id")
310 .bind(&[new.repo.id.as_str().into(), group.as_str().into(), id.as_str().into()])?
311 .all()
312 .await?
313 .results::<RunRow>()?;
314 for other in &others {
315 if cancel_in_progress || other.status == "pending" {
316 // A newer run replaces a waiting one, as on GitHub.
317 self.cancel_run(other, "A newer run in the same concurrency group replaced it.").await?;
318 }
319 }
320 if !cancel_in_progress && others.iter().any(|other| other.status != "pending") {
321 self.db
322 .prepare("UPDATE runs SET status = 'pending' WHERE id = ?")
323 .bind(&[id.as_str().into()])?
324 .run()
325 .await?;
326 return Ok(Some(id));
327 }
328 }
329 self.advance(&id).await?;
330 Ok(Some(id))
331 }
332
333 /// A run that could not start, such as for a workflow file that does not read.
334 #[allow(clippy::too_many_arguments)]
335 pub async fn record_failed_run(
336 &self,
337 row: &WorkflowRow,
338 git_ref: &str,
339 sha: &str,
340 event_key: &str,
341 actor_id: Option<&str>,
342 actor: &str,
343 problem: &str,
344 ) -> Result<()> {
345 let numbered = self
346 .db
347 .prepare("UPDATE workflows SET run_count = run_count + 1 WHERE id = ? RETURNING run_count AS n")
348 .bind(&[row.id.as_str().into()])?
349 .first::<Count>(None)
350 .await?
351 .map_or(1, |count| count.n);
352 let at = now();
353 self.db
354 .prepare(
355 "INSERT OR IGNORE INTO runs (id, workflow_id, repo_id, repo, path, name, title, number, event, git_ref, sha, status,
356 conclusion, error, actor, actor_id, source, info, event_key, created_at, finished_at)
357 VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'push', ?, ?, 'completed', 'failure', ?, ?, ?, ?, '{}', ?, ?, ?)",
358 )
359 .bind(&[
360 new_id("run", now_ms()).into(),
361 row.id.as_str().into(),
362 row.repo_id.as_str().into(),
363 row.repo.as_str().into(),
364 row.path.as_str().into(),
365 row.path.as_str().into(),
366 "Invalid workflow file".into(),
367 numbered.into(),
368 git_ref.into(),
369 sha.into(),
370 problem.into(),
371 actor.into(),
372 optional(actor_id),
373 row.source.as_str().into(),
374 event_key.into(),
375 at.as_str().into(),
376 at.as_str().into(),
377 ])?
378 .run()
379 .await?;
380 Ok(())
381 }
382
383 /// Moves a run along: jobs whose needs are done are decided on, and
384 /// jobs that can start are started.
385 pub async fn advance(&self, run_id: &str) -> Result<()> {
386 // Each pass may finish jobs (skipped ones), which may free others.
387 for _ in 0..20 {
388 let Some(run) = self.run_row(run_id).await? else { return Ok(()) };
389 if run.status == "completed" || run.status == "pending" {
390 return Ok(());
391 }
392 let workflow = match workflow::parse(&run.source) {
393 Ok(workflow) => workflow,
394 Err(problem) => {
395 self.finish_run(&run, Some(&problem)).await?;
396 return Ok(());
397 }
398 };
399 let jobs = self.job_rows(run_id).await?;
400 let mut changed = false;
401 for job in &workflow.jobs {
402 let rows: Vec<&JobRow> = jobs.iter().filter(|row| row.key == job.id).collect();
403 if rows.is_empty() || !rows.iter().all(|row| row.status == "waiting") {
404 continue;
405 }
406 let needed: Vec<(&String, Vec<&JobRow>)> =
407 job.needs.iter().map(|need| (need, jobs.iter().filter(|row| &row.key == need).collect())).collect();
408 if !needed.iter().all(|(_, rows)| rows.iter().all(|row| row.status == "completed")) {
409 continue;
410 }
411 self.decide(&run, job, rows[0], &needed).await?;
412 changed = true;
413 }
414 if !changed {
415 break;
416 }
417 }
418 self.start_queued().await?;
419 self.finish_if_done(run_id).await
420 }
421
422 /// Decides on one job whose needs are done: skip it, fail it, or expand
423 /// it into its matrix and queue it.
424 async fn decide(&self, run: &RunRow, job: &workflow::Job, row: &JobRow, needed: &[(&String, Vec<&JobRow>)]) -> Result<()> {
425 let vars = self.variables_for(&run.repo_id, &repo_path(&run.repo).namespace).await?;
426 let mut contexts = Self::base_contexts(run, &vars, &job.id);
427 let mut needs = Map::new();
428 let mut status = if run.conclusion.as_deref() == Some("cancelled") { Status::Cancelled } else { Status::Success };
429 for (key, rows) in needed {
430 let result = key_result(rows);
431 let mut outputs = Map::new();
432 for row in rows {
433 if let Ok(Value::Object(more)) = serde_json::from_str::<Value>(&row.outputs) {
434 outputs.extend(more);
435 }
436 }
437 if result != "success" && status == Status::Success {
438 status = Status::Failure;
439 }
440 needs.insert((*key).clone(), json!({ "result": result, "outputs": outputs }));
441 }
442 contexts.insert("needs".into(), Value::Object(needs));
443 let scope = Scope {
444 contexts: &contexts,
445 status,
446 hash_files: None,
447 };
448 let condition = job.condition.as_deref().unwrap_or_default();
449 match expr::condition(condition, &scope) {
450 Ok(true) => {}
451 Ok(false) => return self.skip_job(row, None).await,
452 Err(problem) => return self.fail_job(row, &format!("Its `if` does not read: {problem}")).await,
453 }
454 if job.uses.is_some() {
455 return self.fail_job(row, "Reusable workflows (`uses:` on a job) are not called on g1t yet.").await;
456 }
457
458 // Its matrix, which may come from a needed job's outputs.
459 let combinations = match &job.matrix {
460 None => vec![Map::new()],
461 Some(matrix) => {
462 let value = match expr::interpolate_value(matrix, &scope) {
463 Ok(value) => value,
464 Err(problem) => return self.fail_job(row, &format!("Its matrix does not read: {problem}")).await,
465 };
466 match matrix::expand(&value) {
467 Ok(combinations) if !combinations.is_empty() => combinations,
468 Ok(_) => return self.fail_job(row, "Its matrix makes no jobs.").await,
469 Err(problem) => return self.fail_job(row, &problem).await,
470 }
471 }
472 };
473 let total = combinations.len();
474 let raw = job.raw.as_object().cloned().unwrap_or_default();
475 let mut statements = Vec::new();
476 for (index, combination) in combinations.iter().enumerate() {
477 let mut contexts = contexts.clone();
478 contexts.insert("matrix".into(), Value::Object(combination.clone()));
479 contexts.insert(
480 "strategy".into(),
481 json!({ "fail-fast": job.fail_fast, "job-index": index, "job-total": total, "max-parallel": job.max_parallel.unwrap_or(total as u32) }),
482 );
483 let scope = Scope {
484 contexts: &contexts,
485 status: Status::Success,
486 hash_files: None,
487 };
488 let base_name = job.name.clone().unwrap_or(job.id.clone());
489 let name = if expr::has_expression(&base_name) {
490 expr::interpolate(&base_name, &scope).unwrap_or(base_name)
491 } else if job.matrix.is_some() {
492 matrix::job_name(&base_name, combination)
493 } else {
494 base_name
495 };
496 let runs_on = expr::interpolate_value(&job.runs_on, &scope).unwrap_or(Value::Null);
497 let labels = match &runs_on {
498 Value::String(label) => vec![label.clone()],
499 Value::Array(labels) => labels.iter().map(expr::to_text).collect(),
500 Value::Object(spec) => spec.get("labels").map(|l| match l {
501 Value::Array(labels) => labels.iter().map(expr::to_text).collect(),
502 other => vec![expr::to_text(other)],
503 }).unwrap_or_default(),
504 _ => Vec::new(),
505 };
506 let reason = labels
507 .iter()
508 .find(|label| {
509 let lower = label.to_ascii_lowercase();
510 lower.contains("windows") || lower.contains("macos")
511 })
512 .map(|label| format!("`runs-on: {label}`: g1t runs jobs on Linux only."));
513 let timeout = raw
514 .get("timeout-minutes")
515 .and_then(|value| expr::interpolate_value(value, &scope).ok())
516 .and_then(|value| value.as_f64().or_else(|| expr::to_text(&value).parse().ok()))
517 .map_or(MAX_TIMEOUT_MINUTES, |minutes| (minutes.ceil() as u32).clamp(1, MAX_TIMEOUT_MINUTES));
518 let continue_on_error = raw
519 .get("continue-on-error")
520 .and_then(|value| expr::interpolate_value(value, &scope).ok())
521 .is_some_and(|value| expr::truthy(&value));
522 let (status, conclusion, finished) = match &reason {
523 Some(_) => ("completed", Some("failure"), Some(now())),
524 None => ("queued", None, None),
525 };
526 let values: Vec<worker::wasm_bindgen::JsValue> = vec![
527 name.into(),
528 serde_json::to_string(combination)?.into(),
529 status.into(),
530 optional(conclusion),
531 optional(reason.as_deref()),
532 timeout.into(),
533 u32::from(continue_on_error).into(),
534 job.max_parallel.map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
535 optional(finished.as_deref()),
536 ];
537 if index == 0 {
538 let mut bound = values;
539 bound.push(row.id.as_str().into());
540 statements.push(
541 self.db
542 .prepare(
543 "UPDATE jobs SET name = ?, matrix = ?, status = ?, conclusion = ?, reason = ?, timeout_minutes = ?,
544 continue_on_error = ?, max_parallel = ?, finished_at = ? WHERE id = ?",
545 )
546 .bind(&bound)?,
547 );
548 } else {
549 let mut bound: Vec<worker::wasm_bindgen::JsValue> = vec![
550 new_id("job", now_ms()).into(),
551 row.run_id.as_str().into(),
552 row.repo_id.as_str().into(),
553 row.namespace.as_str().into(),
554 row.key.as_str().into(),
555 (index as u32).into(),
556 row.needs.as_str().into(),
557 ];
558 bound.extend(values);
559 statements.push(
560 self.db
561 .prepare(
562 "INSERT INTO jobs (id, run_id, repo_id, namespace, key, ordinal, needs, name, matrix, status, conclusion, reason,
563 timeout_minutes, continue_on_error, max_parallel, finished_at)
564 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
565 )
566 .bind(&bound)?,
567 );
568 }
569 }
570 self.db.batch(statements).await?;
571 Ok(())
572 }
573
574 async fn skip_job(&self, row: &JobRow, reason: Option<&str>) -> Result<()> {
575 self.db
576 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'skipped', reason = ?, finished_at = ? WHERE id = ?")
577 .bind(&[optional(reason), now().into(), row.id.as_str().into()])?
578 .run()
579 .await?;
580 Ok(())
581 }
582
583 async fn fail_job(&self, row: &JobRow, reason: &str) -> Result<()> {
584 self.db
585 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'failure', reason = ?, finished_at = ? WHERE id = ? AND status != 'completed'")
586 .bind(&[reason.into(), now().into(), row.id.as_str().into()])?
587 .run()
588 .await?;
589 Ok(())
590 }
591
592 /// Starts queued jobs, oldest first, while their workspace has room.
593 pub async fn start_queued(&self) -> Result<()> {
594 let queued = self
595 .db
596 .prepare("SELECT * FROM jobs WHERE status = 'queued' ORDER BY rowid LIMIT 50")
597 .all()
598 .await?
599 .results::<JobRow>()?;
600 let mut running: std::collections::HashMap<String, u32> = std::collections::HashMap::new();
601 for job in queued {
602 let in_workspace = match running.get(&job.namespace) {
603 Some(n) => *n,
604 None => {
605 let n = self
606 .db
607 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE status = 'in_progress' AND namespace = ?")
608 .bind(&[job.namespace.as_str().into()])?
609 .first::<Count>(None)
610 .await?
611 .map_or(0, |count| count.n);
612 running.insert(job.namespace.clone(), n);
613 n
614 }
615 };
616 if in_workspace >= RUNNING_PER_WORKSPACE {
617 continue;
618 }
619 if let Some(max) = job.max_parallel {
620 let siblings = self
621 .db
622 .prepare("SELECT COUNT(*) AS n FROM jobs WHERE run_id = ? AND key = ? AND status = 'in_progress'")
623 .bind(&[job.run_id.as_str().into(), job.key.as_str().into()])?
624 .first::<Count>(None)
625 .await?
626 .map_or(0, |count| count.n);
627 if siblings >= max {
628 continue;
629 }
630 }
631 let token = random_hex(24);
632 let at = now();
633 let claimed = self
634 .db
635 .prepare(
636 "UPDATE jobs SET status = 'in_progress', token_hash = ?, started_at = ?, seen_at = ? WHERE id = ? AND status = 'queued' RETURNING id",
637 )
638 .bind(&[sha256_hex(&token).into(), at.as_str().into(), at.as_str().into(), job.id.as_str().into()])?
639 .first::<Value>(None)
640 .await?;
641 if claimed.is_none() {
642 continue;
643 }
644 running.insert(job.namespace.clone(), in_workspace + 1);
645 self.db
646 .prepare("UPDATE runs SET status = 'in_progress', started_at = COALESCE(started_at, ?) WHERE id = ? AND status = 'queued'")
647 .bind(&[at.as_str().into(), job.run_id.as_str().into()])?
648 .run()
649 .await?;
650 let run = self.run_row(&job.run_id).await?;
651 let repo: RepoPath = run.as_ref().map(|run| repo_path(&run.repo)).unwrap_or(RepoPath {
652 namespace: job.namespace.clone(),
653 name: String::new(),
654 });
655 let started: Outcome<Value> = g1t_kit::call(
656 &self.runner,
657 "start_actions_job",
658 &StartJobArgs {
659 job: job.id.clone(),
660 token,
661 repo,
662 timeout_minutes: job.timeout_minutes,
663 },
664 )
665 .await
666 .unwrap_or_else(|error| fail(FailureCode::Conflict, format!("The runner could not be reached: {error}")));
667 if let Outcome::Fail(refused) = started {
668 Box::pin(self.finish_job(&job.id, "failure", Some(&refused.message), None)).await?;
669 }
670 }
671 Ok(())
672 }
673
674 /// Finishes a job and moves its run along.
675 pub async fn finish_job(&self, job_id: &str, conclusion: &str, reason: Option<&str>, outputs: Option<&Map<String, Value>>) -> Result<()> {
676 let finished = self
677 .db
678 .prepare(
679 "UPDATE jobs SET status = 'completed', conclusion = ?, reason = COALESCE(?, reason), outputs = COALESCE(?, outputs),
680 finished_at = ?, token_hash = NULL WHERE id = ? AND status != 'completed' RETURNING *",
681 )
682 .bind(&[
683 conclusion.into(),
684 optional(reason),
685 outputs.map(|o| serde_json::to_string(o).unwrap_or_default()).as_deref().map_or(worker::wasm_bindgen::JsValue::NULL, Into::into),
686 now().into(),
687 job_id.into(),
688 ])?
689 .first::<JobRow>(None)
690 .await?;
691 let Some(job) = finished else { return Ok(()) };
692 // Steps still marked as going are not going any more.
693 let mut steps: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
694 let mut touched = false;
695 for step in steps.iter_mut() {
696 if step["status"] != "completed" {
697 let was_running = step["status"] == "in_progress";
698 step["status"] = json!("completed");
699 step["conclusion"] = json!(if was_running { conclusion } else { "skipped" });
700 touched = true;
701 }
702 }
703 if touched {
704 self.db
705 .prepare("UPDATE jobs SET steps = ? WHERE id = ?")
706 .bind(&[serde_json::to_string(&steps)?.into(), job.id.as_str().into()])?
707 .run()
708 .await?;
709 }
710 // fail-fast: one failed combination stops the rest of its matrix.
711 if conclusion == "failure" && job.continue_on_error == 0 && job.matrix.as_deref().is_some_and(|m| m != "{}") {
712 let run = self.run_row(&job.run_id).await?;
713 let fail_fast = run
714 .as_ref()
715 .and_then(|run| workflow::parse(&run.source).ok())
716 .and_then(|workflow| workflow.jobs.into_iter().find(|j| j.id == job.key))
717 .is_none_or(|j| j.fail_fast);
718 if fail_fast {
719 let siblings = self
720 .db
721 .prepare("SELECT * FROM jobs WHERE run_id = ? AND key = ? AND status != 'completed'")
722 .bind(&[job.run_id.as_str().into(), job.key.as_str().into()])?
723 .all()
724 .await?
725 .results::<JobRow>()?;
726 for sibling in siblings {
727 self.stop_job(&sibling, "Another job of its matrix failed, and the matrix is fail-fast.").await?;
728 }
729 }
730 }
731 Box::pin(self.advance(&job.run_id)).await
732 }
733
734 /// Cancels a job, stopping its sandbox if it has one.
735 async fn stop_job(&self, job: &JobRow, reason: &str) -> Result<()> {
736 if job.status == "in_progress" {
737 let _: Result<Value> = g1t_kit::call(&self.runner, "stop_actions_job", &json!({ "job": job.id })).await;
738 }
739 self.db
740 .prepare("UPDATE jobs SET status = 'completed', conclusion = 'cancelled', reason = ?, finished_at = ?, token_hash = NULL WHERE id = ? AND status != 'completed'")
741 .bind(&[reason.into(), now().into(), job.id.as_str().into()])?
742 .run()
743 .await?;
744 Ok(())
745 }
746
747 /// Finishes the run when every job has.
748 async fn finish_if_done(&self, run_id: &str) -> Result<()> {
749 let Some(run) = self.run_row(run_id).await? else { return Ok(()) };
750 if run.status == "completed" || run.status == "pending" {
751 return Ok(());
752 }
753 let jobs = self.job_rows(run_id).await?;
754 if !jobs.iter().all(|job| job.status == "completed") {
755 return Ok(());
756 }
757 self.finish_run(&run, None).await
758 }
759
760 async fn finish_run(&self, run: &RunRow, error: Option<&str>) -> Result<()> {
761 let jobs = self.job_rows(&run.id).await?;
762 let rows: Vec<&JobRow> = jobs.iter().collect();
763 let conclusion = if error.is_some() {
764 "failure"
765 } else if run.conclusion.as_deref() == Some("cancelled") {
766 "cancelled"
767 } else if rows.is_empty() {
768 "skipped"
769 } else {
770 key_result(&rows)
771 };
772 let done = self
773 .db
774 .prepare("UPDATE runs SET status = 'completed', conclusion = ?, error = COALESCE(?, error), finished_at = ? WHERE id = ? AND status != 'completed' RETURNING id")
775 .bind(&[conclusion.into(), optional(error), now().into(), run.id.as_str().into()])?
776 .first::<Value>(None)
777 .await?;
778 if done.is_none() {
779 return Ok(());
780 }
781 self.report_status(run, conclusion).await?;
782 // The next run waiting in its concurrency group.
783 if let Some(group) = &run.concurrency_group {
784 let next = self
785 .db
786 .prepare("SELECT * FROM runs WHERE repo_id = ? AND concurrency_group = ? AND status = 'pending' ORDER BY id LIMIT 1")
787 .bind(&[run.repo_id.as_str().into(), group.as_str().into()])?
788 .first::<RunRow>(None)
789 .await?;
790 if let Some(next) = next {
791 self.db.prepare("UPDATE runs SET status = 'queued' WHERE id = ?").bind(&[next.id.as_str().into()])?.run().await?;
792 Box::pin(self.advance(&next.id)).await?;
793 }
794 }
795 Ok(())
796 }
797
798 /// Tells the pull request (or commit) how the run went, as a status.
799 async fn report_status(&self, run: &RunRow, conclusion: &str) -> Result<()> {
800 let state = match conclusion {
801 "success" | "skipped" => "success",
802 "cancelled" => "error",
803 _ => "failure",
804 };
805 let _: Result<Value> = g1t_kit::call(
806 &self.work,
807 "set_commit_status",
808 &json!({
809 "repoId": run.repo_id,
810 "sha": run.sha,
811 "context": format!("{} / {}", run.name, run.event),
812 "state": state,
813 "description": format!("{} {}", run.name, match conclusion {
814 "success" => "passed",
815 "skipped" => "was skipped",
816 "cancelled" => "was cancelled",
817 _ => "failed",
818 }),
819 "targetUrl": format!("{SITE}/{}/actions/runs/{}", run.repo, run.id),
820 }),
821 )
822 .await;
823 Ok(())
824 }
825
826 /// Tells the pull request a run has started on its head.
827 pub async fn report_pending(&self, run: &RunRow) -> Result<()> {
828 let _: Result<Value> = g1t_kit::call(
829 &self.work,
830 "set_commit_status",
831 &json!({
832 "repoId": run.repo_id,
833 "sha": run.sha,
834 "context": format!("{} / {}", run.name, run.event),
835 "state": "pending",
836 "description": format!("{} is running", run.name),
837 "targetUrl": format!("{SITE}/{}/actions/runs/{}", run.repo, run.id),
838 }),
839 )
840 .await;
841 Ok(())
842 }
843
844 /// Cancels a run: its waiting and queued jobs, and stops its running ones.
845 pub async fn cancel_run(&self, run: &RunRow, reason: &str) -> Result<()> {
846 self.db
847 .prepare("UPDATE runs SET conclusion = 'cancelled' WHERE id = ? AND status != 'completed'")
848 .bind(&[run.id.as_str().into()])?
849 .run()
850 .await?;
851 for job in self.job_rows(&run.id).await?.iter().filter(|job| job.status != "completed") {
852 self.stop_job(job, reason).await?;
853 }
854 if run.status == "pending" {
855 self.db.prepare("UPDATE runs SET status = 'queued' WHERE id = ?").bind(&[run.id.as_str().into()])?.run().await?;
856 }
857 self.advance(&run.id).await
858 }
859
860 pub async fn cancel(&self, a: RunActionArgs) -> Result<Outcome<WorkflowRun>> {
861 if let Some(Outcome::Fail(refused)) = Self::member(&a.actor, &a.repo) {
862 return Ok(Outcome::Fail(refused));
863 }
864 let run = check!(self.run_in(&a.repo, &a.id).await?);
865 if run.status == "completed" {
866 return Ok(fail(FailureCode::Conflict, "The run has already finished."));
867 }
868 self.cancel_run(&run, &format!("{} cancelled the run.", a.actor.username)).await?;
869 self.run_summary(&run.id).await
870 }
871
872 /// Runs again: every job, or with `failed_only` those that did not
873 /// succeed and the jobs that need them.
874 pub async fn rerun(&self, a: RunActionArgs) -> Result<Outcome<WorkflowRun>> {
875 if let Some(Outcome::Fail(refused)) = Self::member(&a.actor, &a.repo) {
876 return Ok(Outcome::Fail(refused));
877 }
878 let run = check!(self.run_in(&a.repo, &a.id).await?);
879 if run.status != "completed" {
880 return Ok(fail(FailureCode::Conflict, "The run is still going: cancel it first."));
881 }
882 if run.error.is_some() {
883 return Ok(fail(FailureCode::Conflict, "This run never started: fix the workflow file and push again."));
884 }
885 let jobs = self.job_rows(&run.id).await?;
886 let workflow = workflow::parse(&run.source).ok();
887 // Which keys run again: failed ones and, transitively, those needing them.
888 let mut again: Vec<String> = Vec::new();
889 for key in workflow.as_ref().map(|w| w.job_order()).unwrap_or_default() {
890 let rows: Vec<&JobRow> = jobs.iter().filter(|j| j.key == key).collect();
891 let failed = rows.iter().any(|row| row.conclusion.as_deref() != Some("success"));
892 let needs_again = rows.first().is_some_and(|row| row.needs().iter().any(|need| again.contains(need)));
893 if !a.failed_only || failed || needs_again {
894 again.push(key.to_owned());
895 }
896 }
897 if again.is_empty() {
898 return Ok(fail(FailureCode::Conflict, "Every job succeeded: there is nothing to run again."));
899 }
900 let mut statements = Vec::new();
901 for key in &again {
902 statements.push(self.db.prepare("DELETE FROM logs WHERE job_id IN (SELECT id FROM jobs WHERE run_id = ? AND key = ?)").bind(&[run.id.as_str().into(), key.as_str().into()])?);
903 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()])?);
904 statements.push(
905 self.db
906 .prepare(
907 "UPDATE jobs SET status = 'waiting', conclusion = NULL, steps = '[]', annotations = '[]', outputs = '{}', reason = NULL,
908 matrix = NULL, token_hash = NULL, seen_at = NULL, started_at = NULL, finished_at = NULL WHERE run_id = ? AND key = ?",
909 )
910 .bind(&[run.id.as_str().into(), key.as_str().into()])?,
911 );
912 }
913 statements.push(
914 self.db
915 .prepare("UPDATE runs SET status = 'queued', conclusion = NULL, attempt = attempt + 1, started_at = NULL, finished_at = NULL WHERE id = ?")
916 .bind(&[run.id.as_str().into()])?,
917 );
918 self.db.batch(statements).await?;
919 if let Some(run) = self.run_row(&run.id).await? {
920 self.report_pending(&run).await?;
921 }
922 self.advance(&run.id).await?;
923 self.run_summary(&run.id).await
924 }
925
926 pub async fn run_in(&self, repo: &RepoPath, id: &str) -> Result<Outcome<RunRow>> {
927 let row = self
928 .db
929 .prepare("SELECT * FROM runs WHERE id = ? AND lower(repo) = lower(?)")
930 .bind(&[id.into(), format!("{}/{}", repo.namespace, repo.name).into()])?
931 .first::<RunRow>(None)
932 .await?;
933 Ok(row.map_or_else(|| fail(FailureCode::NotFound, "No such run."), Outcome::Ok))
934 }
935
936 // --- The sandbox's side -----------------------------------------------------
937
938 async fn job_for_token(&self, a: &JobCallArgs) -> Result<Outcome<JobRow>> {
939 let job = self.db.prepare("SELECT * FROM jobs WHERE id = ?").bind(&[a.job.as_str().into()])?.first::<JobRow>(None).await?;
940 Ok(match job {
941 Some(job) if job.status == "in_progress" && job.token_hash.as_deref().is_some_and(|hash| same(hash, &sha256_hex(&a.token))) => {
942 Outcome::Ok(job)
943 }
944 _ => fail(FailureCode::Unauthenticated, "That job is not running, or the token is not its."),
945 })
946 }
947
948 /// `job_spec`: everything the sandbox needs to run the job.
949 pub async fn job_spec(&self, a: JobCallArgs) -> Result<Outcome<Value>> {
950 let job = check!(self.job_for_token(&a).await?);
951 let Some(run) = self.run_row(&job.run_id).await? else {
952 return Ok(fail(FailureCode::NotFound, "No such run."));
953 };
954 let Ok(workflow) = workflow::parse(&run.source) else {
955 return Ok(fail(FailureCode::Invalid, "The workflow no longer reads."));
956 };
957 let Some(spec) = workflow.jobs.iter().find(|j| j.id == job.key) else {
958 return Ok(fail(FailureCode::NotFound, "The job is not in the workflow."));
959 };
960 let repo = repo_path(&run.repo);
961 let trusted = run.trusted != 0;
962 // GITHUB_TOKEN: the workspace's, for as long as the job may run.
963 let token = if trusted {
964 match self.workspace_actor(&repo.namespace).await? {
965 Some(workspace) => {
966 let created: CreatedAccessToken = g1t_kit::call(
967 &self.identity,
968 "create_access_token",
969 &CreateAccessTokenArgs {
970 user: workspace,
971 name: format!("GITHUB_TOKEN for {} run {}", run.repo, run.number),
972 ttl_seconds: Some(u64::from(job.timeout_minutes) * 60 + 600),
973 },
974 )
975 .await?;
976 created.token
977 }
978 None => String::new(),
979 }
980 } else {
981 String::new()
982 };
983 let mut secrets = if trusted { self.secrets_for(&run.repo_id, &repo.namespace).await? } else { Map::new() };
984 secrets.insert("GITHUB_TOKEN".into(), Value::String(token.clone()));
985 let masks: Vec<String> = secrets.values().filter_map(|v| v.as_str()).filter(|v| v.len() >= 4).map(str::to_owned).collect();
986 let vars = self.variables_for(&run.repo_id, &repo.namespace).await?;
987
988 let jobs = self.job_rows(&run.id).await?;
989 let mut needs = Map::new();
990 for need in &spec.needs {
991 let rows: Vec<&JobRow> = jobs.iter().filter(|row| &row.key == need).collect();
992 let mut outputs = Map::new();
993 for row in &rows {
994 if let Ok(Value::Object(more)) = serde_json::from_str::<Value>(&row.outputs) {
995 outputs.extend(more);
996 }
997 }
998 needs.insert(need.clone(), json!({ "result": key_result(&rows), "outputs": outputs }));
999 }
1000 let siblings = jobs.iter().filter(|row| row.key == job.key).count();
1001 let matrix: Value = job.matrix.as_deref().and_then(|m| serde_json::from_str(m).ok()).unwrap_or(json!({}));
1002 let info = run.info();
1003 let mut github = info.context(&job.key, &token, run.action.as_deref());
1004 github["token"] = json!(token);
1005
1006 // Where to check out: a pull request's fork, or the repository.
1007 let clone_url = match run.pull {
1008 Some(number) if run.event.starts_with("pull_request") && run.event != "pull_request_target" => {
1009 let located: Outcome<g1t_contracts::work::PullDetail> = g1t_kit::call(
1010 &self.work,
1011 "get_pull",
1012 &g1t_contracts::work::ViewArgs {
1013 repo: repo.clone(),
1014 number,
1015 viewer: self.workspace_actor(&repo.namespace).await?,
1016 after_seq: 0,
1017 },
1018 )
1019 .await?;
1020 match located {
1021 Outcome::Ok(detail) => match detail.pull.fork {
1022 Some(fork) => format!("{SITE}/{}/{}.git", fork.namespace, fork.name),
1023 None => format!("{SITE}/{}.git", run.repo),
1024 },
1025 Outcome::Fail(_) => format!("{SITE}/{}.git", run.repo),
1026 }
1027 }
1028 _ => format!("{SITE}/{}.git", run.repo),
1029 };
1030
1031 Ok(Outcome::Ok(json!({
1032 "job": job.id,
1033 "run": run.id,
1034 "key": job.key,
1035 "name": job.name,
1036 "spec": spec.raw,
1037 "workflow": {
1038 "env": workflow.env,
1039 "defaults": workflow.raw.get("defaults").cloned().unwrap_or(Value::Null),
1040 },
1041 "github": github,
1042 "variables": info.variables(&job.key),
1043 "event": info.event,
1044 "contexts": {
1045 "vars": vars,
1046 "secrets": secrets,
1047 "inputs": run.inputs(),
1048 "matrix": matrix,
1049 "needs": needs,
1050 "strategy": {
1051 "fail-fast": spec.fail_fast,
1052 "job-index": job.ordinal,
1053 "job-total": siblings,
1054 "max-parallel": spec.max_parallel.unwrap_or(siblings as u32),
1055 },
1056 "runner": runner_context(),
1057 },
1058 "checkout": {
1059 "repository": run.repo,
1060 "url": clone_url,
1061 "sha": run.sha,
1062 "ref": run.git_ref,
1063 "token": token,
1064 },
1065 "timeoutMinutes": job.timeout_minutes,
1066 "masks": masks,
1067 })))
1068 }
1069
1070 /// `job_report`: the sandbox telling how the job is going.
1071 pub async fn job_report(&self, a: JobCallArgs) -> Result<Outcome<Value>> {
1072 let job = check!(self.job_for_token(&a).await?);
1073 let report = &a.report;
1074 let at = now();
1075 match report["kind"].as_str().unwrap_or_default() {
1076 "steps" => {
1077 // The list can grow as the job goes (post steps), so steps
1078 // already reported keep where they stand.
1079 let known: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
1080 let steps: Vec<Value> = report["steps"]
1081 .as_array()
1082 .map(|names| {
1083 names
1084 .iter()
1085 .enumerate()
1086 .map(|(i, name)| match known.get(i) {
1087 Some(step) if step["status"] != "queued" => step.clone(),
1088 _ => json!({ "number": i + 1, "name": expr::to_text(name), "status": "queued", "conclusion": null, "startedAt": null, "finishedAt": null }),
1089 })
1090 .collect()
1091 })
1092 .unwrap_or_default();
1093 self.db
1094 .prepare("UPDATE jobs SET steps = ?, seen_at = ? WHERE id = ?")
1095 .bind(&[serde_json::to_string(&steps)?.into(), at.as_str().into(), job.id.as_str().into()])?
1096 .run()
1097 .await?;
1098 }
1099 "step" => {
1100 let number = report["number"].as_u64().unwrap_or(0) as usize;
1101 let mut steps: Vec<Value> = serde_json::from_str(&job.steps).unwrap_or_default();
1102 if let Some(step) = number.checked_sub(1).and_then(|i| steps.get_mut(i)) {
1103 let status = report["status"].as_str().unwrap_or("in_progress");
1104 step["status"] = json!(status);
1105 if status == "in_progress" {
1106 step["startedAt"] = json!(at);
1107 }
1108 if status == "completed" {
1109 step["finishedAt"] = json!(at);
1110 step["conclusion"] = report["conclusion"].clone();
1111 }
1112 if let Some(name) = report["name"].as_str() {
1113 step["name"] = json!(name);
1114 }
1115 }
1116 self.db
1117 .prepare("UPDATE jobs SET steps = ?, seen_at = ? WHERE id = ?")
1118 .bind(&[serde_json::to_string(&steps)?.into(), at.as_str().into(), job.id.as_str().into()])?
1119 .run()
1120 .await?;
1121 }
1122 "log" => {
1123 let mut text = report["text"].as_str().unwrap_or_default().to_owned();
1124 if text.len() > MAX_CHUNK_BYTES {
1125 let mut cut = MAX_CHUNK_BYTES;
1126 while !text.is_char_boundary(cut) {
1127 cut -= 1;
1128 }
1129 text.truncate(cut);
1130 }
1131 #[derive(Deserialize)]
1132 struct Size {
1133 n: Option<f64>,
1134 seq: Option<f64>,
1135 }
1136 let size = self
1137 .db
1138 .prepare("SELECT SUM(LENGTH(text)) AS n, MAX(seq) AS seq FROM logs WHERE job_id = ?")
1139 .bind(&[job.id.as_str().into()])?
1140 .first::<Size>(None)
1141 .await?;
1142 let (used, seq) = size.map_or((0, 0.0), |s| (s.n.unwrap_or(0.0) as usize, s.seq.unwrap_or(0.0)));
1143 if used < MAX_LOG_BYTES {
1144 if used + text.len() >= MAX_LOG_BYTES {
1145 text.push_str("\n… The log reached its limit of 4 MB; the rest is not kept.\n");
1146 }
1147 self.db
1148 .prepare("INSERT INTO logs (job_id, seq, step, text) VALUES (?, ?, ?, ?)")
1149 .bind(&[job.id.as_str().into(), // Numbers go to D1 as f64: a u64 would be a BigInt, which it refuses.
1150 (seq + 1.0).into(), (report["step"].as_u64().unwrap_or(0) as u32).into(), text.into()])?
1151 .run()
1152 .await?;
1153 }
1154 self.db.prepare("UPDATE jobs SET seen_at = ? WHERE id = ?").bind(&[at.into(), job.id.as_str().into()])?.run().await?;
1155 }
1156 "annotation" => {
1157 let mut annotations: Vec<Value> = serde_json::from_str(&job.annotations).unwrap_or_default();
1158 if annotations.len() < MAX_ANNOTATIONS {
1159 annotations.push(json!({
1160 "level": report["level"].as_str().unwrap_or("notice"),
1161 "message": report["message"].as_str().unwrap_or_default().chars().take(4000).collect::<String>(),
1162 "title": report["title"],
1163 "file": report["file"],
1164 "line": report["line"],
1165 }));
1166 self.db
1167 .prepare("UPDATE jobs SET annotations = ?, seen_at = ? WHERE id = ?")
1168 .bind(&[serde_json::to_string(&annotations)?.into(), at.as_str().into(), job.id.as_str().into()])?
1169 .run()
1170 .await?;
1171 }
1172 }
1173 "done" => {
1174 let conclusion = report["conclusion"]
1175 .as_str()
1176 .filter(|c| matches!(*c, "success" | "failure" | "cancelled"))
1177 .unwrap_or("failure");
1178 let outputs = report["outputs"].as_object().cloned();
1179 Box::pin(self.finish_job(&job.id, conclusion, report["reason"].as_str(), outputs.as_ref())).await?;
1180 }
1181 other => return Ok(fail(FailureCode::Invalid, format!("There is no report called `{other}`."))),
1182 }
1183 Ok(Outcome::Ok(json!({ "ok": true })))
1184 }
1185
1186 // --- Every minute ---------------------------------------------------------------
1187
1188 pub async fn on_minute(&self, now_ms: u64) -> Result<()> {
1189 let minute = now_ms / 60_000 * 60_000;
1190 if let Err(error) = self.run_schedules(minute).await {
1191 worker::console_error!("actions: schedules failed: {error}");
1192 }
1193 // Jobs whose sandbox went quiet or ran past their time.
1194 let running = self.db.prepare("SELECT * FROM jobs WHERE status = 'in_progress'").all().await?.results::<JobRow>()?;
1195 for job in running {
1196 // Times in g1t's format compare as text.
1197 let before = |ms: u64| rfc3339(now_ms.saturating_sub(ms));
1198 let silent = job.seen_at.as_deref().is_some_and(|seen| seen < before(SILENT_MS).as_str());
1199 let limit = (u64::from(job.timeout_minutes) * 60 + 120) * 1000;
1200 let over = job.started_at.as_deref().is_some_and(|started| started < before(limit).as_str());
1201 if over {
1202 let reason = format!("It ran longer than its time limit of {} minutes.", job.timeout_minutes);
1203 let _: Result<Value> = g1t_kit::call(&self.runner, "stop_actions_job", &json!({ "job": job.id })).await;
1204 self.finish_job(&job.id, "failure", Some(&reason), None).await?;
1205 } else if silent {
1206 self.finish_job(&job.id, "failure", Some("The runner stopped answering."), None).await?;
1207 }
1208 }
1209 self.start_queued().await
1210 }
1211}
1212