Skip to main content

clm_rust_core/fiber/
plugin.rs

1//! Purely Functional Software Deployment (PFSD) Plugin Functors.
2//!
3//! Models a plugin as an immutable, content-addressed polynomial functor
4//! (A x C x B) in Content Addressable Storage (CAS), identified by its BLAKE3 digest.
5
6use super::context::{Context, Fiber};
7use serde::{Deserialize, Serialize};
8use serde_json::Value;
9use std::sync::Arc;
10
11#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
12pub struct PluginFunctor {
13    pub plugin_id: String,
14    pub name: String,
15    pub version: String,
16    pub abstract_spec_ref: String,
17    pub concrete_impl_ref: String,
18    pub balanced_exp_ref: String,
19    pub required_capabilities: Vec<String>,
20    pub optional_capabilities: Vec<String>,
21}
22
23impl PluginFunctor {
24    /// Computes the canonical BLAKE3 content digest for a plugin definition.
25    pub fn compute_plugin_id(
26        name: &str,
27        version: &str,
28        abstract_ref: &str,
29        concrete_ref: &str,
30        balanced_ref: &str,
31        required_caps: &[String],
32    ) -> String {
33        let mut hasher = blake3::Hasher::new();
34        hasher.update(name.as_bytes());
35        hasher.update(b"|");
36        hasher.update(version.as_bytes());
37        hasher.update(b"|");
38        hasher.update(abstract_ref.as_bytes());
39        hasher.update(b"|");
40        hasher.update(concrete_ref.as_bytes());
41        hasher.update(b"|");
42        hasher.update(balanced_ref.as_bytes());
43        for cap in required_caps {
44            hasher.update(b"|");
45            hasher.update(cap.as_bytes());
46        }
47        format!("blake3:{}", hasher.finalize().to_hex())
48    }
49
50    /// Parses and validates a PFSD plugin YAML definition.
51    pub fn from_yaml(yaml_content: &str) -> Result<Self, String> {
52        let val: Value = serde_yaml::from_str(yaml_content)
53            .map_err(|e| format!("Failed to parse plugin functor YAML: {}", e))?;
54
55        let root = val.get("clm").unwrap_or(&val);
56        let schema = root.get("concrete_impl")
57            .and_then(|c| c.get("schema"))
58            .unwrap_or(root);
59
60        let name = root.get("metadata")
61            .and_then(|m| m.get("name"))
62            .and_then(|v| v.as_str())
63            .unwrap_or("plugin-functor")
64            .to_string();
65
66        let version = root.get("metadata")
67            .and_then(|m| m.get("version"))
68            .and_then(|v| v.as_str())
69            .unwrap_or("1.0.0")
70            .to_string();
71
72        let iface = schema.get("interface");
73        let a_ref = iface.and_then(|i| i.get("abstract_spec")).and_then(|v| v.as_str()).unwrap_or("mcard:none").to_string();
74        let c_ref = iface.and_then(|i| i.get("concrete_impl")).and_then(|v| v.as_str()).unwrap_or("pcard:none").to_string();
75        let b_ref = iface.and_then(|i| i.get("balanced_exp")).and_then(|v| v.as_str()).unwrap_or("vcard:none").to_string();
76
77        let mut required_caps = Vec::new();
78        if let Some(arr) = schema.get("capabilities").and_then(|c| c.get("required")).and_then(|r| r.as_array()) {
79            for item in arr {
80                if let Some(s) = item.as_str() {
81                    required_caps.push(s.to_string());
82                }
83            }
84        }
85
86        let mut optional_caps = Vec::new();
87        if let Some(arr) = schema.get("capabilities").and_then(|c| c.get("optional")).and_then(|r| r.as_array()) {
88            for item in arr {
89                if let Some(s) = item.as_str() {
90                    optional_caps.push(s.to_string());
91                }
92            }
93        }
94
95        let computed_id = Self::compute_plugin_id(
96            &name,
97            &version,
98            &a_ref,
99            &c_ref,
100            &b_ref,
101            &required_caps,
102        );
103
104        let declared_id = schema.get("plugin_id")
105            .and_then(|v| v.as_str())
106            .unwrap_or(&computed_id);
107
108        if declared_id != computed_id && !declared_id.is_empty() && declared_id != "blake3:<digest>" {
109            return Err(format!(
110                "Content-Address Integrity Violation: Declared '{}' does not match computed '{}'",
111                declared_id, computed_id
112            ));
113        }
114
115        Ok(Self {
116            plugin_id: computed_id,
117            name,
118            version,
119            abstract_spec_ref: a_ref,
120            concrete_impl_ref: c_ref,
121            balanced_exp_ref: b_ref,
122            required_capabilities: required_caps,
123            optional_capabilities: optional_caps,
124        })
125    }
126
127    /// Verifies that all required capabilities exist in the context's dependency lattice.
128    pub fn verify_dependency_lattice(&self, ctx: &Context) -> Result<bool, String> {
129        let mut missing = Vec::new();
130        for cap in &self.required_capabilities {
131            if !ctx.require(cap) {
132                missing.push(cap.clone());
133            }
134        }
135        if missing.is_empty() {
136            Ok(true)
137        } else {
138            Err(format!("Dependency lattice unsatisfied; missing capabilities: {:?}", missing))
139        }
140    }
141
142    /// Mounts the plugin as a Fiber in the provided context scope.
143    pub fn mount(&self, ctx: &Context) -> Result<Arc<Fiber>, String> {
144        self.verify_dependency_lattice(ctx)?;
145        let fiber = ctx.create_fiber(&self.plugin_id, self.required_capabilities.clone())?;
146        fiber.activate()?;
147        Ok(fiber)
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::*;
154
155    #[test]
156    fn test_plugin_functor_from_yaml_and_blake3_integrity() {
157        let yaml = r#"
158clm:
159  metadata:
160    name: "kv-storage-plugin"
161    version: "2.1.0"
162  concrete_impl:
163    schema:
164      interface:
165        abstract_spec: "mcard:sha256:abc"
166        concrete_impl: "pcard:sha256:def"
167        balanced_exp: "vcard:sha256:ghi"
168      capabilities:
169        required: ["clm.tridb.read", "clm.crypto.sign"]
170        optional: ["clm.net.broadcast"]
171"#;
172
173        let plugin = PluginFunctor::from_yaml(yaml).unwrap();
174        assert!(plugin.plugin_id.starts_with("blake3:"));
175        assert_eq!(plugin.name, "kv-storage-plugin");
176        assert_eq!(plugin.version, "2.1.0");
177        assert_eq!(plugin.required_capabilities.len(), 2);
178    }
179
180    #[test]
181    fn test_plugin_dependency_lattice_and_mounting() {
182        let yaml = r#"
183clm:
184  metadata:
185    name: "auth-plugin"
186    version: "1.0.0"
187  concrete_impl:
188    schema:
189      capabilities:
190        required: ["clm.crypto.sign"]
191"#;
192
193        let plugin = PluginFunctor::from_yaml(yaml).unwrap();
194        let ctx = Context::root();
195
196        // Mounting before capability provided should fail lattice check
197        assert!(plugin.mount(&ctx).is_err());
198
199        // Provide capability and retry mount
200        ctx.provide("clm.crypto.sign", "mock_key".to_string());
201        assert!(plugin.verify_dependency_lattice(&ctx).is_ok());
202
203        let fiber = plugin.mount(&ctx).unwrap();
204        assert_eq!(fiber.get_state(), crate::fiber::FiberState::Active);
205    }
206}