use crate::cpn::mcard_token::{NetMCard, TokenMCard};
use crate::cpn::token_namespace::{FiringReceiptMCard, MCardMarking, MCardTokenNamespace};
use crate::layer2::petri_process::MCardNamespaceProtocolService;
use crate::layer2::vfs::DirectoryManifest;
use std::collections::{BTreeMap, BTreeSet};
pub struct MCardHostMountAdapter {
pub service: MCardNamespaceProtocolService,
pub sponsor_did: String,
}
impl Default for MCardHostMountAdapter {
fn default() -> Self {
Self::new()
}
}
impl MCardHostMountAdapter {
pub fn new() -> Self {
Self {
service: MCardNamespaceProtocolService::new_in_memory(),
sponsor_did: crate::layer0::vocabulary_identities::DID_KEY_Z6MKRUSTHOSTMOUNT.to_string(),
}
}
pub fn put_file(&self, path: &str, content: &[u8]) -> Result<String, String> {
let res = self
.service
.put(path, content, Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3), Some(&self.sponsor_did));
if !res.committed {
return Err("put_file failed".to_string());
}
Ok(res.payload["qualified_ref"]
.as_str()
.unwrap_or_default()
.to_string())
}
pub fn cat(&self, path: &str) -> Result<Vec<u8>, String> {
self.service
.fs
.read_raw_bytes(path)
.map_err(|e| e.to_string())
}
pub fn ls(&self, prefix: &str) -> Result<Vec<String>, String> {
let res = self.service.list(prefix, Some(&self.sponsor_did));
if !res.committed {
return Err("ls failed".to_string());
}
let arr = res.payload["items"]
.as_array()
.cloned()
.unwrap_or_default();
Ok(arr
.into_iter()
.filter_map(|v| v.as_str().map(|s| s.to_string()))
.collect())
}
pub fn mkdir(&self, dir_path: &str) -> Result<String, String> {
let manifest = DirectoryManifest::new(Vec::new(), Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3));
self.put_file(dir_path, &manifest.to_canonical_bytes())
}
pub fn cp(&mut self, src_path: &str, dst_path: &str) -> Result<String, String> {
let resolved = self.service.resolve(src_path, Some(&self.sponsor_did));
if !resolved.committed {
return Err(format!("Source '{src_path}' not found"));
}
let qref = resolved.payload["qualified_ref"]
.as_str()
.unwrap_or_default()
.to_string();
let dst_res = self.service.resolve(dst_path, Some(&self.sponsor_did));
let expected_old = if dst_res.committed {
dst_res.payload["qualified_ref"]
.as_str()
.map(|s| s.to_string())
} else {
None
};
let bnd = self.service.bind(
dst_path,
&qref,
expected_old.as_deref(),
Some(&self.sponsor_did),
);
if !bnd.committed {
return Err(format!("cp bind failed for '{dst_path}'"));
}
Ok(qref)
}
pub fn mv(&mut self, src_path: &str, dst_path: &str) -> Result<String, String> {
let qref = self.cp(src_path, dst_path)?;
self.rm(src_path)?;
Ok(qref)
}
pub fn rm(&self, path: &str) -> Result<(), String> {
self.service
.fs
.delete_file(path)
.map_err(|e| e.to_string())
}
}
pub struct NamespaceUnionMount {
mounts: Vec<(String, MCardHostMountAdapter)>,
}
impl Default for NamespaceUnionMount {
fn default() -> Self {
Self::new()
}
}
impl NamespaceUnionMount {
pub fn new() -> Self {
Self { mounts: Vec::new() }
}
pub fn add_mount(&mut self, name: &str, adapter: MCardHostMountAdapter) -> Result<(), String> {
let mut existing = BTreeSet::new();
for (_, m) in &self.mounts {
for h in m.ls(crate::layer0::vocabulary::HANDLE_MCARD)? {
existing.insert(h);
}
}
let incoming = adapter.ls(crate::layer0::vocabulary::HANDLE_MCARD)?;
for h in &incoming {
if existing.contains(h) {
return Err(format!(
"Namespace union collision detected (Meet != bottom) on handle '{h}'"
));
}
}
self.mounts.push((name.to_string(), adapter));
Ok(())
}
pub fn ls_union(&self, prefix: &str) -> Result<Vec<String>, String> {
let mut seen = BTreeSet::new();
for (_, m) in &self.mounts {
for h in m.ls(prefix)? {
if !seen.insert(h.clone()) {
return Err(format!("Runtime union collision on '{h}'"));
}
}
}
Ok(seen.into_iter().collect())
}
pub fn cat_union(&self, path: &str) -> Result<Vec<u8>, String> {
let mut found: Vec<Vec<u8>> = Vec::new();
for (_, m) in &self.mounts {
if let Ok(bytes) = m.cat(path) {
found.push(bytes);
}
}
match found.len() {
0 => Err(format!("Handle '{path}' not found in union namespace")),
1 => Ok(found.remove(0)),
_ => Err(format!("Ambiguous collision on '{path}' across union mounts")),
}
}
}
pub struct Layer1NetCollectionServer {
pub net_id: String,
pub namespace: MCardTokenNamespace,
pub adapter: MCardHostMountAdapter,
pub firings: BTreeMap<String, FiringReceiptMCard>,
}
impl Layer1NetCollectionServer {
pub fn new(net_id: &str) -> Self {
Self {
net_id: net_id.to_string(),
namespace: MCardTokenNamespace::new(net_id),
adapter: MCardHostMountAdapter::new(),
firings: BTreeMap::new(),
}
}
pub fn with_namespace(
net_id: &str,
namespace: MCardTokenNamespace,
adapter: Option<MCardHostMountAdapter>,
) -> Self {
Self {
net_id: net_id.to_string(),
namespace,
adapter: adapter.unwrap_or_default(),
firings: BTreeMap::new(),
}
}
pub fn marking(&self) -> &MCardMarking {
&self.namespace.marking
}
pub fn base_uri(&self) -> String {
format!("ns/{}", self.net_id)
}
pub fn record_firing(&mut self, receipt: FiringReceiptMCard) {
self.firings.insert(receipt.qualified_hash(), receipt);
}
pub fn sync_to_collection(&mut self, _sponsor_did: Option<&str>) -> Result<(), String> {
let base = self.base_uri();
let places: Vec<_> = self.namespace.places.values().cloned().collect();
let transitions: Vec<_> = self.namespace.transitions.values().cloned().collect();
let mut tokens_by_place = BTreeMap::new();
let mut refs_by_place = BTreeMap::new();
for pid in self.namespace.places.keys() {
let toks = self.namespace.get_place_tokens(pid);
let refs = self.namespace.marking.place_refs(pid);
tokens_by_place.insert(pid.clone(), toks);
refs_by_place.insert(pid.clone(), refs);
}
let net_card = NetMCard::create(
&self.net_id,
places.clone(),
transitions.clone(),
tokens_by_place.clone(),
Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3),
None,
)?;
self.adapter.put_file(&format!("{base}/topology"), &net_card.card.content)?;
let refs_val = serde_json::to_value(&refs_by_place).map_err(|e| e.to_string())?;
let marking_tok = TokenMCard::from_json(&refs_val, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PETRI_MARKING, Some(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3))?;
self.adapter.put_file(&format!("{base}/marking"), &marking_tok.card.content)?;
for place in &places {
self.adapter.put_file(&format!("{base}/places/{}/spec", place.place_id), &place.card.content)?;
if let Some(toks) = tokens_by_place.get(&place.place_id) {
for (idx, tok) in toks.iter().enumerate() {
self.adapter.put_file(&format!("{base}/places/{}/tokens/{idx}", place.place_id), &tok.card.content)?;
}
}
}
for trans in &transitions {
self.adapter.put_file(&format!("{base}/transitions/{}/spec", trans.transition_id), &trans.card.content)?;
}
for (fref, receipt) in &self.firings {
let safe_ref = fref.replace(':', "_");
self.adapter.put_file(&format!("{base}/firings/{safe_ref}"), &receipt.card.content)?;
}
Ok(())
}
pub fn read_resource(&self, subpath: &str) -> Result<String, String> {
let clean = subpath.trim_start_matches('/');
let base = self.base_uri();
let target = if clean.starts_with(&base) {
clean.to_string()
} else {
format!("{base}/{clean}")
};
let bytes = self.adapter.cat(&target)?;
String::from_utf8(bytes).map_err(|e| e.to_string())
}
pub fn list_resources(&self) -> Result<Vec<String>, String> {
self.adapter.ls(&self.base_uri())
}
}