use crate::dag::{self, ExecutionTask, JobGraph, ShardGroup, ShardRequest};
use crate::plan::Plan;
use crate::shard::{Basis, Discovered, Shard, ShardPlan};
use crate::wire::{JobSpec, UnitSpec, WorkflowSpec};
use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use sha2::{Digest, Sha256};
pub const SCHEMA_VERSION: u32 = 6;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SourceRef {
pub source_id: String,
pub execution_commit: Option<String>,
pub base: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pinned: Option<crate::source_plan::PinnedIdentity>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FrozenConfig {
pub workflow_dirs: Vec<String>,
pub default_workflows_dir: String,
pub no_cache: Vec<String>,
pub link_node_modules: bool,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub ignore_env: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Filters {
pub all: bool,
pub include_disabled: bool,
pub workflows_dirs: Vec<String>,
pub workflows: Vec<String>,
pub jobs: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SkippedWorkflow {
pub workflow: String,
pub reason: String,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub unrunnable: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct DisabledWorkflow {
pub path: String,
pub state: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DisabledSource {
NotChecked,
Provided,
Github,
Unavailable,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct DisabledRecord {
pub source: DisabledSource,
pub workflows: Vec<DisabledWorkflow>,
}
impl DisabledRecord {
pub fn not_checked() -> Self {
DisabledRecord {
source: DisabledSource::NotChecked,
workflows: vec![],
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FrozenPlan {
pub schema_version: u32,
pub digest: String,
pub repository: Option<String>,
pub source: SourceRef,
pub branch: Option<String>,
pub changed_files: Vec<String>,
pub config_digest: String,
pub config: FrozenConfig,
pub filters: Filters,
pub workflows: Vec<WorkflowSpec>,
pub skipped: Vec<SkippedWorkflow>,
pub disabled: DisabledRecord,
pub units: Vec<UnitSpec>,
pub graph: JobGraph,
pub tasks: Vec<ExecutionTask>,
pub shard_groups: Vec<ShardGroup>,
}
pub struct PlanParts {
pub repository: Option<String>,
pub source: SourceRef,
pub branch: Option<String>,
pub changed_files: Vec<String>,
pub config: FrozenConfig,
pub filters: Filters,
pub disabled: DisabledRecord,
pub plan: Plan,
}
fn drop_workflows(plan: &mut Plan, broken: &[(usize, String)]) {
let gone = |i: usize| broken.iter().any(|(b, _)| *b == i);
let new_index: Vec<Option<usize>> = {
let mut next = 0;
(0..plan.selected.len())
.map(|i| {
(!gone(i)).then(|| {
next += 1;
next - 1
})
})
.collect()
};
for (i, why) in broken {
plan.unrunnable.push(plan.selected[*i].wf.file.clone());
plan.skipped
.push((plan.selected[*i].wf.file.clone(), why.clone()));
}
let selected = std::mem::take(&mut plan.selected);
plan.selected = selected
.into_iter()
.enumerate()
.filter(|(i, _)| !gone(*i))
.map(|(_, s)| s)
.collect();
plan.units.retain_mut(|u| match new_index[u.wf] {
Some(n) => {
u.wf = n;
true
}
None => false,
});
}
pub fn canonical_json(value: &Value) -> String {
fn sorted(v: &Value) -> Value {
match v {
Value::Object(m) => {
let mut keys: Vec<&String> = m.keys().collect();
keys.sort();
let mut out = Map::new();
for k in keys {
out.insert(k.clone(), sorted(&m[k]));
}
Value::Object(out)
}
Value::Array(a) => Value::Array(a.iter().map(sorted).collect()),
other => other.clone(),
}
}
sorted(value).to_string()
}
pub(crate) fn sha256_of(text: &str) -> String {
let mut h = Sha256::new();
h.update(text.as_bytes());
let hex: String = h.finalize().iter().map(|b| format!("{b:02x}")).collect();
format!("sha256:{hex}")
}
impl FrozenPlan {
pub fn new(parts: PlanParts) -> Result<Self> {
Self::new_with_shards(parts, &[])
}
pub fn new_with_shards(mut parts: PlanParts, shards: &[ShardRequest]) -> Result<Self> {
let config_digest = sha256_of(&canonical_json(&serde_json::to_value(&parts.config)?));
let specs = |plan: &Plan| {
(
plan.selected
.iter()
.map(WorkflowSpec::from_selected)
.collect::<Vec<_>>(),
plan.units
.iter()
.map(UnitSpec::from_unit)
.collect::<Vec<_>>(),
)
};
let (mut workflows, mut units) = specs(&parts.plan);
let broken = dag::unrunnable_workflows(&workflows, &units);
if !broken.is_empty() {
drop_workflows(&mut parts.plan, &broken);
(workflows, units) = specs(&parts.plan);
}
let graph = dag::build_graph(&workflows, &units)?;
let (tasks, shard_groups) = dag::derive_tasks(&parts.plan, &workflows, &units, shards);
let unrunnable = std::mem::take(&mut parts.plan.unrunnable);
let mut fp = FrozenPlan {
schema_version: if parts.source.pinned.is_some() {
crate::source_plan::PINNED_SCHEMA_VERSION
} else {
SCHEMA_VERSION
},
digest: String::new(),
repository: parts.repository,
source: parts.source,
branch: parts.branch,
changed_files: parts.changed_files,
config_digest,
config: parts.config,
filters: parts.filters,
workflows,
skipped: parts
.plan
.skipped
.into_iter()
.map(|(workflow, reason)| SkippedWorkflow {
unrunnable: unrunnable.contains(&workflow),
workflow,
reason,
})
.collect(),
disabled: parts.disabled,
units,
graph,
tasks,
shard_groups,
};
fp.digest = fp.compute_digest()?;
Ok(fp)
}
pub fn require_git_source(&self) -> Result<()> {
if self.schema_version != SCHEMA_VERSION
|| self.source.pinned.is_some()
|| self
.source
.execution_commit
.as_ref()
.is_none_or(String::is_empty)
|| self.source.base.as_ref().is_none_or(String::is_empty)
{
return Err(crate::source_plan::PinnedPlanError::UnsupportedExecution.into());
}
Ok(())
}
pub fn compute_digest(&self) -> Result<String> {
let mut v = serde_json::to_value(self).context("cannot serialize the plan")?;
v["digest"] = Value::String(String::new());
Ok(sha256_of(&canonical_json(&v)))
}
pub fn verify(&self) -> Result<()> {
if self.schema_version != SCHEMA_VERSION
&& self.schema_version != crate::source_plan::PINNED_SCHEMA_VERSION
{
bail!(
"plan schema version {} is not supported (this is {SCHEMA_VERSION})",
self.schema_version
);
}
match (self.schema_version, &self.source.pinned) {
(6, None)
if self
.source
.execution_commit
.as_ref()
.is_some_and(|s| !s.is_empty())
&& self.source.base.as_ref().is_some_and(|s| !s.is_empty()) => {}
(crate::source_plan::PINNED_SCHEMA_VERSION, Some(identity)) => {
crate::source_plan::verify_identity(self, identity)?
}
_ => bail!("plan source identity does not match its schema version"),
}
crate::wire::check_version("plan job graph", self.graph.schema_version)?;
for t in &self.tasks {
crate::wire::check_version(&format!("plan task {}", t.id), t.schema_version)?;
}
self.verify_shard_dirs()?;
let want = sha256_of(&canonical_json(&serde_json::to_value(&self.config)?));
if want != self.config_digest {
bail!("plan config digest does not match its config");
}
if dag::build_graph(&self.workflows, &self.units)? != self.graph {
bail!("plan job graph does not match its jobs");
}
let want = self.compute_digest()?;
if want != self.digest {
bail!(
"plan digest {} does not match its content ({want})",
self.digest
);
}
Ok(())
}
fn verify_shard_dirs(&self) -> Result<()> {
let plan = self.to_plan();
for t in &self.tasks {
let Some(ts) = &t.shard else { continue };
crate::demand::workspace_dir(
&format!("task {}: the shard's directory", t.id),
&ts.dir,
)?;
let step_dir = t.jobs.first().and_then(|j| {
let w = &plan.selected.iter().find(|s| s.wf.file == t.workflow)?.wf;
let job = w.jobs.iter().find(|x| &x.id == j)?;
Some(crate::plan::step_dir(w, job, job.steps.get(ts.step)?))
});
if step_dir.is_some_and(|d| d != ts.dir) {
bail!(
"task {}: the shard's directory {:?} is not where its step runs",
t.id,
ts.dir
);
}
}
Ok(())
}
pub fn to_canonical_json(&self) -> Result<String> {
Ok(canonical_json(&serde_json::to_value(self)?))
}
pub fn from_json(text: &str) -> Result<Self> {
let fp: FrozenPlan = serde_json::from_str(text).context("cannot read the plan")?;
fp.verify()?;
Ok(fp)
}
pub fn to_plan(&self) -> Plan {
Plan {
selected: self
.workflows
.iter()
.map(WorkflowSpec::to_selected)
.collect(),
skipped: self
.skipped
.iter()
.map(|s| (s.workflow.clone(), s.reason.clone()))
.collect(),
unrunnable: self
.skipped
.iter()
.filter(|s| s.unrunnable)
.map(|s| s.workflow.clone())
.collect(),
units: self.units.iter().map(UnitSpec::to_unit).collect(),
ignore_env: self.config.ignore_env.clone(),
}
}
pub fn with_plan(&self, plan: Plan) -> Result<Self> {
FrozenPlan::new_with_shards(
PlanParts {
repository: self.repository.clone(),
source: self.source.clone(),
branch: self.branch.clone(),
changed_files: self.changed_files.clone(),
config: self.config.clone(),
filters: self.filters.clone(),
disabled: self.disabled.clone(),
plan,
},
&self.shard_requests(),
)
}
pub fn with_shards(&self, shards: &[ShardRequest]) -> Result<Self> {
let parts = PlanParts {
repository: self.repository.clone(),
source: self.source.clone(),
branch: self.branch.clone(),
changed_files: self.changed_files.clone(),
config: self.config.clone(),
filters: self.filters.clone(),
disabled: self.disabled.clone(),
plan: self.to_plan(),
};
FrozenPlan::new_with_shards(parts, shards)
}
pub fn shard_requests(&self) -> Vec<ShardRequest> {
self.shard_groups
.iter()
.filter(|g| g.split)
.filter_map(|g| {
let first = self.task(g.shards.first()?)?;
let ts = first.shard.as_ref()?;
Some(ShardRequest {
workflow: g.workflow.clone(),
job: g.source_jobs.first()?.clone(),
plan: ShardPlan {
runner: g.runner.clone().unwrap_or_default(),
mode: ts.mode,
basis: Basis::Fallback,
shards: g
.shards
.iter()
.filter_map(|id| self.task(id)?.shard.as_ref())
.map(|s| Shard {
index: s.index,
tests: s.tests.clone(),
load: 0,
})
.collect(),
not_split: vec![],
},
step: ts.step,
dir: ts.dir.clone(),
discovered: Discovered {
tests: g.manifest.clone(),
complete: g.manifest_exact,
..Default::default()
},
fail_fast: g.fail_fast,
})
})
.collect()
}
pub fn with_source_id(mut self, source_id: &str) -> Result<Self> {
self.source.source_id = source_id.to_string();
self.digest = self.compute_digest()?;
Ok(self)
}
pub fn job(&self, wf: usize, id: &str) -> &JobSpec {
self.workflows[wf].job(id).expect("job in plan")
}
pub fn task(&self, id: &str) -> Option<&ExecutionTask> {
self.tasks.iter().find(|t| t.id == id)
}
}
pub fn derive_job_dag(fp: &FrozenPlan) -> Result<JobGraph> {
dag::build_graph(&fp.workflows, &fp.units)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonical_json_sorts_keys_at_every_level() {
let v: Value =
serde_json::from_str(r#"{"b":1,"a":{"d":[{"z":1,"y":2}],"c":null}}"#).unwrap();
assert_eq!(
canonical_json(&v),
r#"{"a":{"c":null,"d":[{"y":2,"z":1}]},"b":1}"#
);
}
#[test]
fn digests_are_sha256_hex() {
assert_eq!(
sha256_of(""),
"sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}
}