use crate::dag::{self, ExecutionTask, JobGraph, ShardGroup};
use crate::plan::Plan;
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 = 4;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SourceRef {
pub source_id: String,
pub execution_commit: String,
pub base: String,
}
#[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(mut parts: PlanParts) -> 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);
let unrunnable = std::mem::take(&mut parts.plan.unrunnable);
let mut fp = FrozenPlan {
schema_version: 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 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 {
bail!(
"plan schema version {} is not supported (this is {SCHEMA_VERSION})",
self.schema_version
);
}
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(())
}
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(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,
})
}
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"
);
}
}