1use crate::cpn::mcard_token::{NetMCard, TokenMCard};
5use crate::cpn::token_namespace::{FiringReceiptMCard, MCardMarking, MCardTokenNamespace};
6use crate::layer2::petri_process::MCardNamespaceProtocolService;
7use crate::layer2::vfs::DirectoryManifest;
8use std::collections::{BTreeMap, BTreeSet};
9
10pub struct MCardHostMountAdapter {
12 pub service: MCardNamespaceProtocolService,
14 pub sponsor_did: String,
16}
17
18impl Default for MCardHostMountAdapter {
19 fn default() -> Self {
20 Self::new()
21 }
22}
23
24impl MCardHostMountAdapter {
25 pub fn new() -> Self {
27 Self {
28 service: MCardNamespaceProtocolService::new_in_memory(),
29 sponsor_did: "did:key:z6MkRustHostMount".to_string(),
30 }
31 }
32
33 pub fn put_file(&self, path: &str, content: &[u8]) -> Result<String, String> {
35 let res = self
36 .service
37 .put(path, content, Some("blake3"), Some(&self.sponsor_did));
38 if !res.committed {
39 return Err("put_file failed".to_string());
40 }
41 Ok(res.payload["qualified_ref"]
42 .as_str()
43 .unwrap_or_default()
44 .to_string())
45 }
46
47 pub fn cat(&self, path: &str) -> Result<Vec<u8>, String> {
49 self.service
50 .fs
51 .read_raw_bytes(path)
52 .map_err(|e| e.to_string())
53 }
54
55 pub fn ls(&self, prefix: &str) -> Result<Vec<String>, String> {
57 let res = self.service.list(prefix, Some(&self.sponsor_did));
58 if !res.committed {
59 return Err("ls failed".to_string());
60 }
61 let arr = res.payload["items"]
62 .as_array()
63 .cloned()
64 .unwrap_or_default();
65 Ok(arr
66 .into_iter()
67 .filter_map(|v| v.as_str().map(|s| s.to_string()))
68 .collect())
69 }
70
71 pub fn mkdir(&self, dir_path: &str) -> Result<String, String> {
73 let manifest = DirectoryManifest::new(Vec::new(), Some("blake3"));
74 self.put_file(dir_path, &manifest.to_canonical_bytes())
75 }
76
77 pub fn cp(&mut self, src_path: &str, dst_path: &str) -> Result<String, String> {
79 let resolved = self.service.resolve(src_path, Some(&self.sponsor_did));
80 if !resolved.committed {
81 return Err(format!("Source '{src_path}' not found"));
82 }
83 let qref = resolved.payload["qualified_ref"]
84 .as_str()
85 .unwrap_or_default()
86 .to_string();
87 let dst_res = self.service.resolve(dst_path, Some(&self.sponsor_did));
88 let expected_old = if dst_res.committed {
89 dst_res.payload["qualified_ref"]
90 .as_str()
91 .map(|s| s.to_string())
92 } else {
93 None
94 };
95 let bnd = self.service.bind(
96 dst_path,
97 &qref,
98 expected_old.as_deref(),
99 Some(&self.sponsor_did),
100 );
101 if !bnd.committed {
102 return Err(format!("cp bind failed for '{dst_path}'"));
103 }
104 Ok(qref)
105 }
106
107 pub fn mv(&mut self, src_path: &str, dst_path: &str) -> Result<String, String> {
109 let qref = self.cp(src_path, dst_path)?;
110 self.rm(src_path)?;
111 Ok(qref)
112 }
113
114 pub fn rm(&self, path: &str) -> Result<(), String> {
116 self.service
117 .fs
118 .delete_file(path)
119 .map_err(|e| e.to_string())
120 }
121}
122
123pub struct NamespaceUnionMount {
125 mounts: Vec<(String, MCardHostMountAdapter)>,
126}
127
128impl Default for NamespaceUnionMount {
129 fn default() -> Self {
130 Self::new()
131 }
132}
133
134impl NamespaceUnionMount {
135 pub fn new() -> Self {
137 Self { mounts: Vec::new() }
138 }
139
140 pub fn add_mount(&mut self, name: &str, adapter: MCardHostMountAdapter) -> Result<(), String> {
142 let mut existing = BTreeSet::new();
143 for (_, m) in &self.mounts {
144 for h in m.ls("mcard:")? {
145 existing.insert(h);
146 }
147 }
148 let incoming = adapter.ls("mcard:")?;
149 for h in &incoming {
150 if existing.contains(h) {
151 return Err(format!(
152 "Namespace union collision detected (Meet != bottom) on handle '{h}'"
153 ));
154 }
155 }
156 self.mounts.push((name.to_string(), adapter));
157 Ok(())
158 }
159
160 pub fn ls_union(&self, prefix: &str) -> Result<Vec<String>, String> {
162 let mut seen = BTreeSet::new();
163 for (_, m) in &self.mounts {
164 for h in m.ls(prefix)? {
165 if !seen.insert(h.clone()) {
166 return Err(format!("Runtime union collision on '{h}'"));
167 }
168 }
169 }
170 Ok(seen.into_iter().collect())
171 }
172
173 pub fn cat_union(&self, path: &str) -> Result<Vec<u8>, String> {
175 let mut found: Vec<Vec<u8>> = Vec::new();
176 for (_, m) in &self.mounts {
177 if let Ok(bytes) = m.cat(path) {
178 found.push(bytes);
179 }
180 }
181 match found.len() {
182 0 => Err(format!("Handle '{path}' not found in union namespace")),
183 1 => Ok(found.remove(0)),
184 _ => Err(format!("Ambiguous collision on '{path}' across union mounts")),
185 }
186 }
187}
188
189pub struct Layer1NetCollectionServer {
191 pub net_id: String,
192 pub namespace: MCardTokenNamespace,
193 pub adapter: MCardHostMountAdapter,
194 pub firings: BTreeMap<String, FiringReceiptMCard>,
195}
196
197impl Layer1NetCollectionServer {
198 pub fn new(net_id: &str) -> Self {
199 Self {
200 net_id: net_id.to_string(),
201 namespace: MCardTokenNamespace::new(net_id),
202 adapter: MCardHostMountAdapter::new(),
203 firings: BTreeMap::new(),
204 }
205 }
206
207 pub fn with_namespace(
208 net_id: &str,
209 namespace: MCardTokenNamespace,
210 adapter: Option<MCardHostMountAdapter>,
211 ) -> Self {
212 Self {
213 net_id: net_id.to_string(),
214 namespace,
215 adapter: adapter.unwrap_or_default(),
216 firings: BTreeMap::new(),
217 }
218 }
219
220 pub fn marking(&self) -> &MCardMarking {
221 &self.namespace.marking
222 }
223
224 pub fn base_uri(&self) -> String {
225 format!("ns/{}", self.net_id)
226 }
227
228 pub fn record_firing(&mut self, receipt: FiringReceiptMCard) {
229 self.firings.insert(receipt.qualified_hash(), receipt);
230 }
231
232 pub fn sync_to_collection(&mut self, _sponsor_did: Option<&str>) -> Result<(), String> {
233 let base = self.base_uri();
234 let places: Vec<_> = self.namespace.places.values().cloned().collect();
235 let transitions: Vec<_> = self.namespace.transitions.values().cloned().collect();
236 let mut tokens_by_place = BTreeMap::new();
237 let mut refs_by_place = BTreeMap::new();
238
239 for pid in self.namespace.places.keys() {
240 let toks = self.namespace.get_place_tokens(pid);
241 let refs = self.namespace.marking.place_refs(pid);
242 tokens_by_place.insert(pid.clone(), toks);
243 refs_by_place.insert(pid.clone(), refs);
244 }
245
246 let net_card = NetMCard::create(
247 &self.net_id,
248 places.clone(),
249 transitions.clone(),
250 tokens_by_place.clone(),
251 Some("blake3"),
252 None,
253 )?;
254 self.adapter.put_file(&format!("{base}/topology"), &net_card.card.content)?;
255
256 let refs_val = serde_json::to_value(&refs_by_place).map_err(|e| e.to_string())?;
257 let marking_tok = TokenMCard::from_json(&refs_val, "clm://type/petri/marking", Some("blake3"))?;
258 self.adapter.put_file(&format!("{base}/marking"), &marking_tok.card.content)?;
259
260 for place in &places {
261 self.adapter.put_file(&format!("{base}/places/{}/spec", place.place_id), &place.card.content)?;
262 if let Some(toks) = tokens_by_place.get(&place.place_id) {
263 for (idx, tok) in toks.iter().enumerate() {
264 self.adapter.put_file(&format!("{base}/places/{}/tokens/{idx}", place.place_id), &tok.card.content)?;
265 }
266 }
267 }
268
269 for trans in &transitions {
270 self.adapter.put_file(&format!("{base}/transitions/{}/spec", trans.transition_id), &trans.card.content)?;
271 }
272
273 for (fref, receipt) in &self.firings {
274 let safe_ref = fref.replace(':', "_");
275 self.adapter.put_file(&format!("{base}/firings/{safe_ref}"), &receipt.card.content)?;
276 }
277
278 Ok(())
279 }
280
281 pub fn read_resource(&self, subpath: &str) -> Result<String, String> {
282 let clean = subpath.trim_start_matches('/');
283 let base = self.base_uri();
284 let target = if clean.starts_with(&base) {
285 clean.to_string()
286 } else {
287 format!("{base}/{clean}")
288 };
289 let bytes = self.adapter.cat(&target)?;
290 String::from_utf8(bytes).map_err(|e| e.to_string())
291 }
292
293 pub fn list_resources(&self) -> Result<Vec<String>, String> {
294 self.adapter.ls(&self.base_uri())
295 }
296}
297