use std::collections::{BTreeMap, BTreeSet};
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LayerView {
pub includes: Vec<Include>,
pub tools: Vec<String>,
}
pub fn view(bytes: &[u8]) -> Result<LayerView, ComposeError> {
let json: serde_json::Value =
serde_json::from_slice(bytes).map_err(|e| ComposeError::Unreadable(e.to_string()))?;
let mut v = LayerView::default();
let Some(entries) = json["manifests"].as_array() else {
return Ok(v);
};
for e in entries {
let ann = &e["annotations"];
let digest = e["digest"].as_str().unwrap_or_default().to_string();
match ann[crate::kind::ANN_KIND].as_str() {
Some("layer") => v.includes.push(Include {
digest,
realm: ann[ANN_INCLUDE_REALM].as_str().map(|s| s.to_string()),
layer: ann[ANN_INCLUDE_LAYER].as_str().map(|s| s.to_string()),
}),
None => {
if let Some(t) = ann["eu.pulseengine.tool"].as_str() {
v.tools.push(t.to_string());
}
}
Some(_) => {}
}
}
Ok(v)
}
pub const ANN_INCLUDE_REALM: &str = "eu.pulseengine.varve.include.realm";
pub const ANN_INCLUDE_LAYER: &str = "eu.pulseengine.varve.include.layer";
pub const MAX_DEPTH: usize = 8;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Include {
pub digest: String,
pub realm: Option<String>,
pub layer: Option<String>,
}
#[derive(Debug, thiserror::Error)]
pub enum ComposeError {
#[error(
"composition cycle: layer {digest} includes itself, directly or through \
{via} — refusing to follow it"
)]
Cycle { digest: String, via: String },
#[error(
"composition is more than {MAX_DEPTH} layers deep — refusing to walk further \
(a layer graph this deep is a mistake, not a design)"
)]
TooDeep,
#[error("layer manifest could not be read for composition: {0}")]
Unreadable(String),
#[error(
"tool '{tool}' is exposed by more than one layer in this composition \
({first} and {second}) — refusing to choose. Restrict the pin's `tools`, \
or remove the duplicate from one layer."
)]
AmbiguousTool {
tool: String,
first: String,
second: String,
},
}
pub fn includes(v: &LayerView) -> Vec<Include> {
v.includes.clone()
}
pub fn walk<F>(
root_digest: &str,
root: &LayerView,
mut fetch: F,
) -> Result<Vec<(String, LayerView)>, ComposeError>
where
F: FnMut(&str) -> Option<LayerView>,
{
let mut out = vec![(root_digest.to_string(), root.clone())];
let mut emitted: BTreeSet<String> = BTreeSet::new();
emitted.insert(root_digest.to_string());
let mut stack: Vec<(String, LayerView, BTreeSet<String>)> = vec![(
root_digest.to_string(),
root.clone(),
BTreeSet::from([root_digest.to_string()]),
)];
while let Some((from, view, path)) = stack.pop() {
if path.len() > MAX_DEPTH {
return Err(ComposeError::TooDeep);
}
for inc in includes(&view) {
if path.contains(&inc.digest) {
return Err(ComposeError::Cycle {
digest: inc.digest.clone(),
via: from.clone(),
});
}
let Some(child) = fetch(&inc.digest) else {
continue;
};
if emitted.insert(inc.digest.clone()) {
out.push((inc.digest.clone(), child.clone()));
}
let mut child_path = path.clone();
child_path.insert(inc.digest.clone());
stack.push((inc.digest.clone(), child, child_path));
}
}
Ok(out)
}
pub fn union_tools(
layers: &[(String, LayerView)],
) -> Result<BTreeMap<String, String>, ComposeError> {
let mut owner: BTreeMap<String, String> = BTreeMap::new();
for (digest, v) in layers {
for tool in &v.tools {
if let Some(first) = owner.get(tool)
&& first != digest
{
return Err(ComposeError::AmbiguousTool {
tool: tool.clone(),
first: first.clone(),
second: digest.clone(),
});
}
owner.insert(tool.clone(), digest.clone());
}
}
Ok(owner)
}
#[cfg(test)]
mod tests {
use super::*;
fn manifest(layer: &str, tools: &[&str], includes: &[(&str, &str)]) -> LayerView {
let mut entries: Vec<String> = tools
.iter()
.map(|t| {
format!(
r#"{{"digest":"sha256:{t}","annotations":{{"eu.pulseengine.tool":"{t}"}}}}"#
)
})
.collect();
for (digest, realm) in includes {
entries.push(format!(
r#"{{"digest":"{digest}","annotations":{{"eu.pulseengine.varve.kind":"layer","{ANN_INCLUDE_REALM}":"{realm}"}}}}"#
));
}
let json = format!(
r#"{{"schemaVersion":2,"mediaType":"application/vnd.oci.image.index.v1+json",
"artifactType":"application/vnd.pulseengine.varve.layer.v1+json",
"annotations":{{"eu.pulseengine.varve.layer":"{layer}","eu.pulseengine.varve.channel":"qualified",
"eu.pulseengine.varve.counter":"1","org.opencontainers.image.created":"2026-08-01T00:00:00Z"}},
"manifests":[{}]}}"#,
entries.join(",")
);
let _ = layer;
view(json.as_bytes()).unwrap()
}
#[test]
fn a_composition_exposes_both_layers_tools() {
let upstream = manifest("2026.08.0", &["wasm-tools", "cargo-component"], &[]);
let root = manifest(
"2026.08.0",
&["rivet", "meld"],
&[("sha256:up", "bytecodealliance")],
);
let inc = includes(&root);
assert_eq!(inc.len(), 1);
assert_eq!(inc[0].digest, "sha256:up");
assert_eq!(inc[0].realm.as_deref(), Some("bytecodealliance"));
let layers = walk("sha256:root", &root, |d| {
(d == "sha256:up").then(|| upstream.clone())
})
.unwrap();
assert_eq!(layers.len(), 2, "root plus the included layer");
let tools = union_tools(&layers).unwrap();
for t in ["rivet", "meld", "wasm-tools", "cargo-component"] {
assert!(tools.contains_key(t), "{t} missing from the composition");
}
assert_eq!(tools["wasm-tools"], "sha256:up");
assert_eq!(tools["rivet"], "sha256:root");
}
#[test]
fn a_tool_in_two_layers_is_an_error_not_a_silent_choice() {
let upstream = manifest("2026.08.0", &["wasm-tools"], &[]);
let root = manifest(
"2026.08.0",
&["wasm-tools"],
&[("sha256:up", "bytecodealliance")],
);
let layers = walk("sha256:root", &root, |d| {
(d == "sha256:up").then(|| upstream.clone())
})
.unwrap();
match union_tools(&layers) {
Err(ComposeError::AmbiguousTool { tool, .. }) => assert_eq!(tool, "wasm-tools"),
other => panic!("expected AmbiguousTool, got {other:?}"),
}
}
#[test]
fn depth_is_bounded_so_a_long_chain_cannot_exhaust_the_walker() {
let leaf = manifest("2026.08.0", &["leaf"], &[]);
let chain: Vec<LayerView> = (0..=MAX_DEPTH + 2)
.map(|i| manifest("2026.08.0", &["t"], &[(&format!("sha256:{}", i + 1), "r")]))
.collect();
let err = walk("sha256:0", &chain[0], |d| {
let n: usize = d.trim_start_matches("sha256:").parse().ok()?;
chain.get(n).cloned().or_else(|| Some(leaf.clone()))
})
.unwrap_err();
assert!(matches!(err, ComposeError::TooDeep), "got {err:?}");
}
#[test]
fn a_diamond_is_walked_once_not_refused_as_a_cycle() {
let d = manifest("2026.08.0", &["base"], &[]);
let b = manifest("2026.08.0", &["b"], &[("sha256:d", "r")]);
let c = manifest("2026.08.0", &["c"], &[("sha256:d", "r")]);
let a = manifest("2026.08.0", &["a"], &[("sha256:b", "r"), ("sha256:c", "r")]);
let walked = walk("sha256:a", &a, |q| match q {
"sha256:b" => Some(b.clone()),
"sha256:c" => Some(c.clone()),
"sha256:d" => Some(d.clone()),
_ => None,
})
.unwrap();
assert_eq!(walked.len(), 4, "A, B, C and D each once: {walked:?}");
let tools = union_tools(&walked).unwrap();
assert_eq!(tools["base"], "sha256:d");
}
#[test]
fn a_cycle_is_refused_not_followed() {
let a = manifest("2026.08.0", &["x"], &[("sha256:b", "r")]);
let b = manifest("2026.08.0", &["y"], &[("sha256:a", "r")]);
let (ac, bc) = (a.clone(), b.clone());
let err = walk("sha256:a", &a, move |d| match d {
"sha256:b" => Some(bc.clone()),
"sha256:a" => Some(ac.clone()),
_ => None,
})
.unwrap_err();
assert!(matches!(err, ComposeError::Cycle { .. }), "got {err:?}");
}
#[test]
fn an_uninstalled_include_is_skipped_for_the_caller_to_report() {
let root = manifest("2026.08.0", &["rivet"], &[("sha256:missing", "other")]);
let layers = walk("sha256:root", &root, |_| None).unwrap();
assert_eq!(layers.len(), 1, "only the root resolved");
assert_eq!(
includes(&root).len(),
1,
"but the include is still declared"
);
}
#[test]
fn a_layer_without_includes_composes_to_itself() {
let plain = manifest("2026.08.0", &["rivet", "meld"], &[]);
assert!(includes(&plain).is_empty());
let layers = walk("sha256:root", &plain, |_| None).unwrap();
assert_eq!(layers.len(), 1);
assert_eq!(union_tools(&layers).unwrap().len(), 2);
}
}