use super::context::{Context, Fiber};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PluginFunctor {
pub plugin_id: String,
pub name: String,
pub version: String,
pub abstract_spec_ref: String,
pub concrete_impl_ref: String,
pub balanced_exp_ref: String,
pub required_capabilities: Vec<String>,
pub optional_capabilities: Vec<String>,
}
impl PluginFunctor {
pub fn compute_plugin_id(
name: &str,
version: &str,
abstract_ref: &str,
concrete_ref: &str,
balanced_ref: &str,
required_caps: &[String],
) -> String {
let mut hasher = blake3::Hasher::new();
hasher.update(name.as_bytes());
hasher.update(b"|");
hasher.update(version.as_bytes());
hasher.update(b"|");
hasher.update(abstract_ref.as_bytes());
hasher.update(b"|");
hasher.update(concrete_ref.as_bytes());
hasher.update(b"|");
hasher.update(balanced_ref.as_bytes());
for cap in required_caps {
hasher.update(b"|");
hasher.update(cap.as_bytes());
}
format!("blake3:{}", hasher.finalize().to_hex())
}
pub fn from_yaml(yaml_content: &str) -> Result<Self, String> {
let val: Value = serde_yaml::from_str(yaml_content)
.map_err(|e| format!("Failed to parse plugin functor YAML: {}", e))?;
let root = val.get("clm").unwrap_or(&val);
let schema = root.get("concrete_impl")
.and_then(|c| c.get("schema"))
.unwrap_or(root);
let name = root.get("metadata")
.and_then(|m| m.get("name"))
.and_then(|v| v.as_str())
.unwrap_or("plugin-functor")
.to_string();
let version = root.get("metadata")
.and_then(|m| m.get("version"))
.and_then(|v| v.as_str())
.unwrap_or("1.0.0")
.to_string();
let iface = schema.get("interface");
let a_ref = iface.and_then(|i| i.get("abstract_spec")).and_then(|v| v.as_str()).unwrap_or("mcard:none").to_string();
let c_ref = iface.and_then(|i| i.get("concrete_impl")).and_then(|v| v.as_str()).unwrap_or("pcard:none").to_string();
let b_ref = iface.and_then(|i| i.get("balanced_exp")).and_then(|v| v.as_str()).unwrap_or("vcard:none").to_string();
let mut required_caps = Vec::new();
if let Some(arr) = schema.get("capabilities").and_then(|c| c.get("required")).and_then(|r| r.as_array()) {
for item in arr {
if let Some(s) = item.as_str() {
required_caps.push(s.to_string());
}
}
}
let mut optional_caps = Vec::new();
if let Some(arr) = schema.get("capabilities").and_then(|c| c.get("optional")).and_then(|r| r.as_array()) {
for item in arr {
if let Some(s) = item.as_str() {
optional_caps.push(s.to_string());
}
}
}
let computed_id = Self::compute_plugin_id(
&name,
&version,
&a_ref,
&c_ref,
&b_ref,
&required_caps,
);
let declared_id = schema.get("plugin_id")
.and_then(|v| v.as_str())
.unwrap_or(&computed_id);
if declared_id != computed_id && !declared_id.is_empty() && declared_id != "blake3:<digest>" {
return Err(format!(
"Content-Address Integrity Violation: Declared '{}' does not match computed '{}'",
declared_id, computed_id
));
}
Ok(Self {
plugin_id: computed_id,
name,
version,
abstract_spec_ref: a_ref,
concrete_impl_ref: c_ref,
balanced_exp_ref: b_ref,
required_capabilities: required_caps,
optional_capabilities: optional_caps,
})
}
pub fn verify_dependency_lattice(&self, ctx: &Context) -> Result<bool, String> {
let mut missing = Vec::new();
for cap in &self.required_capabilities {
if !ctx.require(cap) {
missing.push(cap.clone());
}
}
if missing.is_empty() {
Ok(true)
} else {
Err(format!("Dependency lattice unsatisfied; missing capabilities: {:?}", missing))
}
}
pub fn mount(&self, ctx: &Context) -> Result<Arc<Fiber>, String> {
self.verify_dependency_lattice(ctx)?;
let fiber = ctx.create_fiber(&self.plugin_id, self.required_capabilities.clone())?;
fiber.activate()?;
Ok(fiber)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_plugin_functor_from_yaml_and_blake3_integrity() {
let yaml = r#"
clm:
metadata:
name: "kv-storage-plugin"
version: "2.1.0"
concrete_impl:
schema:
interface:
abstract_spec: "mcard:sha256:abc"
concrete_impl: "pcard:sha256:def"
balanced_exp: "vcard:sha256:ghi"
capabilities:
required: ["clm.tridb.read", "clm.crypto.sign"]
optional: ["clm.net.broadcast"]
"#;
let plugin = PluginFunctor::from_yaml(yaml).unwrap();
assert!(plugin.plugin_id.starts_with("blake3:"));
assert_eq!(plugin.name, "kv-storage-plugin");
assert_eq!(plugin.version, "2.1.0");
assert_eq!(plugin.required_capabilities.len(), 2);
}
#[test]
fn test_plugin_dependency_lattice_and_mounting() {
let yaml = r#"
clm:
metadata:
name: "auth-plugin"
version: "1.0.0"
concrete_impl:
schema:
capabilities:
required: ["clm.crypto.sign"]
"#;
let plugin = PluginFunctor::from_yaml(yaml).unwrap();
let ctx = Context::root();
assert!(plugin.mount(&ctx).is_err());
ctx.provide("clm.crypto.sign", "mock_key".to_string());
assert!(plugin.verify_dependency_lattice(&ctx).is_ok());
let fiber = plugin.mount(&ctx).unwrap();
assert_eq!(fiber.get_state(), crate::fiber::FiberState::Active);
}
}