use super::{PreparedFingerprint, content};
use crate::config::{ArtifactName, Eval, EvalDeclaration, Profile, RepoConfig};
use serde_json::json;
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet};
const KIND_KEY_FORMAT_PREFIX: &[u8] = b"artifactize-kind-key-v1\n";
const PARTS_KEY_FORMAT_PREFIX: &[u8] = b"artifactize-parts-key-v1\n";
const REUSE_KEY_FORMAT_PREFIX: &str = "artifactize-key-v2\n";
pub fn eval_definition_hash(eval: &EvalDeclaration) -> crate::types::DefinitionHash {
let kind = match &eval.profile() {
Profile::Agent { .. } => "agent",
Profile::Human {} => "human",
Profile::Runtime { .. } => "runtime",
};
let mut criteria = json!({
"kind": kind,
"payload": eval.payload(),
"passSchema": eval.pass_schema(),
"failSchema": eval.fail_schema(),
});
if let Some(red_at) = eval.red_at() {
criteria["redAt"] = json!(red_at);
}
if let Profile::Runtime { command, args, .. } = &eval.profile() {
criteria["command"] = json!(command);
criteria["args"] = json!(args);
}
criteria.sort_all_objects();
content::hex(&Sha256::digest(
serde_json::to_vec(&criteria).expect("evaluation criteria is JSON"),
))
.parse()
.expect("a SHA-256 digest in hex is a definition hash")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Key {
pub value: crate::types::ReuseKey,
pub eval_def_hash: crate::types::DefinitionHash,
pub fingerprints: BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
pub artifact_kinds: BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unkeyed {
Target,
Dependency(ArtifactName),
LiveObservation(ArtifactName),
LiveUnobserved(ArtifactName),
}
pub fn dependencies<'a>(config: &'a RepoConfig, eval: &'a Eval) -> BTreeSet<&'a ArtifactName> {
std::iter::once(&eval.target)
.chain(config.descendants(&eval.target))
.chain(&eval.deps)
.collect()
}
pub(crate) fn fingerprint_targets<'a>(
config: &'a RepoConfig,
required: &BTreeSet<&'a ArtifactName>,
) -> BTreeSet<&'a ArtifactName> {
config
.evals
.iter()
.filter(|eval| required.contains(&eval.target))
.flat_map(|eval| dependencies(config, eval))
.collect()
}
pub(crate) fn live_input<'a>(config: &'a RepoConfig, eval: &'a Eval) -> Option<&'a ArtifactName> {
dependencies(config, eval)
.into_iter()
.find(|name| config.artifacts[*name].kind() == crate::config::ArtifactKind::Live)
}
pub fn key(
eval_def_hash: &crate::types::DefinitionHash,
fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
) -> crate::types::ReuseKey {
let mut digest = Sha256::new();
digest.update(format!("{REUSE_KEY_FORMAT_PREFIX}eval {eval_def_hash}\n"));
for (name, fingerprint) in fingerprints {
digest.update(format!("artifact {name} {fingerprint}\n"));
}
content::hex(&digest.finalize())
.parse()
.expect("SHA-256 is a reuse key")
}
pub fn key_with_kinds(
eval_def_hash: &crate::types::DefinitionHash,
fingerprints: &BTreeMap<crate::types::ArtifactName, crate::types::Fingerprint>,
kinds: &BTreeMap<crate::types::ArtifactName, crate::config::ArtifactKind>,
) -> crate::types::ReuseKey {
if kinds.is_empty() {
return key(eval_def_hash, fingerprints);
}
let mut digest = Sha256::new();
digest.update(KIND_KEY_FORMAT_PREFIX);
digest.update(key(eval_def_hash, fingerprints).as_bytes());
digest.update(serde_json::to_vec(kinds).expect("Artifact kinds are JSON"));
content::hex(&digest.finalize())
.parse()
.expect("SHA-256 is a reuse key")
}
pub(crate) fn parts_key(value: &crate::types::ReuseKey) -> crate::types::ReuseKey {
let mut digest = Sha256::new();
digest.update(PARTS_KEY_FORMAT_PREFIX);
digest.update(value.as_bytes());
content::hex(&digest.finalize())
.parse()
.expect("SHA-256 is a reuse key")
}
pub fn eval_key(
config: &RepoConfig,
eval: &Eval,
fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
) -> Result<Key, Unkeyed> {
if matches!(eval.declaration.profile(), Profile::Runtime { .. })
&& let Some(id) = live_input(config, eval)
{
return Err(Unkeyed::LiveObservation(id.clone()));
}
if !fingerprints.contains_key(&eval.target) {
return Err(
if config.artifacts[&eval.target].kind() == crate::config::ArtifactKind::Live {
Unkeyed::LiveUnobserved(eval.target.clone())
} else {
Unkeyed::Target
},
);
}
let values = dependencies(config, eval)
.into_iter()
.map(|id| {
let fingerprint = fingerprints.get(id).ok_or_else(|| {
if config.artifacts[id].kind() == crate::config::ArtifactKind::Live {
Unkeyed::LiveUnobserved(id.clone())
} else {
Unkeyed::Dependency(id.clone())
}
})?;
Ok((id.clone(), fingerprint.value.clone()))
})
.collect::<Result<BTreeMap<_, _>, Unkeyed>>()?;
let eval_def_hash = eval_definition_hash(&eval.declaration);
let artifact_kinds = values
.keys()
.map(|id| (id.clone(), config.artifacts[id].kind()))
.collect();
let value = key_with_kinds(&eval_def_hash, &values, &artifact_kinds);
let value = if config.artifacts[&eval.target].parts.is_empty() {
value
} else {
parts_key(&value)
};
Ok(Key {
value,
eval_def_hash,
fingerprints: values,
artifact_kinds,
})
}
pub fn eval_keys<'a>(
config: &'a RepoConfig,
fingerprints: &BTreeMap<&ArtifactName, PreparedFingerprint>,
) -> BTreeMap<&'a crate::types::EvalId, Key> {
config
.evals
.iter()
.filter_map(|eval| Some((&eval.id, eval_key(config, eval, fingerprints).ok()?)))
.collect()
}