use crate::layer0::vocabulary::{URI_SCHEME_MCARD};
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use crate::domain::{CordisCoeffects, DynamicPCard};
use crate::layer0::mcard_record::MCardRecord;
use crate::types::ContentHash;
use super::token_models::{qualified_record_hash, record_from_canonical_json, TokenMCard};
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(transparent)]
pub struct TransitionMCard(TransitionMCardData);
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransitionMCardData {
pub card: MCardRecord,
pub transition_id: String,
pub input_places: Vec<String>,
pub output_places: Vec<String>,
pub domain_type: String,
pub codomain_type: String,
pub coeffects: BTreeMap<String, String>,
pub operation_expr: String,
}
impl std::ops::Deref for TransitionMCard {
type Target = TransitionMCardData;
fn deref(&self) -> &Self::Target { &self.0 }
}
impl<'de> Deserialize<'de> for TransitionMCard {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let model = Self(TransitionMCardData::deserialize(deserializer)?);
if model.verify() { Ok(model) } else { Err(serde::de::Error::custom("MCard view differs from its verified record")) }
}
}
impl TransitionMCard {
const KIND: &'static str = "transition_mcard";
pub fn default_coeffect_map() -> BTreeMap<String, String> {
let mut m = BTreeMap::new();
for axis in ["filesystem", "network", "random", "sqlite", "time"] {
m.insert(axis.to_string(), "none".to_string());
}
m
}
pub fn create(
transition_id: &str,
input_places: Vec<String>,
output_places: Vec<String>,
domain_type: &str,
codomain_type: &str,
coeffects: Option<BTreeMap<String, String>>,
operation_expr: &str,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Self, String> {
let coeff = coeffects.unwrap_or_else(Self::default_coeffect_map);
let envelope = json!({
"codomain_type": codomain_type,
"coeffects": coeff,
"domain_type": domain_type,
"input_places": input_places,
"kind": Self::KIND,
"operation_expr": operation_expr,
"output_places": output_places,
"transition_id": transition_id,
});
let card = record_from_canonical_json(&envelope, algorithm, timestamp)?;
Ok(Self(TransitionMCardData {
card,
transition_id: transition_id.to_string(),
input_places,
output_places,
domain_type: domain_type.to_string(),
codomain_type: codomain_type.to_string(),
coeffects: coeff,
operation_expr: operation_expr.to_string(),
}))
}
pub fn hash(&self) -> &str {
&self.card.hash
}
pub fn qualified_hash(&self) -> String {
qualified_record_hash(&self.card).expect("immutable verified MCard")
}
pub fn verify(&self) -> bool {
super::token_models::verify_envelope(&self.card, self, Self::KIND)
}
pub fn as_dynamic_pcard(&self) -> Result<DynamicPCard, String> {
let services: Vec<String> = self
.coeffects
.iter()
.filter(|(_, mode)| mode.as_str() != "none")
.map(|(k, v)| format!("{k}:{v}"))
.collect();
Ok(DynamicPCard {
id: self.transition_id.clone(),
code_hash: ContentHash::parse(&self.card.hash).map_err(|e| e.to_string())?,
source_uri: format!("{URI_SCHEME_MCARD}{}", self.qualified_hash()),
coeffects: CordisCoeffects {
required_services: services,
input_schema_uri: Some(self.domain_type.clone()),
output_schema_uri: Some(self.codomain_type.clone()),
required_capabilities: Vec::new(),
},
signature: format!("{} -> {}", self.domain_type, self.codomain_type),
})
}
pub fn fire<F>(
&self,
input_tokens: &[TokenMCard],
transform: F,
algorithm: Option<&str>,
timestamp: Option<&str>,
) -> Result<Vec<TokenMCard>, String>
where
F: Fn(&[Value]) -> Value,
{
let declared_algorithm = super::token_models::record_algorithm(&self.card)?;
let algo = algorithm.unwrap_or(&declared_algorithm);
let raw_inputs: Vec<Value> = input_tokens.iter().map(|t| t.payload.clone()).collect();
let out_payload = transform(&raw_inputs);
let out_count = self.output_places.len().max(1);
let mut produced = Vec::with_capacity(out_count);
for idx in 0..out_count {
produced.push(TokenMCard::from_payload(
out_payload.clone(),
&self.codomain_type,
&format!("{}_out_{idx}", self.transition_id),
Some(algo),
timestamp,
)?);
}
Ok(produced)
}
}