use crate::dag::ExecutionTask;
use crate::frozen::{canonical_json, sha256_of, FrozenPlan};
use crate::plan::{self, Hoist, Plan, StayReason, StepKey};
use anyhow::{anyhow, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use std::collections::{BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
pub const CACHE_SCHEMA: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StepRef {
pub workflow: String,
pub job: String,
pub index: usize,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct RecipeStep {
pub id: String,
pub dir: String,
pub run: String,
pub shell: Option<String>,
pub env: Vec<(String, String)>,
pub unresolved_env: Vec<(String, String)>,
#[serde(default)]
pub ignored_env: Vec<(String, String)>,
#[serde(default)]
pub ignored_env_differs: Vec<IgnoredEnvDiffers>,
pub label: String,
pub workflow: String,
pub job: String,
pub at: Vec<StepRef>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IgnoredEnvDiffers {
pub workflow: String,
pub job: String,
pub name: String,
pub value: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LeftInPlace {
pub workflow: String,
pub job: String,
pub index: usize,
pub label: String,
pub reason: StayReason,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ToolchainRequirement {
pub tool: String,
pub version: String,
pub from: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SetupRecipe {
#[serde(default = "crate::wire::wire_version")]
pub schema_version: u32,
pub task: String,
pub steps: Vec<RecipeStep>,
pub left_in_place: Vec<LeftInPlace>,
pub toolchain: Vec<ToolchainRequirement>,
}
impl crate::wire::Digested for SetupRecipe {
fn schema_version(&self) -> u32 {
self.schema_version
}
}
impl crate::wire::Digested for PreparedReceipt {
fn schema_version(&self) -> u32 {
self.schema_version
}
}
impl Default for SetupRecipe {
fn default() -> Self {
SetupRecipe {
schema_version: crate::wire::wire_version(),
task: String::new(),
steps: vec![],
left_in_place: vec![],
toolchain: vec![],
}
}
}
impl SetupRecipe {
pub fn union(recipes: &[&SetupRecipe]) -> SetupRecipe {
let mut out = SetupRecipe {
task: "*".into(),
..Default::default()
};
for r in recipes {
for s in &r.steps {
match out.steps.iter_mut().find(|x| x.id == s.id) {
Some(x) => {
for a in &s.at {
if !x.at.contains(a) {
x.at.push(a.clone());
}
}
let mut differs = ignored_differences(
&x.ignored_env,
&s.ignored_env,
&s.workflow,
&s.job,
);
differs.extend(s.ignored_env_differs.iter().cloned());
for d in differs {
if !x.ignored_env_differs.contains(&d) {
x.ignored_env_differs.push(d);
}
}
}
None => out.steps.push(s.clone()),
}
}
for l in &r.left_in_place {
if !out.left_in_place.contains(l) {
out.left_in_place.push(l.clone());
}
}
for t in &r.toolchain {
if !out.toolchain.contains(t) {
out.toolchain.push(t.clone());
}
}
}
out.toolchain.sort();
out
}
pub fn template_key(&self, ctx: &TemplateContext) -> TemplateKey {
let inputs = json!({
"cache_schema": ctx.cache_schema,
"source": ctx.source_digest,
"steps": self.steps.iter().map(|s| json!({
"dir": s.dir,
"run": s.run,
"shell": s.shell.as_deref().unwrap_or("bash"),
"env": s.env,
"unresolved_env": s.unresolved_env,
})).collect::<Vec<_>>(),
"toolchain": self.toolchain,
"os": ctx.os,
"arch": ctx.arch,
"profile": ctx.profile,
"scope": ctx.scope,
"freshness": ctx.freshness,
"secrets": ctx.secrets,
});
TemplateKey {
digest: sha256_of(&canonical_json(&inputs)),
inputs,
}
}
pub(crate) fn prepared_places(
&self,
receipt: &PreparedReceipt,
source: &str,
workspace: Option<&str>,
root: &Path,
tctx: &TemplateContext,
contents: bool,
) -> Result<HashMap<String, HashSet<usize>>, String> {
let mut out: HashMap<String, HashSet<usize>> = HashMap::new();
if receipt.steps.is_empty() {
return Ok(out);
}
if receipt.source != source {
return Err("it was made for another commit".into());
}
if workspace.is_none_or(|w| w != receipt.workspace) {
return Err("it was made for another workspace".into());
}
if receipt.template_key != self.template_key(tctx).digest() {
return Err("its template key is not the key of this task's recipe here".into());
}
verify_artifacts(receipt, root, contents)?;
for s in self.steps.iter().filter(|s| receipt.covers(&s.id)) {
for a in &s.at {
out.entry(a.job.clone()).or_default().insert(a.index);
}
}
Ok(out)
}
}
pub(crate) fn verify_artifacts(
receipt: &PreparedReceipt,
root: &Path,
contents: bool,
) -> Result<(), String> {
for a in &receipt.artifacts {
let at = root.join(&a.path);
if at.symlink_metadata().is_err() {
return Err(format!(
"`{}`, which the setup made, is no longer in the workspace",
a.path
));
}
if !contents {
continue;
}
match crate::tree::tree_digest(&at) {
Ok(d) if d.digest == a.digest => {}
Ok(_) => {
return Err(format!(
"`{}` is no longer what the setup made (its tree digest differs)",
a.path
))
}
Err(e) => return Err(format!("`{}` cannot be checked: {e:#}", a.path)),
}
}
Ok(())
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ReuseScope {
Run { run_id: String },
Persistent,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Freshness {
Any,
MaxAgeSecs { secs: u64 },
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct SecretDigest {
pub name: String,
pub digest: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct TemplateContext {
pub source_digest: String,
pub os: String,
pub arch: String,
pub profile: String,
pub cache_schema: u32,
pub scope: ReuseScope,
pub freshness: Freshness,
pub secrets: Vec<SecretDigest>,
}
impl TemplateContext {
pub fn local(fp: &FrozenPlan, run_id: &str) -> Self {
TemplateContext {
source_digest: fp
.source
.pinned
.as_ref()
.map(|s| s.manifest_digest.clone())
.or_else(|| fp.source.execution_commit.clone())
.unwrap_or_else(|| fp.source.source_id.clone()),
os: std::env::consts::OS.into(),
arch: std::env::consts::ARCH.into(),
profile: "local".into(),
cache_schema: CACHE_SCHEMA,
scope: ReuseScope::Run {
run_id: run_id.into(),
},
freshness: Freshness::Any,
secrets: vec![],
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TemplateKey {
digest: String,
inputs: Value,
}
impl TemplateKey {
pub fn digest(&self) -> &str {
&self.digest
}
pub fn inputs(&self) -> &Value {
&self.inputs
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "how", rename_all = "snake_case")]
pub enum PreparedHow {
Ran,
SameAs { step: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PreparedStep {
pub id: String,
#[serde(flatten)]
pub how: PreparedHow,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArtifactDigest {
pub path: String,
pub digest: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PreparedReceipt {
#[serde(default = "crate::wire::wire_version")]
pub schema_version: u32,
pub template_key: String,
pub source: String,
#[serde(default)]
pub workspace: String,
pub steps: Vec<PreparedStep>,
pub artifacts: Vec<ArtifactDigest>,
#[serde(default)]
pub notes: Vec<ReceiptNote>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReceiptNote {
pub step: String,
pub text: String,
}
impl PreparedReceipt {
pub fn empty(template_key: &str, source: &str) -> Self {
PreparedReceipt {
schema_version: crate::wire::wire_version(),
template_key: template_key.into(),
source: source.into(),
workspace: String::new(),
steps: vec![],
artifacts: vec![],
notes: vec![],
}
}
pub fn rebound(&self, workspace: &str) -> PreparedReceipt {
PreparedReceipt {
workspace: workspace.into(),
..self.clone()
}
}
pub fn covers(&self, step_id: &str) -> bool {
self.steps.iter().any(|s| s.id == step_id)
}
pub fn restricted_to(&self, recipe: &SetupRecipe, key: &TemplateKey) -> PreparedReceipt {
PreparedReceipt {
schema_version: crate::wire::wire_version(),
template_key: key.digest().into(),
source: self.source.clone(),
workspace: self.workspace.clone(),
steps: self
.steps
.iter()
.filter(|s| recipe.steps.iter().any(|r| r.id == s.id))
.cloned()
.collect(),
artifacts: self
.artifacts
.iter()
.filter(|a| {
let parent = a.path.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
recipe.steps.iter().any(|r| r.dir == parent)
})
.cloned()
.collect(),
notes: self
.notes
.iter()
.filter(|n| recipe.steps.iter().any(|r| r.id == n.step))
.cloned()
.collect(),
}
}
}
fn step_id(k: &StepKey) -> String {
sha256_of(&canonical_json(&json!({
"dir": k.wd,
"run": k.run,
"shell": k.shell.as_deref().unwrap_or("bash"),
"env": k.env,
"unresolved_env": k.open_env,
})))
}
pub fn derive_setup_recipe(fp: &FrozenPlan, task_id: &str) -> Result<SetupRecipe> {
let task = fp
.task(task_id)
.ok_or_else(|| anyhow!("the plan has no task `{task_id}`"))?;
let plan = fp.to_plan();
derive_in(&plan, &plan::hoist(&plan), task)
}
pub(crate) fn derive_in(plan: &Plan, hoist: &Hoist, task: &ExecutionTask) -> Result<SetupRecipe> {
let sel = plan
.selected
.iter()
.find(|s| s.wf.file == task.workflow)
.ok_or_else(|| anyhow!("the plan has no workflow {}", task.workflow))?;
let w = &sel.wf;
let mut out = SetupRecipe {
task: task.id.clone(),
..Default::default()
};
let mut tools: BTreeSet<ToolchainRequirement> = BTreeSet::new();
for id in &task.jobs {
let Some(j) = w.jobs.iter().find(|j| &j.id == id) else {
continue;
};
if j.container || j.reusable.is_some() {
continue;
}
for s in &j.steps {
let Some(uses) = &s.uses else { continue };
for (k, v) in &s.with {
if let Some(tool) = k.strip_suffix("-version") {
if !v.contains("${{") && !v.is_empty() {
tools.insert(ToolchainRequirement {
tool: tool.to_string(),
version: v.clone(),
from: uses.split('@').next().unwrap_or(uses).to_string(),
});
}
}
}
}
let prefix = plan::prefix_of(w, j, &plan.ignore_env);
let mut seen: HashSet<String> = HashSet::new();
let mut ended = false;
for p in &prefix.steps {
if !hoist.keys.contains(&p.key) {
if hoist.conflicting.contains(&p.key) {
out.left_in_place.push(LeftInPlace {
workflow: w.file.clone(),
job: j.id.clone(),
index: p.index,
label: p.step.label(),
reason: StayReason::ConflictingInstall,
});
}
break;
}
let id = step_id(&p.key);
if !seen.insert(id.clone()) {
ended = true;
break;
}
let at = StepRef {
workflow: w.file.clone(),
job: j.id.clone(),
index: p.index,
};
let ignored: Vec<(String, String)> = plan::effective_env(w, j, p.step)
.0
.into_iter()
.filter(|(k, _)| plan.ignore_env.contains(k))
.collect();
match out.steps.iter_mut().find(|s| s.id == id) {
Some(s) => {
s.at.push(at);
for d in ignored_differences(&s.ignored_env, &ignored, &w.file, &j.id) {
if !s.ignored_env_differs.contains(&d) {
s.ignored_env_differs.push(d);
}
}
}
None => out.steps.push(RecipeStep {
id,
dir: p.key.wd.clone(),
run: p.key.run.clone(),
shell: p.key.shell.clone(),
env: p.key.env.clone(),
unresolved_env: p.key.open_env.clone(),
ignored_env: ignored,
ignored_env_differs: vec![],
label: p.step.label(),
workflow: w.file.clone(),
job: j.id.clone(),
at: vec![at],
}),
}
}
if let (false, Some((index, reason))) = (ended, prefix.stopped_by) {
let s = &j.steps[index];
let run = s.run.as_deref().unwrap_or("");
if plan::is_installer(run)
|| matches!(
reason,
StayReason::EnvFileEffect
| StayReason::AbsolutePath
| StayReason::UnsupportedShell
)
{
out.left_in_place.push(LeftInPlace {
workflow: w.file.clone(),
job: j.id.clone(),
index,
label: s.label(),
reason,
});
}
}
}
out.toolchain = tools.into_iter().collect();
Ok(out)
}
fn ignored_differences(
used: &[(String, String)],
other: &[(String, String)],
workflow: &str,
job: &str,
) -> Vec<IgnoredEnvDiffers> {
let mut names: BTreeSet<&str> = used.iter().map(|(k, _)| k.as_str()).collect();
names.extend(other.iter().map(|(k, _)| k.as_str()));
let get =
|m: &'_ [(String, String)], k: &str| m.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
names
.into_iter()
.filter(|k| get(used, k) != get(other, k))
.map(|k| IgnoredEnvDiffers {
workflow: workflow.to_string(),
job: job.to_string(),
name: k.to_string(),
value: get(other, k),
})
.collect()
}
pub(crate) fn ignored_env_note(s: &RecipeStep) -> Option<String> {
if s.ignored_env_differs.is_empty() {
return None;
}
let mut names: Vec<&str> = s
.ignored_env_differs
.iter()
.map(|d| d.name.as_str())
.collect();
names.sort_unstable();
names.dedup();
let names = names
.iter()
.map(|n| format!("`{n}`"))
.collect::<Vec<_>>()
.join(", ");
let others = s
.ignored_env_differs
.iter()
.map(|d| format!("{} › {}", d.workflow, d.job))
.collect::<BTreeSet<_>>()
.into_iter()
.collect::<Vec<_>>()
.join(", ");
Some(format!(
"ignore-env: the value of {names} differs between jobs that share `{}` (install ran with the values of {} › {}; others: {others})",
s.label, s.workflow, s.job,
))
}
pub fn covered_by(recipe: &SetupRecipe) -> HashMap<String, String> {
let mut seen: Vec<(String, &RecipeStep)> = Vec::new();
let mut out = HashMap::new();
for s in &recipe.steps {
let Some(family) = plan::install_family(&s.run) else {
continue;
};
let first = seen.iter().find(|(f, x)| {
*f == family
&& x.dir == s.dir
&& x.shell == s.shell
&& x.env == s.env
&& x.unresolved_env == s.unresolved_env
});
match first {
Some((_, x)) => {
out.insert(s.id.clone(), x.id.clone());
}
None => seen.push((family, s)),
}
}
out
}
#[derive(Debug, Clone)]
pub struct PreparedSetup {
pub receipt: PreparedReceipt,
pub steps: Vec<crate::exec::StepResult>,
}
impl PreparedSetup {
pub fn ok(&self) -> bool {
self.steps
.iter()
.all(|s| s.outcome == crate::exec::Outcome::Pass)
}
}
pub(crate) fn top_level_entries(root: &Path, dirs: &BTreeSet<String>) -> BTreeSet<String> {
let mut out = BTreeSet::new();
for d in dirs {
let Ok(rd) = std::fs::read_dir(root.join(d)) else {
continue;
};
for e in rd.flatten() {
let name = e.file_name().to_string_lossy().into_owned();
if name == ".git" {
continue;
}
out.insert(if d.is_empty() {
name
} else {
format!("{d}/{name}")
});
}
}
out
}
pub(crate) fn artifact_digests(
root: &Path,
before: &BTreeSet<String>,
after: &BTreeSet<String>,
) -> Vec<ArtifactDigest> {
#[cfg(test)]
crate::exec::finalization_test::inspect("artifact capture");
after
.difference(before)
.map(|p| ArtifactDigest {
path: p.clone(),
digest: crate::tree::tree_digest(&root.join(p))
.map(|d| d.digest)
.unwrap_or_else(|e| format!("unreadable: {e:#}")),
})
.collect()
}
const WORKSPACE_ID: &str = "local-ci-workspace-id";
fn git_dir_of(root: &Path) -> Option<PathBuf> {
let dot = root.join(".git");
if dot.is_dir() {
return Some(dot);
}
let text = std::fs::read_to_string(&dot).ok()?;
let dir = Path::new(text.trim().strip_prefix("gitdir:")?.trim());
let dir = if dir.is_absolute() {
dir.to_path_buf()
} else {
root.join(dir)
};
dir.is_dir().then_some(dir)
}
fn id_place(root: &Path) -> Option<(PathBuf, String)> {
let canon = std::fs::canonicalize(root).ok()?;
let git_dir = git_dir_of(root)?;
if root.join(".git").is_file() {
let owner = std::fs::read_to_string(git_dir.join("gitdir")).ok()?;
let owner = std::fs::canonicalize(owner.trim()).ok()?;
if owner != std::fs::canonicalize(root.join(".git")).ok()? {
return None;
}
}
Some((
git_dir.join(WORKSPACE_ID),
canon.to_string_lossy().into_owned(),
))
}
pub fn workspace_id(root: &Path) -> Option<String> {
let Some((file, recorded)) = id_place(root) else {
return derived_id(root);
};
let text = std::fs::read_to_string(file).ok()?;
let (id, at) = text.split_once('\n')?;
(at.trim_end() == recorded && !id.is_empty()).then(|| id.to_string())
}
fn derived_id(root: &Path) -> Option<String> {
let canon = std::fs::canonicalize(root).ok()?;
#[cfg(unix)]
let ino = {
use std::os::unix::fs::MetadataExt;
let md = std::fs::metadata(&canon).ok()?;
format!("{}:{}", md.dev(), md.ino())
};
#[cfg(not(unix))]
let ino = String::new();
Some(sha256_of(&format!("dir:{}:{ino}", canon.display())))
}
pub(crate) fn ensure_workspace_id(root: &Path) -> Result<String> {
if let Some(id) = workspace_id(root) {
return Ok(id);
}
let Some((file, recorded)) = id_place(root) else {
return derived_id(root).context("cannot derive an id for the workspace");
};
static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
let id = sha256_of(&format!(
"{}:{nanos}:{}:{recorded}",
std::process::id(),
N.fetch_add(1, std::sync::atomic::Ordering::SeqCst),
));
std::fs::write(&file, format!("{id}\n{recorded}"))?;
Ok(id)
}