use std::fmt;
use crate::hash::{ContentHash, hex, unhex};
use crate::types::DataKind;
pub const KEY_VERSION: u32 = 2;
pub const INPUT_POLICY: &str = "canonical";
const DOMAIN: &str = "ligase.step-key";
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StepKey([u8; 32]);
impl StepKey {
#[must_use]
pub fn to_hex(&self) -> String {
hex(&self.0)
}
#[must_use]
pub fn parse(text: &str) -> Option<Self> {
unhex(text).map(Self)
}
}
impl fmt::Display for StepKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.to_hex())
}
}
impl fmt::Debug for StepKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "StepKey({})", self.to_hex())
}
}
#[derive(Clone, Debug)]
pub struct Ingredients {
pub step: String,
pub code: String,
pub recipe: String,
pub output: DataKind,
pub parameters: Vec<(String, String)>,
pub inputs: Vec<(String, ContentHash)>,
pub tools: Vec<(String, String)>,
}
impl Ingredients {
#[must_use]
pub fn key(&self) -> StepKey {
let mut hasher = blake3::Hasher::new();
let mut write = |label: &str, value: &[u8]| {
field(&mut hasher, label.as_bytes());
field(&mut hasher, value);
};
write("domain", DOMAIN.as_bytes());
write("key-version", &KEY_VERSION.to_le_bytes());
write("input-policy", INPUT_POLICY.as_bytes());
write("step", self.step.as_bytes());
write("code", self.code.as_bytes());
write("recipe", self.recipe.as_bytes());
write("output", self.output.name().as_bytes());
named(&mut hasher, "parameters", &self.parameters);
named(
&mut hasher,
"inputs",
&self
.inputs
.iter()
.map(|(param, hash)| (param.clone(), hash.to_hex()))
.collect::<Vec<_>>(),
);
named(&mut hasher, "tools", &self.tools);
StepKey(*hasher.finalize().as_bytes())
}
}
fn named(hasher: &mut blake3::Hasher, label: &str, pairs: &[(String, String)]) {
let mut sorted: Vec<&(String, String)> = pairs.iter().collect();
sorted.sort_by(|left, right| left.0.cmp(&right.0).then(left.1.cmp(&right.1)));
field(hasher, label.as_bytes());
field(hasher, &(sorted.len() as u64).to_le_bytes());
for (name, value) in sorted {
field(hasher, name.as_bytes());
field(hasher, value.as_bytes());
}
}
fn field(hasher: &mut blake3::Hasher, bytes: &[u8]) {
hasher.update(&(bytes.len() as u64).to_le_bytes());
hasher.update(bytes);
}