use crate::layer0::vocabulary::{HASH_PREFIX_BLAKE3};
use crate::cpn::mcard_token::TokenMCard;
use crate::layer2::vfs::MCardFileSystem;
use serde::{Deserialize, Serialize};
use serde_json::Value;
pub const NAMESPACE_PROTOCOL_OPS: &[&str; 9] = &[
"version", "put", "get", "stat", "resolve", "bind", "list", "history", "watch",
];
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProcessExecutionResult {
pub committed: bool,
pub trapped_to_exception: bool,
pub output_token: TokenMCard,
pub places_visited: Vec<String>,
pub fiber_trace: Vec<String>,
pub payload: Value,
}
#[derive(Clone)]
pub struct PetriProcessPCard {
pub process_id: String,
pub required_services: Vec<String>,
pub allowed_prefixes: Vec<String>,
}
impl PetriProcessPCard {
pub fn new(process_id: &str) -> Self {
Self {
process_id: process_id.to_string(),
required_services: Vec::new(),
allowed_prefixes: Vec::new(),
}
}
pub fn place_ids(&self) -> (String, String, String, String, String) {
(
format!("{}:p_in", self.process_id),
format!("{}:p_ready", self.process_id),
format!("{}:p_done", self.process_id),
format!("{}:p_out", self.process_id),
format!("{}:p_exception", self.process_id),
)
}
pub fn execute<F>(
&self,
request: &Value,
sponsor_did: Option<&str>,
target_handle: Option<&str>,
handler: F,
) -> ProcessExecutionResult
where
F: FnOnce(&Value) -> Result<Value, String>,
{
let (p_in, p_ready, p_done, p_out, p_exc) = self.place_ids();
let did_ok = sponsor_did
.map(|d| d.starts_with(crate::layer0::vocabulary_identities::DID_KEY) || d.starts_with(crate::layer0::vocabulary::URI_SCHEME_DID_CLM))
.unwrap_or(false);
if !did_ok {
let exc_val = serde_json::json!({
"error": "unauthenticated_sponsor_did",
"kind": "process_exception",
"process_id": self.process_id,
"stage": "t_acquire",
});
let exc_tok = TokenMCard::from_json(&exc_val, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PROCESS_EXCEPTION, None)
.expect("exc token");
return ProcessExecutionResult {
committed: false,
trapped_to_exception: true,
output_token: exc_tok,
places_visited: vec![p_in, p_exc],
fiber_trace: vec![
"PENDING".to_string(),
"LOADING".to_string(),
"UNLOADING".to_string(),
"DISPOSED".to_string(),
],
payload: exc_val,
};
}
if let Some(target) = target_handle {
if !self.allowed_prefixes.is_empty() {
let clean = target
.trim_start_matches('/')
.strip_prefix(crate::layer0::vocabulary::HANDLE_MCARD)
.unwrap_or(target)
.trim_start_matches('/');
let allowed = self
.allowed_prefixes
.iter()
.any(|p| clean.starts_with(p.trim_matches('/')));
if !allowed {
let exc_val = serde_json::json!({
"error": format!("unauthorized_handle_scope:{target}"),
"kind": "process_exception",
"process_id": self.process_id,
"stage": "t_acquire",
});
let exc_tok =
TokenMCard::from_json(&exc_val, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PROCESS_EXCEPTION, None)
.expect("exc token");
return ProcessExecutionResult {
committed: false,
trapped_to_exception: true,
output_token: exc_tok,
places_visited: vec![p_in, p_exc],
fiber_trace: vec![
"PENDING".to_string(),
"LOADING".to_string(),
"UNLOADING".to_string(),
"DISPOSED".to_string(),
],
payload: exc_val,
};
}
}
}
match handler(request) {
Ok(out_val) => {
let out_tok = TokenMCard::from_json(&out_val, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PROCESS_OUT, None)
.expect("out token");
ProcessExecutionResult {
committed: true,
trapped_to_exception: false,
output_token: out_tok,
places_visited: vec![p_in, p_ready, p_done, p_out],
fiber_trace: vec![
"PENDING".to_string(),
"LOADING".to_string(),
"ACTIVE".to_string(),
"UNLOADING".to_string(),
"DISPOSED".to_string(),
],
payload: out_val,
}
}
Err(err) => {
let exc_val = serde_json::json!({
"error": err,
"kind": "process_exception",
"process_id": self.process_id,
"stage": "t_invoke",
});
let exc_tok = TokenMCard::from_json(&exc_val, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PROCESS_EXCEPTION, None)
.expect("exc token");
ProcessExecutionResult {
committed: false,
trapped_to_exception: true,
output_token: exc_tok,
places_visited: vec![p_in, p_ready, p_exc],
fiber_trace: vec![
"PENDING".to_string(),
"LOADING".to_string(),
"ACTIVE".to_string(),
"UNLOADING".to_string(),
"DISPOSED".to_string(),
],
payload: exc_val,
}
}
}
}
}
pub struct MCardNamespaceProtocolService {
pub fs: MCardFileSystem,
pub protocol_version: String,
pub allowed_prefixes: Vec<String>,
watch_log: Vec<Value>,
}
impl MCardNamespaceProtocolService {
pub fn new_in_memory() -> Self {
Self {
fs: MCardFileSystem::new_in_memory().expect("in-memory fs"),
protocol_version: crate::layer0::vocabulary_identities::VERSION_N_1_0_0.to_string(),
allowed_prefixes: Vec::new(),
watch_log: Vec::new(),
}
}
fn run_op<F>(
&self,
op_name: &str,
req: &Value,
sponsor_did: Option<&str>,
target_handle: Option<&str>,
handler: F,
) -> ProcessExecutionResult
where
F: FnOnce(&Value) -> Result<Value, String>,
{
let mut proc = PetriProcessPCard::new(&format!("ns:{op_name}"));
proc.allowed_prefixes = self.allowed_prefixes.clone();
proc.execute(req, sponsor_did, target_handle, handler)
}
pub fn version(&self, client_version: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
let req = serde_json::json!({ "client_version": client_version });
let server_ver = self.protocol_version.clone();
self.run_op("version", &req, sponsor_did, None, move |_| {
let c_maj = client_version.split('.').next().unwrap_or("0");
let s_maj = server_ver.split('.').next().unwrap_or("1");
if c_maj != s_maj {
return Err(format!("Incompatible protocol major version: {client_version}"));
}
Ok(serde_json::json!({
"negotiated_version": server_ver,
"op": "version",
"operations": NAMESPACE_PROTOCOL_OPS,
"server_version": self.protocol_version,
}))
})
}
pub fn put(
&self,
handle: &str,
content: &[u8],
algorithm: Option<&str>,
sponsor_did: Option<&str>,
) -> ProcessExecutionResult {
let algo = algorithm.unwrap_or(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3);
let req = serde_json::json!({ "algorithm": algo, "size_bytes": content.len() });
self.run_op("put", &req, sponsor_did, Some(handle), |_| {
let rec = self
.fs
.write_raw_bytes(handle, content, Some(algo))
.map_err(|e| e.to_string())?;
Ok(serde_json::json!({
"algorithm": algo,
"g_time": rec.g_time,
"hash": rec.hash,
"op": "put",
"qualified_ref": format!("{algo}:{}", rec.hash),
"size_bytes": content.len(),
}))
})
}
pub fn get(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
let req = serde_json::json!({ "ref": handle });
self.run_op("get", &req, sponsor_did, Some(handle), |_| {
let raw = self.fs.read_raw_bytes(handle).map_err(|e| e.to_string())?;
Ok(serde_json::json!({
"content_utf8": String::from_utf8_lossy(&raw),
"op": "get",
"size_bytes": raw.len(),
}))
})
}
pub fn stat(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
let req = serde_json::json!({ "target": handle });
self.run_op("stat", &req, sponsor_did, Some(handle), |_| {
let raw = self.fs.read_raw_bytes(handle).map_err(|e| e.to_string())?;
Ok(serde_json::json!({
"algorithm": crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3,
"op": "stat",
"size_bytes": raw.len(),
"type_uri": crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_STORAGE_VERIFIED_MCARD,
}))
})
}
pub fn resolve(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
let req = serde_json::json!({ "handle": handle });
self.run_op("resolve", &req, sponsor_did, Some(handle), |_| {
let st = self.fs.stat_file(handle).map_err(|e| e.to_string())?;
Ok(serde_json::json!({
"handle": st.uri,
"op": "resolve",
"qualified_ref": format!("{HASH_PREFIX_BLAKE3}{}", st.hash),
}))
})
}
pub fn bind(
&mut self,
handle: &str,
new_ref: &str,
expected_old_ref: Option<&str>,
sponsor_did: Option<&str>,
) -> ProcessExecutionResult {
let req = serde_json::json!({
"expected_old_ref": expected_old_ref,
"handle": handle,
"new_ref": new_ref,
});
let fs = self.fs.clone();
let canonical = fs.canonicalize_uri(handle);
let qnew = if new_ref.contains(':') {
new_ref.to_string()
} else {
format!("{HASH_PREFIX_BLAKE3}{new_ref}")
};
let next_cursor = self.watch_log.len() + 1;
let res = self.run_op("bind", &req, sponsor_did, Some(handle), |_| {
let ok = fs
.bind(handle, new_ref, expected_old_ref)
.map_err(|e| e.to_string())?;
if !ok {
return Err(format!("CAS conflict on '{handle}'"));
}
Ok(serde_json::json!({
"bound": true,
"cursor": next_cursor,
"handle": canonical,
"new_ref": qnew,
"op": "bind",
}))
});
if res.committed {
self.watch_log.push(serde_json::json!({
"cursor": next_cursor,
"handle": self.fs.canonicalize_uri(handle),
"new_ref": if new_ref.contains(':') { new_ref.to_string() } else { format!("{HASH_PREFIX_BLAKE3}{new_ref}") },
"old_ref": expected_old_ref,
}));
}
res
}
pub fn list(&self, prefix: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
let req = serde_json::json!({ "prefix": prefix });
self.run_op("list", &req, sponsor_did, Some(prefix), |_| {
let items = self.fs.list_dir(prefix).map_err(|e| e.to_string())?;
Ok(serde_json::json!({
"items": items,
"op": "list",
"prefix": prefix,
}))
})
}
pub fn history(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
let req = serde_json::json!({ "handle": handle });
self.run_op("history", &req, sponsor_did, Some(handle), |_| {
let canonical = self.fs.canonicalize_uri(handle);
Ok(serde_json::json!({
"handle": canonical,
"op": "history",
}))
})
}
pub fn watch(&self, since_cursor: usize, sponsor_did: Option<&str>) -> ProcessExecutionResult {
let req = serde_json::json!({ "since_cursor": since_cursor });
let events: Vec<Value> = self
.watch_log
.iter()
.filter(|ev| ev.get("cursor").and_then(|c| c.as_u64()).unwrap_or(0) as usize > since_cursor)
.cloned()
.collect();
self.run_op("watch", &req, sponsor_did, None, move |_| {
Ok(serde_json::json!({
"events": events,
"op": "watch",
}))
})
}
}