use crate::canonical;
use crate::digest::{self, Digest, HasherFactory, TaskStatus};
use crate::error::{CanonicalError, ManifestError};
use crate::value::Value;
pub const MANIFEST_FORMAT: &str = "verirun-manifest/1";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArtifactRecord {
pub path: String,
pub digest: Digest,
pub bytes: u64,
pub executable: bool,
}
impl ArtifactRecord {
#[must_use]
pub fn framing_digest(&self, factory: &dyn HasherFactory) -> Digest {
digest::artifact_digest(
factory,
&self.path,
&self.digest,
self.bytes,
self.executable,
)
}
#[must_use]
#[allow(
clippy::cast_precision_loss,
reason = "byte lengths are inside the safe integer domain by physical necessity (section 9.1), and the canonical encoder rejects any value outside it at encode time"
)]
pub fn to_value(&self) -> Value {
Value::Object(vec![
("path".to_string(), Value::String(self.path.clone())),
("sha256".to_string(), Value::String(self.digest.to_hex())),
("bytes".to_string(), Value::Number(self.bytes as f64)),
("executable".to_string(), Value::Bool(self.executable)),
])
}
pub fn from_value(value: &Value) -> Result<Self, ManifestError> {
let pairs = as_object(value, "artifact")?;
Ok(Self {
path: as_string(get(pairs, "path")?, "path")?.to_string(),
digest: as_digest(get(pairs, "sha256")?, "sha256")?,
bytes: as_bytes(get(pairs, "bytes")?, "bytes")?,
executable: as_bool(get(pairs, "executable")?, "executable")?,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskRecord {
pub task_id: String,
pub exec_digest: Digest,
pub status: TaskStatus,
pub exit_code: Option<i32>,
pub stdout_digest: Digest,
pub stderr_digest: Digest,
pub artifacts: Vec<ArtifactRecord>,
}
impl TaskRecord {
#[must_use]
pub fn new(
task_id: String,
exec_digest: Digest,
status: TaskStatus,
exit_code: Option<i32>,
stdout_digest: Digest,
stderr_digest: Digest,
artifacts: Vec<ArtifactRecord>,
) -> Self {
let mut artifacts = artifacts;
artifacts.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
for window in artifacts.windows(2) {
assert!(
window[0].path != window[1].path,
"duplicate artifact path {:?} in a built record",
window[0].path
);
}
Self {
task_id,
exec_digest,
status,
exit_code,
stdout_digest,
stderr_digest,
artifacts,
}
}
#[must_use]
pub fn record_digest(&self, factory: &dyn HasherFactory) -> Digest {
let framing: Vec<Digest> = self
.artifacts
.iter()
.map(|artifact| artifact.framing_digest(factory))
.collect();
digest::task_digest(
factory,
&self.task_id,
&self.exec_digest,
self.status,
self.exit_code,
&self.stdout_digest,
&self.stderr_digest,
&framing,
)
}
#[must_use]
pub fn named_digests(&self) -> Vec<Digest> {
let mut out: Vec<Digest> = Vec::new();
for digest in std::iter::once(&self.stdout_digest)
.chain(std::iter::once(&self.stderr_digest))
.chain(self.artifacts.iter().map(|artifact| &artifact.digest))
{
if !out.contains(digest) {
out.push(*digest);
}
}
out
}
#[must_use]
pub fn to_value(&self) -> Value {
let exit_code = self
.exit_code
.map_or(Value::Null, |code| Value::Number(f64::from(code)));
Value::Object(vec![
("task_id".to_string(), Value::String(self.task_id.clone())),
(
"exec_digest".to_string(),
Value::String(self.exec_digest.to_hex()),
),
(
"status".to_string(),
Value::String(self.status.as_str().to_string()),
),
("exit_code".to_string(), exit_code),
(
"stdout_sha256".to_string(),
Value::String(self.stdout_digest.to_hex()),
),
(
"stderr_sha256".to_string(),
Value::String(self.stderr_digest.to_hex()),
),
(
"artifacts".to_string(),
Value::Array(
self.artifacts
.iter()
.map(ArtifactRecord::to_value)
.collect(),
),
),
])
}
pub fn from_value(value: &Value) -> Result<Self, ManifestError> {
let pairs = as_object(value, "task")?;
let mut artifacts = match get(pairs, "artifacts")? {
Value::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
out.push(ArtifactRecord::from_value(item)?);
}
out
}
_ => {
return Err(ManifestError::WrongType {
field: "artifacts",
expected: "an array",
});
}
};
artifacts.sort_by(|left, right| left.path.as_bytes().cmp(right.path.as_bytes()));
let task_id = as_string(get(pairs, "task_id")?, "task_id")?.to_string();
if let Some(window) = artifacts
.windows(2)
.find(|window| window[0].path == window[1].path)
{
return Err(ManifestError::DuplicateArtifactPath {
task_id,
path: window[0].path.clone(),
});
}
Ok(Self::new(
task_id,
as_digest(get(pairs, "exec_digest")?, "exec_digest")?,
as_status(get(pairs, "status")?)?,
as_exit_code(get(pairs, "exit_code")?)?,
as_digest(get(pairs, "stdout_sha256")?, "stdout_sha256")?,
as_digest(get(pairs, "stderr_sha256")?, "stderr_sha256")?,
artifacts,
))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Manifest {
pub tasks: Vec<TaskRecord>,
pub merkle_root: Digest,
}
impl Manifest {
#[must_use]
pub fn build(factory: &dyn HasherFactory, mut records: Vec<TaskRecord>) -> Self {
records.sort_by(|left, right| left.task_id.as_bytes().cmp(right.task_id.as_bytes()));
for window in records.windows(2) {
assert!(
window[0].task_id != window[1].task_id,
"duplicate task id {:?} in a built manifest",
window[0].task_id
);
}
let leaves: Vec<Digest> = records
.iter()
.map(|record| record.record_digest(factory))
.collect();
let merkle_root = digest::merkle_root(factory, &leaves);
Self {
tasks: records,
merkle_root,
}
}
#[must_use]
pub fn recompute_root(&self, factory: &dyn HasherFactory) -> Digest {
let leaves: Vec<Digest> = self
.tasks
.iter()
.map(|record| record.record_digest(factory))
.collect();
digest::merkle_root(factory, &leaves)
}
#[must_use]
pub fn to_value(&self) -> Value {
Value::Object(vec![
(
"format".to_string(),
Value::String(MANIFEST_FORMAT.to_string()),
),
(
"merkle_root".to_string(),
Value::String(self.merkle_root.to_hex()),
),
(
"tasks".to_string(),
Value::Array(self.tasks.iter().map(TaskRecord::to_value).collect()),
),
])
}
pub fn from_value(value: &Value) -> Result<Self, ManifestError> {
let pairs = as_object(value, "manifest")?;
let format = as_string(get(pairs, "format")?, "format")?;
if format != MANIFEST_FORMAT {
return Err(ManifestError::WrongFormat {
found: format.to_string(),
});
}
let merkle_root = as_digest(get(pairs, "merkle_root")?, "merkle_root")?;
let mut tasks = match get(pairs, "tasks")? {
Value::Array(items) => {
let mut out = Vec::with_capacity(items.len());
for item in items {
out.push(TaskRecord::from_value(item)?);
}
out
}
_ => {
return Err(ManifestError::WrongType {
field: "tasks",
expected: "an array",
});
}
};
tasks.sort_by(|left, right| left.task_id.as_bytes().cmp(right.task_id.as_bytes()));
for window in tasks.windows(2) {
if window[0].task_id == window[1].task_id {
return Err(ManifestError::DuplicateTaskId {
task_id: window[0].task_id.clone(),
});
}
}
Ok(Self { tasks, merkle_root })
}
pub fn canonical_bytes(&self) -> Result<Vec<u8>, CanonicalError> {
let mut out = Vec::new();
canonical::encode(&self.to_value(), &mut out)?;
Ok(out)
}
#[must_use]
pub fn digest(&self, factory: &dyn HasherFactory) -> Digest {
let bytes = self
.canonical_bytes()
.expect("manifest fields are in the canonical domain by construction");
digest::hash_bytes(factory, digest::DomainTag::Blob, &bytes)
}
}
const fn as_object<'a>(
value: &'a Value,
field: &'static str,
) -> Result<&'a Vec<(String, Value)>, ManifestError> {
match value {
Value::Object(pairs) => Ok(pairs),
_ => Err(ManifestError::WrongType {
field,
expected: "an object",
}),
}
}
fn get<'a>(pairs: &'a [(String, Value)], field: &'static str) -> Result<&'a Value, ManifestError> {
pairs
.iter()
.find(|(key, _)| key == field)
.map(|(_, value)| value)
.ok_or(ManifestError::MissingField { field })
}
fn as_string<'a>(value: &'a Value, field: &'static str) -> Result<&'a str, ManifestError> {
match value {
Value::String(text) => Ok(text),
_ => Err(ManifestError::WrongType {
field,
expected: "a string",
}),
}
}
fn as_digest(value: &Value, field: &'static str) -> Result<Digest, ManifestError> {
let text = as_string(value, field)?;
Digest::from_hex(text).map_err(|source| ManifestError::InvalidDigest { field, source })
}
const fn as_bool(value: &Value, field: &'static str) -> Result<bool, ManifestError> {
match value {
Value::Bool(flag) => Ok(*flag),
_ => Err(ManifestError::WrongType {
field,
expected: "a boolean",
}),
}
}
#[allow(
clippy::float_cmp,
reason = "the domain checks are exactness tests on parsed values: a field is valid only when the number is exactly integral"
)]
#[allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "the value is range-checked against 0..=9007199254740991 and exact integrality immediately before the conversion, so the conversion is exact"
)]
fn as_bytes(value: &Value, field: &'static str) -> Result<u64, ManifestError> {
match value {
Value::Number(number) => {
if *number < 0.0 || *number > canonical::MAX_SAFE_INTEGER || number.fract() != 0.0 {
return Err(ManifestError::InvalidNumber {
field,
detail: format!(
"byte length must be an integer between 0 and 9007199254740991, found {number}"
),
});
}
Ok(*number as u64)
}
_ => Err(ManifestError::WrongType {
field,
expected: "a number",
}),
}
}
#[allow(
clippy::float_cmp,
reason = "the domain checks are exactness tests on parsed values: a field is valid only when the number is exactly integral"
)]
fn as_exit_code(value: &Value) -> Result<Option<i32>, ManifestError> {
match value {
Value::Null => Ok(None),
Value::Number(number) => {
if *number < f64::from(i32::MIN)
|| *number > f64::from(i32::MAX)
|| number.fract() != 0.0
{
return Err(ManifestError::InvalidNumber {
field: "exit_code",
detail: format!(
"exit code must be an integer in the i32 range, found {number}"
),
});
}
#[allow(
clippy::cast_possible_truncation,
reason = "the value was range-checked against the i32 bounds immediately above"
)]
Ok(Some(*number as i32))
}
_ => Err(ManifestError::WrongType {
field: "exit_code",
expected: "an integer or null",
}),
}
}
fn as_status(value: &Value) -> Result<TaskStatus, ManifestError> {
let text = as_string(value, "status")?;
match text {
"succeeded" => Ok(TaskStatus::Succeeded),
"failed" => Ok(TaskStatus::Failed),
"timed_out" => Ok(TaskStatus::TimedOut),
"cached" => Ok(TaskStatus::Cached),
"skipped" => Ok(TaskStatus::Skipped),
_ => Err(ManifestError::UnknownStatus {
found: text.to_string(),
}),
}
}
#[allow(
clippy::struct_excessive_bools,
reason = "the five compared fields of section 9.4 are independent by design; the struct is the field-by-field report"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ChangedFields {
pub status: bool,
pub exit_code: bool,
pub artifacts: bool,
pub stdout: bool,
pub stderr: bool,
}
impl ChangedFields {
#[must_use]
pub const fn any(&self) -> bool {
self.status || self.exit_code || self.artifacts || self.stdout || self.stderr
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TaskDifference {
OnlyInFirst,
OnlyInSecond,
Changed(ChangedFields),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TaskDiff {
pub task_id: String,
pub difference: TaskDifference,
}
#[allow(
clippy::missing_const_for_fn,
reason = "the implementation walks both manifests' records; it cannot be const"
)]
#[must_use]
pub fn diff_manifests(first: &Manifest, second: &Manifest) -> Vec<TaskDiff> {
let first_by_id: std::collections::BTreeMap<&str, &TaskRecord> = first
.tasks
.iter()
.map(|record| (record.task_id.as_str(), record))
.collect();
let second_by_id: std::collections::BTreeMap<&str, &TaskRecord> = second
.tasks
.iter()
.map(|record| (record.task_id.as_str(), record))
.collect();
let ids: std::collections::BTreeSet<&str> = first_by_id
.keys()
.chain(second_by_id.keys())
.copied()
.collect();
let mut differences = Vec::new();
for task_id in ids {
match (first_by_id.get(task_id), second_by_id.get(task_id)) {
(Some(_), None) => differences.push(TaskDiff {
task_id: task_id.to_string(),
difference: TaskDifference::OnlyInFirst,
}),
(None, Some(_)) => differences.push(TaskDiff {
task_id: task_id.to_string(),
difference: TaskDifference::OnlyInSecond,
}),
(Some(left), Some(right)) => {
let fields = ChangedFields {
status: left.status != right.status,
exit_code: left.exit_code != right.exit_code,
artifacts: left.artifacts != right.artifacts,
stdout: left.stdout_digest != right.stdout_digest,
stderr: left.stderr_digest != right.stderr_digest,
};
if fields.any() {
differences.push(TaskDiff {
task_id: task_id.to_string(),
difference: TaskDifference::Changed(fields),
});
}
}
(None, None) => {}
}
}
differences
}