use crate::cpn::mcard_token::{PlaceMCard, TokenMCard, TransitionMCard};
use crate::cpn::token_namespace::{FiringReceiptMCard, MCardMarking, MCardTokenNamespace};
use std::collections::BTreeMap;
use crate::cpn::place_type_lattice::PlaceRole;
use crate::layer1::fractal_net_harness::{register_place_specs, PlaceSpec};
pub type CommPlaceMCard = PlaceMCard;
pub type CommTransitionPCard = TransitionMCard;
#[derive(Debug, Clone)]
pub struct CommTransferResult {
pub delivered: bool,
pub trapped_to_exception: bool,
pub marking: MCardMarking,
pub receipt: FiringReceiptMCard,
}
pub struct Layer3CommPetriNet {
pub namespace: MCardTokenNamespace,
}
impl Default for Layer3CommPetriNet {
fn default() -> Self {
Self::new()
}
}
impl Layer3CommPetriNet {
pub fn new() -> Self {
let mut namespace = MCardTokenNamespace::new("layer3_comm");
let specs = [
PlaceSpec::new("p_local_outbox", "any", PlaceRole::Intermediate),
PlaceSpec::new("p_in_transit", "any", PlaceRole::Intermediate),
PlaceSpec::new("p_remote_inbox", "any", PlaceRole::Intermediate),
PlaceSpec::new("p_comm_exception", "any", PlaceRole::Intermediate),
];
register_place_specs(&mut namespace, &specs).expect("valid comm places");
Self { namespace }
}
pub fn transport_token(
&mut self,
_marking: &MCardMarking,
token: &TokenMCard,
simulate_drop: bool,
) -> CommTransferResult {
let _ = self
.namespace
.deposit_token("p_local_outbox", token.clone(), None, None);
let tid = format!("t_comm_move:{}", token.qualified_hash());
let transition = TransitionMCard::create(
&tid,
vec!["p_local_outbox".to_string()],
vec!["p_remote_inbox".to_string()],
&token.color_type,
&token.color_type,
Some(BTreeMap::new()),
"sheaf_meet_and_verify_hash",
Some("blake3"),
None,
)
.expect("transition");
self.namespace.register_transition(transition);
let (receipt, verdict) = self
.namespace
.fire_in_cordis_fiber(
&tid,
None,
Some("p_comm_exception"),
None,
|inputs| {
if simulate_drop {
return Err("Simulated Reticulum link drop".to_string());
}
Ok(inputs[0].clone())
},
Some("blake3"),
)
.expect("fiber execution");
let committed = matches!(verdict, crate::domain::BailVerdict::Pass);
CommTransferResult {
delivered: committed,
trapped_to_exception: !committed,
marking: self.namespace.marking.clone(),
receipt,
}
}
}