Skip to main content

clm_rust_core/mesh/
service.rs

1//! Federated Service Catalog (`service.pkc.*`) & Dynamic Capability Routing
2//! Canonical Path: kernel/clm_rust_core/src/mesh/service.rs
3//!
4//! Implements:
5//! - DEL-258-01: Federated Service Catalog & Manifest Registry
6//! - DEL-258-02: Multi-Subnet Peer Routing Matrix & Trace Vectors
7//! - INV-258-01: Schema Conformance Witness
8//! - INV-258-02: Deterministic Routing Fallback
9//! - DOD-258-01: Capability Determinism (BLAKE3-hashed MCard manifest)
10
11use std::collections::{BTreeMap, HashMap};
12use serde::{Deserialize, Serialize};
13use crate::mesh::noise::{blake3_digest, SovereignNodeIdentity};
14
15pub const PKC_SERVICE_PREFIX: &str = "service.pkc.";
16pub const PKC_SERVICE_MDNS_TYPE: &str = "_pkc-service._tcp.local.";
17pub const PKC_CAPABILITY_MIME_TYPE: &str = crate::layer0::vocabulary_types::MIME_APPLICATION_X_CLM_CAPABILITY_JSON;
18
19// ── Types & Specifications ──────────────────────────────────────────────────
20
21#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
22pub struct PropertySchema {
23    #[serde(rename = "type")]
24    pub prop_type: String,
25    #[serde(default)]
26    pub required: bool,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub description: Option<String>,
29}
30
31#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
32pub struct SchemaSpec {
33    #[serde(rename = "type")]
34    pub schema_type: String,
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub properties: Option<BTreeMap<String, PropertySchema>>,
37    #[serde(skip_serializing_if = "Option::is_none")]
38    pub required: Option<Vec<String>>,
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub polynomial_order: Option<u32>,
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub description: Option<String>,
43}
44
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
46pub struct SlaWitness {
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub context_window: Option<u32>,
49    pub compute_type: String,
50    pub p95_latency_ms: u32,
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub throughput_tps: Option<u32>,
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub reliability_score: Option<f64>,
55}
56
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
58pub struct PricingSpec {
59    pub base_cost: f64,
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub cost_per_token: Option<f64>,
62    pub currency: String,
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66pub struct ServiceEndpoint {
67    pub protocol: String,
68    pub address: String,
69    pub port: u16,
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub noise_pubkey_hex: Option<String>,
72}
73
74#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
75pub struct ServiceCapabilityManifest {
76    pub service_id: String,
77    pub version: String,
78    pub provider_did: String,
79    pub description: String,
80    pub input_schema: SchemaSpec,
81    pub output_schema: SchemaSpec,
82    pub sla: SlaWitness,
83    pub pricing: PricingSpec,
84    pub endpoints: Vec<ServiceEndpoint>,
85    pub registered_at: u64,
86    pub ttl_seconds: u64,
87    pub content_hash: String,
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub signature: Option<String>,
90}
91
92// ── Validation & Canonicalization ───────────────────────────────────────────
93
94pub fn is_valid_service_id(service_id: &str) -> bool {
95    if !service_id.starts_with(PKC_SERVICE_PREFIX) {
96        return false;
97    }
98    let parts: Vec<&str> = service_id[PKC_SERVICE_PREFIX.len()..].split('.').collect();
99    parts.len() >= 2 && parts.iter().all(|p| !p.is_empty() && p.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-'))
100}
101
102#[derive(Serialize)]
103struct CanonicalManifest<'a> {
104    description: &'a str,
105    endpoints: &'a [ServiceEndpoint],
106    input_schema: &'a SchemaSpec,
107    output_schema: &'a SchemaSpec,
108    pricing: &'a PricingSpec,
109    provider_did: &'a str,
110    registered_at: u64,
111    service_id: &'a str,
112    sla: &'a SlaWitness,
113    ttl_seconds: u64,
114    version: &'a str,
115}
116
117pub fn canonicalize_manifest(manifest: &ServiceCapabilityManifest) -> String {
118    let canonical = CanonicalManifest {
119        description: &manifest.description,
120        endpoints: &manifest.endpoints,
121        input_schema: &manifest.input_schema,
122        output_schema: &manifest.output_schema,
123        pricing: &manifest.pricing,
124        provider_did: &manifest.provider_did,
125        registered_at: manifest.registered_at,
126        service_id: &manifest.service_id,
127        sla: &manifest.sla,
128        ttl_seconds: manifest.ttl_seconds,
129        version: &manifest.version,
130    };
131    serde_json::to_string(&canonical).unwrap_or_default()
132}
133
134pub fn compute_manifest_hash(manifest: &ServiceCapabilityManifest) -> String {
135    let canonical = canonicalize_manifest(manifest);
136    let digest = blake3_digest(canonical.as_bytes());
137    hex::encode(digest)
138}
139
140pub fn sign_capability_manifest(
141    mut manifest: ServiceCapabilityManifest,
142    identity: &SovereignNodeIdentity,
143) -> Result<ServiceCapabilityManifest, String> {
144    if !is_valid_service_id(&manifest.service_id) {
145        return Err(format!("Invalid service identifier '{}'", manifest.service_id));
146    }
147    manifest.provider_did = identity.did.clone();
148    let content_hash = compute_manifest_hash(&manifest);
149    let hash_bytes = hex::decode(&content_hash).map_err(|e| e.to_string())?;
150    let sig_bytes = identity.sign(&hash_bytes);
151    let signature = bs58::encode(sig_bytes).into_string();
152
153    manifest.content_hash = content_hash;
154    manifest.signature = Some(signature);
155    Ok(manifest)
156}
157
158pub fn verify_capability_manifest(manifest: &ServiceCapabilityManifest) -> bool {
159    if !is_valid_service_id(&manifest.service_id) {
160        return false;
161    }
162    let expected_hash = compute_manifest_hash(manifest);
163    if expected_hash != manifest.content_hash {
164        return false;
165    }
166
167    if let Some(ref sig_b58) = manifest.signature {
168        let pubkey_bytes = match SovereignNodeIdentity::did_to_public_key(&manifest.provider_did) {
169            Ok(pk) => pk,
170            Err(_) => return false,
171        };
172        let hash_bytes = match hex::decode(&manifest.content_hash) {
173            Ok(hb) => hb,
174            Err(_) => return false,
175        };
176        let sig_vec = match bs58::decode(sig_b58).into_vec() {
177            Ok(v) => v,
178            Err(_) => return false,
179        };
180        if sig_vec.len() != 64 {
181            return false;
182        }
183        let mut sig_arr = [0u8; 64];
184        sig_arr.copy_from_slice(&sig_vec);
185        return SovereignNodeIdentity::verify_signature(&pubkey_bytes, &hash_bytes, &sig_arr);
186    }
187    true
188}
189
190// ── Routing Matrix & Merkle Trace Vector ─────────────────────────────────────
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq)]
193pub enum RouteTier {
194    Local,
195    Lan,
196    Overlay,
197}
198
199#[derive(Debug, Clone)]
200pub struct RoutingCandidate {
201    pub manifest: ServiceCapabilityManifest,
202    pub tier: RouteTier,
203    pub composite_score: f64,
204    pub effective_latency_ms: u32,
205    pub reliability: f64,
206    pub cost: f64,
207}
208
209#[derive(Debug, Clone, Serialize, Deserialize)]
210pub struct RoutingTraceHop {
211    pub node_did: String,
212    pub timestamp: u64,
213    pub hop_hash: String,
214}
215
216#[derive(Debug, Clone, Serialize, Deserialize)]
217pub struct RoutingTraceVector {
218    pub trace_id: String,
219    pub origin_did: String,
220    pub hops: Vec<RoutingTraceHop>,
221}
222
223pub fn create_trace_vector(origin_did: &str, trace_id: Option<String>) -> RoutingTraceVector {
224    let id = trace_id.unwrap_or_else(|| format!("trace_{}", uuid::Uuid::new_v4()));
225    let initial_data = format!("{}:{}", id, origin_did);
226    let initial_hash = hex::encode(blake3_digest(initial_data.as_bytes()));
227
228    RoutingTraceVector {
229        trace_id: id,
230        origin_did: origin_did.to_string(),
231        hops: vec![RoutingTraceHop {
232            node_did: origin_did.to_string(),
233            timestamp: 0,
234            hop_hash: initial_hash,
235        }],
236    }
237}
238
239pub fn append_trace_hop(vector: &mut RoutingTraceVector, node_did: &str, timestamp: u64) {
240    let prev_hash = vector.hops.last().map(|h| h.hop_hash.as_str()).unwrap_or("0");
241    let hop_data = format!("{}:{}:{}", node_did, prev_hash, timestamp);
242    let hop_hash = hex::encode(blake3_digest(hop_data.as_bytes()));
243
244    vector.hops.push(RoutingTraceHop {
245        node_did: node_did.to_string(),
246        timestamp,
247        hop_hash,
248    });
249}
250
251pub fn detect_routing_loop(vector: &RoutingTraceVector, target_node_did: &str) -> bool {
252    vector.hops.iter().any(|h| h.node_did == target_node_did)
253}
254
255// ── Service Telemetry & Catalog ─────────────────────────────────────────────
256
257#[derive(Debug, Clone)]
258pub struct ServiceTelemetry {
259    pub last_seen: u64,
260    pub latency_ms: u32,
261    pub success_count: u32,
262    pub error_count: u32,
263    pub reliability: f64,
264}
265
266pub struct ServiceCatalog {
267    pub node_did: String,
268    local_services: HashMap<String, ServiceCapabilityManifest>,
269    remote_services: HashMap<String, HashMap<String, ServiceCapabilityManifest>>,
270    telemetry: HashMap<String, ServiceTelemetry>,
271}
272
273impl ServiceCatalog {
274    pub fn new(node_did: &str) -> Self {
275        Self {
276            node_did: node_did.to_string(),
277            local_services: HashMap::new(),
278            remote_services: HashMap::new(),
279            telemetry: HashMap::new(),
280        }
281    }
282
283    pub fn register_local_service(&mut self, manifest: ServiceCapabilityManifest) -> Result<(), String> {
284        if !verify_capability_manifest(&manifest) {
285            return Err(format!("Manifest for '{}' failed verification", manifest.service_id));
286        }
287        self.local_services.insert(manifest.service_id.clone(), manifest);
288        Ok(())
289    }
290
291    pub fn register_remote_service(&mut self, manifest: ServiceCapabilityManifest) -> bool {
292        if !verify_capability_manifest(&manifest) {
293            return false;
294        }
295        let service_id = manifest.service_id.clone();
296        let provider_did = manifest.provider_did.clone();
297
298        self.telemetry.entry(provider_did.clone()).or_insert_with(|| ServiceTelemetry {
299            last_seen: manifest.registered_at,
300            latency_ms: manifest.sla.p95_latency_ms,
301            success_count: 1,
302            error_count: 0,
303            reliability: manifest.sla.reliability_score.unwrap_or(1.0),
304        });
305
306        self.remote_services
307            .entry(service_id)
308            .or_default()
309            .insert(provider_did, manifest);
310        true
311    }
312
313    pub fn find_providers(&self, service_id: &str) -> Vec<ServiceCapabilityManifest> {
314        let mut results = Vec::new();
315        if let Some(local) = self.local_services.get(service_id) {
316            results.push(local.clone());
317        }
318        if let Some(remotes) = self.remote_services.get(service_id) {
319            for manifest in remotes.values() {
320                results.push(manifest.clone());
321            }
322        }
323        results
324    }
325
326    pub fn update_telemetry(&mut self, provider_did: &str, observed_latency_ms: u32, success: bool) {
327        let cur = self.telemetry.entry(provider_did.to_string()).or_insert_with(|| ServiceTelemetry {
328            last_seen: 0,
329            latency_ms: observed_latency_ms,
330            success_count: 0,
331            error_count: 0,
332            reliability: 1.0,
333        });
334
335        if success {
336            cur.success_count += 1;
337        } else {
338            cur.error_count += 1;
339        }
340        let total = cur.success_count + cur.error_count;
341        cur.reliability = if total > 0 { cur.success_count as f64 / total as f64 } else { 1.0 };
342        cur.latency_ms = ((cur.latency_ms as f64 * 0.7) + (observed_latency_ms as f64 * 0.3)) as u32;
343    }
344
345    pub fn get_telemetry(&self, provider_did: &str) -> Option<&ServiceTelemetry> {
346        self.telemetry.get(provider_did)
347    }
348
349    pub fn sweep_expired(&mut self, now: u64) -> Vec<String> {
350        let mut evicted = Vec::new();
351        for (service_id, providers) in self.remote_services.iter_mut() {
352            providers.retain(|did, manifest| {
353                let last_active = manifest.registered_at;
354                let ttl_ms = manifest.ttl_seconds * 1000;
355                if now.saturating_sub(last_active) > ttl_ms {
356                    evicted.push(format!("{}@{}", service_id, did));
357                    false
358                } else {
359                    true
360                }
361            });
362        }
363        self.remote_services.retain(|_, providers| !providers.is_empty());
364        evicted
365    }
366}
367
368// ── Service Router ──────────────────────────────────────────────────────────
369
370pub struct ServiceRouter<'a> {
371    pub catalog: &'a ServiceCatalog,
372    pub this_node_did: String,
373    pub weight_latency: f64,
374    pub weight_cost: f64,
375    pub weight_reliability: f64,
376}
377
378impl<'a> ServiceRouter<'a> {
379    pub fn new(catalog: &'a ServiceCatalog) -> Self {
380        Self {
381            catalog,
382            this_node_did: catalog.node_did.clone(),
383            weight_latency: 0.5,
384            weight_cost: 0.3,
385            weight_reliability: 0.2,
386        }
387    }
388
389    pub fn classify_tier(&self, manifest: &ServiceCapabilityManifest) -> RouteTier {
390        if manifest.provider_did == self.this_node_did {
391            return RouteTier::Local;
392        }
393        if let Some(ep) = manifest.endpoints.first() {
394            let addr = ep.address.to_lowercase();
395            if addr == "127.0.0.1" || addr == "localhost" || addr.ends_with(".local") || addr.starts_with("192.168.") || addr.starts_with("10.") {
396                return RouteTier::Lan;
397            }
398        }
399        RouteTier::Overlay
400    }
401
402    pub fn rank_candidates(&self, service_id: &str, trace: Option<&RoutingTraceVector>) -> Vec<RoutingCandidate> {
403        let manifests = self.catalog.find_providers(service_id);
404        let mut candidates = Vec::new();
405
406        for manifest in manifests {
407            if let Some(tr) = trace
408                && detect_routing_loop(tr, &manifest.provider_did) {
409                    continue;
410                }
411
412            let tier = self.classify_tier(&manifest);
413            let tele = self.catalog.get_telemetry(&manifest.provider_did);
414            let effective_latency = tele.map(|t| t.latency_ms).unwrap_or(manifest.sla.p95_latency_ms);
415            let reliability = tele.map(|t| t.reliability).unwrap_or(manifest.sla.reliability_score.unwrap_or(1.0));
416            let cost = manifest.pricing.base_cost;
417
418            let tier_multiplier = match tier {
419                RouteTier::Local => 0.4,
420                RouteTier::Lan => 1.0,
421                RouteTier::Overlay => 1.6,
422            };
423
424            let normalized_lat = effective_latency as f64 / 100.0;
425            let score = tier_multiplier * (self.weight_latency * normalized_lat + self.weight_cost * cost)
426                - self.weight_reliability * (reliability * 10.0);
427
428            candidates.push(RoutingCandidate {
429                manifest,
430                tier,
431                composite_score: score,
432                effective_latency_ms: effective_latency,
433                reliability,
434                cost,
435            });
436        }
437
438        candidates.sort_by(|a, b| a.composite_score.partial_cmp(&b.composite_score).unwrap_or(std::cmp::Ordering::Equal));
439        candidates
440    }
441
442    pub fn select_best_route(&self, service_id: &str, trace: Option<&RoutingTraceVector>) -> Option<RoutingCandidate> {
443        self.rank_candidates(service_id, trace).into_iter().next()
444    }
445}
446
447// ── Tests ───────────────────────────────────────────────────────────────────
448
449#[cfg(test)]
450#[path = "service_tests.rs"]
451mod tests;