1use crate::layer0::fiber_transitions::{trace, CORE_TRACE};
5use crate::layer0::vocabulary::{HASH_PREFIX_BLAKE3};
6use crate::cpn::mcard_token::TokenMCard;
7use crate::layer2::vfs::MCardFileSystem;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10
11pub const NAMESPACE_PROTOCOL_OPS: &[&str; 9] = &[
13 "version", "put", "get", "stat", "resolve", "bind", "list", "history", "watch",
14];
15
16#[derive(Debug, Clone, Serialize, Deserialize)]
18pub struct ProcessExecutionResult {
19 pub committed: bool,
21 pub trapped_to_exception: bool,
23 pub output_token: TokenMCard,
25 pub places_visited: Vec<String>,
27 pub fiber_trace: Vec<String>,
29 pub payload: Value,
31}
32
33#[derive(Clone)]
35pub struct PetriProcessPCard {
36 pub process_id: String,
38 pub required_services: Vec<String>,
40 pub allowed_prefixes: Vec<String>,
42}
43
44impl PetriProcessPCard {
45 pub fn new(process_id: &str) -> Self {
47 Self {
48 process_id: process_id.to_string(),
49 required_services: Vec::new(),
50 allowed_prefixes: Vec::new(),
51 }
52 }
53
54 pub fn place_ids(&self) -> (String, String, String, String, String) {
56 (
57 format!("{}:p_in", self.process_id),
58 format!("{}:p_ready", self.process_id),
59 format!("{}:p_done", self.process_id),
60 format!("{}:p_out", self.process_id),
61 format!("{}:p_exception", self.process_id),
62 )
63 }
64
65 pub fn execute<F>(
67 &self,
68 request: &Value,
69 sponsor_did: Option<&str>,
70 target_handle: Option<&str>,
71 handler: F,
72 ) -> ProcessExecutionResult
73 where
74 F: FnOnce(&Value) -> Result<Value, String>,
75 {
76 let (p_in, p_ready, p_done, p_out, p_exc) = self.place_ids();
77 let did_ok = sponsor_did
78 .map(|d| d.starts_with(crate::layer0::vocabulary_identities::DID_KEY) || d.starts_with(crate::layer0::vocabulary::URI_SCHEME_DID_CLM))
79 .unwrap_or(false);
80 if !did_ok {
81 return self.trapped("unauthenticated_sponsor_did", "t_acquire", vec![p_in, p_exc], rejected_trace());
82 }
83
84 if let Some(target) = target_handle {
85 if !self.allowed_prefixes.is_empty() {
86 let clean = target
87 .trim_start_matches('/')
88 .strip_prefix(crate::layer0::vocabulary::HANDLE_MCARD)
89 .unwrap_or(target)
90 .trim_start_matches('/');
91 let allowed = self
92 .allowed_prefixes
93 .iter()
94 .any(|p| clean.starts_with(p.trim_matches('/')));
95 if !allowed {
96 let error = format!("unauthorized_handle_scope:{target}");
97 return self.trapped(&error, "t_acquire", vec![p_in, p_exc], rejected_trace());
98 }
99 }
100 }
101
102 match handler(request) {
103 Ok(out_val) => {
104 let out_tok = TokenMCard::from_json(&out_val, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PROCESS_OUT, None)
105 .expect("out token");
106 ProcessExecutionResult {
107 committed: true,
108 trapped_to_exception: false,
109 output_token: out_tok,
110 places_visited: vec![p_in, p_ready, p_done, p_out],
111 fiber_trace: CORE_TRACE.map(String::from).to_vec(),
112 payload: out_val,
113 }
114 }
115 Err(err) => self.trapped(&err, "t_invoke", vec![p_in, p_ready, p_exc], CORE_TRACE.map(String::from).to_vec()),
116 }
117 }
118
119 fn trapped(
121 &self,
122 error: &str,
123 stage: &'static str,
124 places_visited: Vec<String>,
125 fiber_trace: Vec<String>,
126 ) -> ProcessExecutionResult {
127 let exception = ProcessException { error, kind: "process_exception", process_id: &self.process_id, stage };
128 let payload = serde_json::to_value(exception).expect("exception payload");
129 let output_token = TokenMCard::from_json(&payload, crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_PROCESS_EXCEPTION, None)
130 .expect("exc token");
131 ProcessExecutionResult { committed: false, trapped_to_exception: true, output_token, places_visited, fiber_trace, payload }
132 }
133}
134
135#[derive(Serialize)]
137struct ProcessException<'a> {
138 error: &'a str,
139 kind: &'static str,
140 process_id: &'a str,
141 stage: &'static str,
142}
143
144fn rejected_trace() -> Vec<String> {
146 [trace::PENDING, trace::LOADING, trace::UNLOADING, trace::DISPOSED].map(String::from).to_vec()
147}
148
149pub struct MCardNamespaceProtocolService {
151 pub fs: MCardFileSystem,
153 pub protocol_version: String,
155 pub allowed_prefixes: Vec<String>,
157 watch_log: Vec<Value>,
158}
159
160impl MCardNamespaceProtocolService {
161 pub fn new_in_memory() -> Self {
163 Self {
164 fs: MCardFileSystem::new_in_memory().expect("in-memory fs"),
165 protocol_version: crate::layer0::vocabulary_identities::VERSION_N_1_0_0.to_string(),
166 allowed_prefixes: Vec::new(),
167 watch_log: Vec::new(),
168 }
169 }
170
171 fn run_op<F>(
172 &self,
173 op_name: &str,
174 req: &Value,
175 sponsor_did: Option<&str>,
176 target_handle: Option<&str>,
177 handler: F,
178 ) -> ProcessExecutionResult
179 where
180 F: FnOnce(&Value) -> Result<Value, String>,
181 {
182 let mut proc = PetriProcessPCard::new(&format!("ns:{op_name}"));
183 proc.allowed_prefixes = self.allowed_prefixes.clone();
184 proc.execute(req, sponsor_did, target_handle, handler)
185 }
186
187 pub fn version(&self, client_version: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
189 let req = serde_json::json!({ "client_version": client_version });
190 let server_ver = self.protocol_version.clone();
191 self.run_op("version", &req, sponsor_did, None, move |_| {
192 let c_maj = client_version.split('.').next().unwrap_or("0");
193 let s_maj = server_ver.split('.').next().unwrap_or("1");
194 if c_maj != s_maj {
195 return Err(format!("Incompatible protocol major version: {client_version}"));
196 }
197 Ok(serde_json::json!({
198 "negotiated_version": server_ver,
199 "op": "version",
200 "operations": NAMESPACE_PROTOCOL_OPS,
201 "server_version": self.protocol_version,
202 }))
203 })
204 }
205
206 pub fn put(
208 &self,
209 handle: &str,
210 content: &[u8],
211 algorithm: Option<&str>,
212 sponsor_did: Option<&str>,
213 ) -> ProcessExecutionResult {
214 let algo = algorithm.unwrap_or(crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3);
215 let req = serde_json::json!({ "algorithm": algo, "size_bytes": content.len() });
216 self.run_op("put", &req, sponsor_did, Some(handle), |_| {
217 let rec = self
218 .fs
219 .write_raw_bytes(handle, content, Some(algo))
220 .map_err(|e| e.to_string())?;
221 Ok(serde_json::json!({
222 "algorithm": algo,
223 "g_time": rec.g_time,
224 "hash": rec.hash,
225 "op": "put",
226 "qualified_ref": format!("{algo}:{}", rec.hash),
227 "size_bytes": content.len(),
228 }))
229 })
230 }
231
232 pub fn get(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
234 let req = serde_json::json!({ "ref": handle });
235 self.run_op("get", &req, sponsor_did, Some(handle), |_| {
236 let raw = self.fs.read_raw_bytes(handle).map_err(|e| e.to_string())?;
237 Ok(serde_json::json!({
238 "content_utf8": String::from_utf8_lossy(&raw),
239 "op": "get",
240 "size_bytes": raw.len(),
241 }))
242 })
243 }
244
245 pub fn stat(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
247 let req = serde_json::json!({ "target": handle });
248 self.run_op("stat", &req, sponsor_did, Some(handle), |_| {
249 let raw = self.fs.read_raw_bytes(handle).map_err(|e| e.to_string())?;
250 Ok(serde_json::json!({
251 "algorithm": crate::layer0::vocabulary::HASH_ALGORITHM_BLAKE3,
252 "op": "stat",
253 "size_bytes": raw.len(),
254 "type_uri": crate::layer0::vocabulary_types::TYPE_URI_CLM_TYPE_STORAGE_VERIFIED_MCARD,
255 }))
256 })
257 }
258
259 pub fn resolve(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
261 let req = serde_json::json!({ "handle": handle });
262 self.run_op("resolve", &req, sponsor_did, Some(handle), |_| {
263 let st = self.fs.stat_file(handle).map_err(|e| e.to_string())?;
264 Ok(serde_json::json!({
265 "handle": st.uri,
266 "op": "resolve",
267 "qualified_ref": format!("{HASH_PREFIX_BLAKE3}{}", st.hash),
268 }))
269 })
270 }
271
272 pub fn bind(
274 &mut self,
275 handle: &str,
276 new_ref: &str,
277 expected_old_ref: Option<&str>,
278 sponsor_did: Option<&str>,
279 ) -> ProcessExecutionResult {
280 let req = serde_json::json!({
281 "expected_old_ref": expected_old_ref,
282 "handle": handle,
283 "new_ref": new_ref,
284 });
285 let fs = self.fs.clone();
286 let canonical = fs.canonicalize_uri(handle);
287 let qnew = if new_ref.contains(':') {
288 new_ref.to_string()
289 } else {
290 format!("{HASH_PREFIX_BLAKE3}{new_ref}")
291 };
292 let next_cursor = self.watch_log.len() + 1;
293 let res = self.run_op("bind", &req, sponsor_did, Some(handle), |_| {
294 let ok = fs
295 .bind(handle, new_ref, expected_old_ref)
296 .map_err(|e| e.to_string())?;
297 if !ok {
298 return Err(format!("CAS conflict on '{handle}'"));
299 }
300 Ok(serde_json::json!({
301 "bound": true,
302 "cursor": next_cursor,
303 "handle": canonical,
304 "new_ref": qnew,
305 "op": "bind",
306 }))
307 });
308 if res.committed {
309 self.watch_log.push(serde_json::json!({
310 "cursor": next_cursor,
311 "handle": self.fs.canonicalize_uri(handle),
312 "new_ref": if new_ref.contains(':') { new_ref.to_string() } else { format!("{HASH_PREFIX_BLAKE3}{new_ref}") },
313 "old_ref": expected_old_ref,
314 }));
315 }
316 res
317 }
318
319 pub fn list(&self, prefix: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
321 let req = serde_json::json!({ "prefix": prefix });
322 self.run_op("list", &req, sponsor_did, Some(prefix), |_| {
323 let items = self.fs.list_dir(prefix).map_err(|e| e.to_string())?;
324 Ok(serde_json::json!({
325 "items": items,
326 "op": "list",
327 "prefix": prefix,
328 }))
329 })
330 }
331
332 pub fn history(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
334 let req = serde_json::json!({ "handle": handle });
335 self.run_op("history", &req, sponsor_did, Some(handle), |_| {
336 let canonical = self.fs.canonicalize_uri(handle);
337 Ok(serde_json::json!({
338 "handle": canonical,
339 "op": "history",
340 }))
341 })
342 }
343
344 pub fn watch(&self, since_cursor: usize, sponsor_did: Option<&str>) -> ProcessExecutionResult {
346 let req = serde_json::json!({ "since_cursor": since_cursor });
347 let events: Vec<Value> = self
348 .watch_log
349 .iter()
350 .filter(|ev| ev.get("cursor").and_then(|c| c.as_u64()).unwrap_or(0) as usize > since_cursor)
351 .cloned()
352 .collect();
353 self.run_op("watch", &req, sponsor_did, None, move |_| {
354 Ok(serde_json::json!({
355 "events": events,
356 "op": "watch",
357 }))
358 })
359 }
360}