use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::time::Instant;
use crate::fiber::{Fiber, FiberState};
use crate::layer0::mcard_record::{create_record, MCardRecord};
use crate::layer1::types::{Marking, PetriNet};
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PcardData {
pub function_id: String,
pub pcard_hash: String,
pub abstract_face: serde_json::Value,
pub concrete_face: serde_json::Value,
pub balanced_face: serde_json::Value,
}
#[derive(Debug, Clone)]
pub struct TransitionExecutionOutcome {
pub transition_id: String,
pub function_id: String,
pub success: bool,
pub record_hash: Option<String>,
pub latency_ms: f64,
pub state_history: Vec<FiberState>,
pub error: Option<String>,
}
pub struct TransitionLoader {
pub pool_db_path: PathBuf,
}
impl TransitionLoader {
pub fn new(pool_db_path: impl Into<PathBuf>) -> Self {
Self {
pool_db_path: pool_db_path.into(),
}
}
pub fn default_pool() -> Self {
let candidates = [
PathBuf::from("clm/db/layer0_function_memory.mcard.db"),
PathBuf::from("../../db/layer0_function_memory.mcard.db"),
PathBuf::from("../db/layer0_function_memory.mcard.db"),
];
let found = candidates.into_iter().find(|p| p.exists()).unwrap_or_else(|| {
PathBuf::from("clm/db/layer0_function_memory.mcard.db")
});
Self::new(found)
}
pub fn resolve_pcard(&self, function_id: &str) -> Result<PcardData, String> {
if !self.pool_db_path.exists() {
return Err(format!("Function memory DB not found: {:?}", self.pool_db_path));
}
let conn = rusqlite::Connection::open_with_flags(
&self.pool_db_path,
rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY,
)
.map_err(|e| format!("Failed to open DB: {}", e))?;
let mut stmt = conn
.prepare("SELECT current_hash FROM handle_registry WHERE handle = ?")
.map_err(|e| format!("Prepare error: {}", e))?;
let mut hash_res: Result<String, _> = stmt.query_row([function_id], |row| row.get(0));
if hash_res.is_err() {
if function_id == crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_CREATE_RECORD {
hash_res = stmt.query_row([crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_RECORD_CREATE_RECORD], |row| row.get(0));
} else if function_id == crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_RECORD_CREATE_RECORD {
hash_res = stmt.query_row([crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_CREATE_RECORD], |row| row.get(0));
}
}
let pcard_hash = hash_res.map_err(|_| format!("Function handle '{}' not found in handle_registry", function_id))?;
let mut card_stmt = conn
.prepare("SELECT content FROM card WHERE hash = ?")
.map_err(|e| format!("Card prepare error: {}", e))?;
let card_raw: Vec<u8> = card_stmt
.query_row([&pcard_hash], |row| row.get(0))
.map_err(|e| format!("Root card '{}' missing: {}", pcard_hash, e))?;
let root_val: serde_json::Value = serde_json::from_slice(&card_raw)
.map_err(|e| format!("Failed to parse root card JSON: {}", e))?;
let faces = root_val
.get("payload")
.and_then(|p| p.get("faces"))
.and_then(|f| f.as_object())
.ok_or_else(|| "PCard missing required faces object".to_string())?;
let mut resolved_faces: HashMap<String, serde_json::Value> = HashMap::new();
for (aspect, q_hash_val) in faces {
let q_hash = q_hash_val.as_str().unwrap_or("");
let bare_hash = if let Some((_, h)) = q_hash.split_once(':') {
h
} else {
q_hash
};
if let Ok(f_raw) = card_stmt.query_row([bare_hash], |row| row.get::<_, Vec<u8>>(0)) {
if let Ok(f_val) = serde_json::from_slice(&f_raw) {
resolved_faces.insert(aspect.clone(), f_val);
}
}
}
Ok(PcardData {
function_id: function_id.to_string(),
pcard_hash,
abstract_face: resolved_faces.remove("abstract").unwrap_or(serde_json::Value::Null),
concrete_face: resolved_faces.remove("concrete").unwrap_or(serde_json::Value::Null),
balanced_face: resolved_faces.remove("balanced").unwrap_or(serde_json::Value::Null),
})
}
pub fn invoke_create_record(
&self,
content: &[u8],
algorithm: Option<&str>,
) -> Result<MCardRecord, String> {
create_record(content, algorithm)
}
pub fn validate_bipartite(net: &PetriNet) -> Result<(), String> {
let place_ids: HashSet<&str> = net.places.iter().map(|p| p.id.as_str()).collect();
let trans_ids: HashSet<&str> = net.transitions.iter().map(|t| t.id.as_str()).collect();
let overlap: Vec<&&str> = place_ids.intersection(&trans_ids).collect();
if !overlap.is_empty() {
return Err(format!("Partition overlap: {:?} declared as both Place and Transition", overlap));
}
for trans in &net.transitions {
for inp in &trans.inputs {
if trans_ids.contains(inp.as_str()) {
return Err(format!(
"Bipartite violation: Transition '{}' connects directly to Transition '{}'",
trans.id, inp
));
}
if !place_ids.contains(inp.as_str()) {
return Err(format!(
"Transition '{}' references unknown input Place '{}'",
trans.id, inp
));
}
}
for outp in &trans.outputs {
if trans_ids.contains(outp.as_str()) {
return Err(format!(
"Bipartite violation: Transition '{}' connects directly to Transition '{}'",
trans.id, outp
));
}
if !place_ids.contains(outp.as_str()) {
return Err(format!(
"Transition '{}' references unknown output Place '{}'",
trans.id, outp
));
}
}
}
Ok(())
}
pub fn fire_transition(
&self,
net: &PetriNet,
marking: &mut Marking,
transition_id: &str,
input_payload: &[u8],
planted_error: bool,
) -> Result<TransitionExecutionOutcome, String> {
Self::validate_bipartite(net)?;
let trans = net
.transitions
.iter()
.find(|t| t.id == transition_id)
.ok_or_else(|| format!("Transition '{}' not found in net", transition_id))?;
for in_place in &trans.inputs {
let count = marking.get(in_place).copied().unwrap_or(0);
if count < 1 {
return Err(format!(
"Transition '{}' not enabled: input place '{}' has 0 tokens",
transition_id, in_place
));
}
}
let fiber = Fiber::new(
format!("fiber_{}_{}", transition_id, uuid::Uuid::new_v4()),
vec!["@Inject::Context".to_string()],
);
let mut state_history = vec![fiber.get_state()];
let start_time = Instant::now();
fiber.transition_to(FiberState::Loading)?;
state_history.push(fiber.get_state());
fiber.transition_to(FiberState::Active)?;
state_history.push(fiber.get_state());
if planted_error {
let _ = fiber.transition_to(FiberState::Unloading);
state_history.push(fiber.get_state());
let _ = fiber.transition_to(FiberState::Disposed);
state_history.push(fiber.get_state());
let latency_ms = start_time.elapsed().as_secs_f64() * 1000.0;
return Ok(TransitionExecutionOutcome {
transition_id: transition_id.to_string(),
function_id: crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_RECORD_CREATE_RECORD.to_string(),
success: false,
record_hash: None,
latency_ms,
state_history,
error: Some("Planted failure in transition execution".to_string()),
});
}
let record = create_record(input_payload, None)?;
fiber.transition_to(FiberState::Unloading)?;
state_history.push(fiber.get_state());
for in_place in &trans.inputs {
let count = marking.get_mut(in_place).unwrap();
*count -= 1;
}
for outp in &trans.outputs {
let count = marking.entry(outp.clone()).or_insert(0);
*count += 1;
}
fiber.transition_to(FiberState::Disposed)?;
state_history.push(fiber.get_state());
let latency_ms = start_time.elapsed().as_secs_f64() * 1000.0;
Ok(TransitionExecutionOutcome {
transition_id: transition_id.to_string(),
function_id: crate::layer0::vocabulary::HANDLE_URN_MCARD_CAS_MCARD_RECORD_CREATE_RECORD.to_string(),
success: true,
record_hash: Some(record.hash),
latency_ms,
state_history,
error: None,
})
}
}