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