Skip to main content

clm_rust_core/layer2/
petri_process.rs

1//! Layer 2 `PetriProcessPCard` Service Wrapper & 9-Operation Authenticated Namespace Protocol (Sprint 511)
2//! Canonical Path: kernel/clm_rust_core/src/layer2/petri_process.rs
3
4use crate::cpn::mcard_token::TokenMCard;
5use crate::layer2::vfs::MCardFileSystem;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8
9/// Canonical 9 operations of the authenticated MCard Namespace Protocol.
10pub const NAMESPACE_PROTOCOL_OPS: &[&str; 9] = &[
11    "version", "put", "get", "stat", "resolve", "bind", "list", "history", "watch",
12];
13
14/// Result of executing a `PetriProcessPCard` transition cycle (`p_in -> p_ready -> p_done -> p_out | p_exception`).
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct ProcessExecutionResult {
17    /// True if the transition committed to `p_out`.
18    pub committed: bool,
19    /// True if the transition trapped to `p_exception`.
20    pub trapped_to_exception: bool,
21    /// Output or exception `TokenMCard`.
22    pub output_token: TokenMCard,
23    /// Ordered sequence of visited Petri Net places.
24    pub places_visited: Vec<String>,
25    /// Recorded 5-state Cordis `Fiber` trace.
26    pub fiber_trace: Vec<String>,
27    /// Structured JSON response or error payload.
28    pub payload: Value,
29}
30
31/// Layer 2 Petri Net Process wrapper enforcing MISU DID authentication and capability prefix bounds.
32#[derive(Clone)]
33pub struct PetriProcessPCard {
34    /// Logical process identifier.
35    pub process_id: String,
36    /// Required Cordis service capabilities.
37    pub required_services: Vec<String>,
38    /// Allowed handle prefix scopes.
39    pub allowed_prefixes: Vec<String>,
40}
41
42impl PetriProcessPCard {
43    /// Creates a new `PetriProcessPCard` for `process_id`.
44    pub fn new(process_id: &str) -> Self {
45        Self {
46            process_id: process_id.to_string(),
47            required_services: Vec::new(),
48            allowed_prefixes: Vec::new(),
49        }
50    }
51
52    /// Returns the 5 canonical Petri Net place IDs `(p_in, p_ready, p_done, p_out, p_exception)`.
53    pub fn place_ids(&self) -> (String, String, String, String, String) {
54        (
55            format!("{}:p_in", self.process_id),
56            format!("{}:p_ready", self.process_id),
57            format!("{}:p_done", self.process_id),
58            format!("{}:p_out", self.process_id),
59            format!("{}:p_exception", self.process_id),
60        )
61    }
62
63    /// Executes `handler` inside the process Petri Net with MISU DID and scope checks.
64    pub fn execute<F>(
65        &self,
66        request: &Value,
67        sponsor_did: Option<&str>,
68        target_handle: Option<&str>,
69        handler: F,
70    ) -> ProcessExecutionResult
71    where
72        F: FnOnce(&Value) -> Result<Value, String>,
73    {
74        let (p_in, p_ready, p_done, p_out, p_exc) = self.place_ids();
75        let did_ok = sponsor_did
76            .map(|d| d.starts_with("did:key:") || d.starts_with("did:clm:"))
77            .unwrap_or(false);
78        if !did_ok {
79            let exc_val = serde_json::json!({
80                "error": "unauthenticated_sponsor_did",
81                "kind": "process_exception",
82                "process_id": self.process_id,
83                "stage": "t_acquire",
84            });
85            let exc_tok = TokenMCard::from_json(&exc_val, "clm://type/process/exception", None)
86                .expect("exc token");
87            return ProcessExecutionResult {
88                committed: false,
89                trapped_to_exception: true,
90                output_token: exc_tok,
91                places_visited: vec![p_in, p_exc],
92                fiber_trace: vec![
93                    "PENDING".to_string(),
94                    "LOADING".to_string(),
95                    "UNLOADING".to_string(),
96                    "DISPOSED".to_string(),
97                ],
98                payload: exc_val,
99            };
100        }
101
102        if let Some(target) = target_handle {
103            if !self.allowed_prefixes.is_empty() {
104                let clean = target
105                    .trim_start_matches('/')
106                    .strip_prefix("mcard:")
107                    .unwrap_or(target)
108                    .trim_start_matches('/');
109                let allowed = self
110                    .allowed_prefixes
111                    .iter()
112                    .any(|p| clean.starts_with(p.trim_matches('/')));
113                if !allowed {
114                    let exc_val = serde_json::json!({
115                        "error": format!("unauthorized_handle_scope:{target}"),
116                        "kind": "process_exception",
117                        "process_id": self.process_id,
118                        "stage": "t_acquire",
119                    });
120                    let exc_tok =
121                        TokenMCard::from_json(&exc_val, "clm://type/process/exception", None)
122                            .expect("exc token");
123                    return ProcessExecutionResult {
124                        committed: false,
125                        trapped_to_exception: true,
126                        output_token: exc_tok,
127                        places_visited: vec![p_in, p_exc],
128                        fiber_trace: vec![
129                            "PENDING".to_string(),
130                            "LOADING".to_string(),
131                            "UNLOADING".to_string(),
132                            "DISPOSED".to_string(),
133                        ],
134                        payload: exc_val,
135                    };
136                }
137            }
138        }
139
140        match handler(request) {
141            Ok(out_val) => {
142                let out_tok = TokenMCard::from_json(&out_val, "clm://type/process/out", None)
143                    .expect("out token");
144                ProcessExecutionResult {
145                    committed: true,
146                    trapped_to_exception: false,
147                    output_token: out_tok,
148                    places_visited: vec![p_in, p_ready, p_done, p_out],
149                    fiber_trace: vec![
150                        "PENDING".to_string(),
151                        "LOADING".to_string(),
152                        "ACTIVE".to_string(),
153                        "UNLOADING".to_string(),
154                        "DISPOSED".to_string(),
155                    ],
156                    payload: out_val,
157                }
158            }
159            Err(err) => {
160                let exc_val = serde_json::json!({
161                    "error": err,
162                    "kind": "process_exception",
163                    "process_id": self.process_id,
164                    "stage": "t_invoke",
165                });
166                let exc_tok = TokenMCard::from_json(&exc_val, "clm://type/process/exception", None)
167                    .expect("exc token");
168                ProcessExecutionResult {
169                    committed: false,
170                    trapped_to_exception: true,
171                    output_token: exc_tok,
172                    places_visited: vec![p_in, p_ready, p_exc],
173                    fiber_trace: vec![
174                        "PENDING".to_string(),
175                        "LOADING".to_string(),
176                        "ACTIVE".to_string(),
177                        "UNLOADING".to_string(),
178                        "DISPOSED".to_string(),
179                    ],
180                    payload: exc_val,
181                }
182            }
183        }
184    }
185}
186
187/// 9-operation authenticated MCard Namespace Protocol service (`version`, `put`, `get`, `stat`, `resolve`, `bind`, `list`, `history`, `watch`).
188pub struct MCardNamespaceProtocolService {
189    /// Underlying `MCardFileSystem`.
190    pub fs: MCardFileSystem,
191    /// Protocol semantic version string.
192    pub protocol_version: String,
193    /// Allowed handle prefixes for capability scoping.
194    pub allowed_prefixes: Vec<String>,
195    watch_log: Vec<Value>,
196}
197
198impl MCardNamespaceProtocolService {
199    /// Creates an in-memory `MCardNamespaceProtocolService`.
200    pub fn new_in_memory() -> Self {
201        Self {
202            fs: MCardFileSystem::new_in_memory().expect("in-memory fs"),
203            protocol_version: "1.0.0".to_string(),
204            allowed_prefixes: Vec::new(),
205            watch_log: Vec::new(),
206        }
207    }
208
209    fn run_op<F>(
210        &self,
211        op_name: &str,
212        req: &Value,
213        sponsor_did: Option<&str>,
214        target_handle: Option<&str>,
215        handler: F,
216    ) -> ProcessExecutionResult
217    where
218        F: FnOnce(&Value) -> Result<Value, String>,
219    {
220        let mut proc = PetriProcessPCard::new(&format!("ns:{op_name}"));
221        proc.allowed_prefixes = self.allowed_prefixes.clone();
222        proc.execute(req, sponsor_did, target_handle, handler)
223    }
224
225    /// Negotiates protocol version and returns supported namespace operations.
226    pub fn version(&self, client_version: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
227        let req = serde_json::json!({ "client_version": client_version });
228        let server_ver = self.protocol_version.clone();
229        self.run_op("version", &req, sponsor_did, None, move |_| {
230            let c_maj = client_version.split('.').next().unwrap_or("0");
231            let s_maj = server_ver.split('.').next().unwrap_or("1");
232            if c_maj != s_maj {
233                return Err(format!("Incompatible protocol major version: {client_version}"));
234            }
235            Ok(serde_json::json!({
236                "negotiated_version": server_ver,
237                "op": "version",
238                "operations": NAMESPACE_PROTOCOL_OPS,
239                "server_version": self.protocol_version,
240            }))
241        })
242    }
243
244    /// Stores `content` at `handle` and seals an immutable `MCardRecord`.
245    pub fn put(
246        &self,
247        handle: &str,
248        content: &[u8],
249        algorithm: Option<&str>,
250        sponsor_did: Option<&str>,
251    ) -> ProcessExecutionResult {
252        let algo = algorithm.unwrap_or("blake3");
253        let req = serde_json::json!({ "algorithm": algo, "size_bytes": content.len() });
254        self.run_op("put", &req, sponsor_did, Some(handle), |_| {
255            let rec = self
256                .fs
257                .write_raw_bytes(handle, content, Some(algo))
258                .map_err(|e| e.to_string())?;
259            Ok(serde_json::json!({
260                "algorithm": algo,
261                "g_time": rec.g_time,
262                "hash": rec.hash,
263                "op": "put",
264                "qualified_ref": format!("{algo}:{}", rec.hash),
265                "size_bytes": content.len(),
266            }))
267        })
268    }
269
270    /// Retrieves verified content bytes from `handle`.
271    pub fn get(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
272        let req = serde_json::json!({ "ref": handle });
273        self.run_op("get", &req, sponsor_did, Some(handle), |_| {
274            let raw = self.fs.read_raw_bytes(handle).map_err(|e| e.to_string())?;
275            Ok(serde_json::json!({
276                "content_utf8": String::from_utf8_lossy(&raw),
277                "op": "get",
278                "size_bytes": raw.len(),
279            }))
280        })
281    }
282
283    /// Returns metadata (`size_bytes`, `algorithm`, `type_uri`) for `handle`.
284    pub fn stat(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
285        let req = serde_json::json!({ "target": handle });
286        self.run_op("stat", &req, sponsor_did, Some(handle), |_| {
287            let raw = self.fs.read_raw_bytes(handle).map_err(|e| e.to_string())?;
288            Ok(serde_json::json!({
289                "algorithm": "blake3",
290                "op": "stat",
291                "size_bytes": raw.len(),
292                "type_uri": "clm://type/storage/verified_mcard",
293            }))
294        })
295    }
296
297    /// Resolves `handle` to its current algorithm-qualified `a:hex` reference.
298    pub fn resolve(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
299        let req = serde_json::json!({ "handle": handle });
300        self.run_op("resolve", &req, sponsor_did, Some(handle), |_| {
301            let st = self.fs.stat_file(handle).map_err(|e| e.to_string())?;
302            Ok(serde_json::json!({
303                "handle": st.uri,
304                "op": "resolve",
305                "qualified_ref": format!("blake3:{}", st.hash),
306            }))
307        })
308    }
309
310    /// Atomically compare-and-swaps `handle` to `new_ref` given `expected_old_ref`.
311    pub fn bind(
312        &mut self,
313        handle: &str,
314        new_ref: &str,
315        expected_old_ref: Option<&str>,
316        sponsor_did: Option<&str>,
317    ) -> ProcessExecutionResult {
318        let req = serde_json::json!({
319            "expected_old_ref": expected_old_ref,
320            "handle": handle,
321            "new_ref": new_ref,
322        });
323        let fs = self.fs.clone();
324        let canonical = fs.canonicalize_uri(handle);
325        let qnew = if new_ref.contains(':') {
326            new_ref.to_string()
327        } else {
328            format!("blake3:{new_ref}")
329        };
330        let next_cursor = self.watch_log.len() + 1;
331        let res = self.run_op("bind", &req, sponsor_did, Some(handle), |_| {
332            let ok = fs
333                .bind(handle, new_ref, expected_old_ref)
334                .map_err(|e| e.to_string())?;
335            if !ok {
336                return Err(format!("CAS conflict on '{handle}'"));
337            }
338            Ok(serde_json::json!({
339                "bound": true,
340                "cursor": next_cursor,
341                "handle": canonical,
342                "new_ref": qnew,
343                "op": "bind",
344            }))
345        });
346        if res.committed {
347            self.watch_log.push(serde_json::json!({
348                "cursor": next_cursor,
349                "handle": self.fs.canonicalize_uri(handle),
350                "new_ref": if new_ref.contains(':') { new_ref.to_string() } else { format!("blake3:{new_ref}") },
351                "old_ref": expected_old_ref,
352            }));
353        }
354        res
355    }
356
357    /// Lists handles matching `prefix`.
358    pub fn list(&self, prefix: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
359        let req = serde_json::json!({ "prefix": prefix });
360        self.run_op("list", &req, sponsor_did, Some(prefix), |_| {
361            let items = self.fs.list_dir(prefix).map_err(|e| e.to_string())?;
362            Ok(serde_json::json!({
363                "items": items,
364                "op": "list",
365                "prefix": prefix,
366            }))
367        })
368    }
369
370    /// Returns temporal handle history for `handle`.
371    pub fn history(&self, handle: &str, sponsor_did: Option<&str>) -> ProcessExecutionResult {
372        let req = serde_json::json!({ "handle": handle });
373        self.run_op("history", &req, sponsor_did, Some(handle), |_| {
374            let canonical = self.fs.canonicalize_uri(handle);
375            Ok(serde_json::json!({
376                "handle": canonical,
377                "op": "history",
378            }))
379        })
380    }
381
382    /// Streams bind events strictly newer than `since_cursor`.
383    pub fn watch(&self, since_cursor: usize, sponsor_did: Option<&str>) -> ProcessExecutionResult {
384        let req = serde_json::json!({ "since_cursor": since_cursor });
385        let events: Vec<Value> = self
386            .watch_log
387            .iter()
388            .filter(|ev| ev.get("cursor").and_then(|c| c.as_u64()).unwrap_or(0) as usize > since_cursor)
389            .cloned()
390            .collect();
391        self.run_op("watch", &req, sponsor_did, None, move |_| {
392            Ok(serde_json::json!({
393                "events": events,
394                "op": "watch",
395            }))
396        })
397    }
398}