1use crate::domain::{MCard, PCardDefinition};
17use crate::fiber::disposable::DisposableList;
18use std::sync::{Arc, Mutex};
19use std::time::{SystemTime, UNIX_EPOCH};
20
21#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum FibrationError {
24 DisposableUnwindError(Vec<String>),
25 LockError(String),
26 AxiomViolation(String),
27 CarrierMismatch(String),
28}
29
30impl std::fmt::Display for FibrationError {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 match self {
33 Self::DisposableUnwindError(errs) => {
34 write!(f, "Fibration LIFO unwinding failed: {}", errs.join("; "))
35 }
36 Self::LockError(msg) => write!(f, "Fibration lock error: {}", msg),
37 Self::AxiomViolation(msg) => write!(f, "Fibration axiom violation: {}", msg),
38 Self::CarrierMismatch(msg) => write!(f, "Fibration carrier mismatch: {}", msg),
39 }
40 }
41}
42
43impl std::error::Error for FibrationError {}
44
45pub trait Fibration<M = MCard, P = PCardDefinition>: Send + Sync {
47 fn project(&self) -> &M;
50
51 fn carrier_handle(&self) -> Option<&str>;
53
54 fn lift_mutation(&mut self, next_carrier: M) -> Result<(), FibrationError>;
57
58 fn lift_handle_rebind(&mut self, new_handle: impl Into<String>) -> Result<(), FibrationError>;
60}
61
62#[derive(Clone)]
65pub struct ProcessObject<M = MCard, P = PCardDefinition> {
66 pub carrier: M,
68 pub carrier_handle: Option<String>,
70 pub disposables: Arc<Mutex<DisposableList>>,
72 pub pcard: Option<P>,
74 pub created_at: u64,
76 pub is_active: bool,
78}
79
80impl<M> ProcessObject<M, PCardDefinition> {
81 pub fn new(carrier: M) -> Self {
83 let now = SystemTime::now()
84 .duration_since(UNIX_EPOCH)
85 .map(|d| d.as_millis() as u64)
86 .unwrap_or(0);
87
88 Self {
89 carrier,
90 carrier_handle: None,
91 disposables: Arc::new(Mutex::new(DisposableList::new())),
92 pcard: None,
93 created_at: now,
94 is_active: true,
95 }
96 }
97}
98
99impl<M, P> ProcessObject<M, P> {
100 pub fn new_with_pcard(carrier: M, pcard: P) -> Self {
102 let now = SystemTime::now()
103 .duration_since(UNIX_EPOCH)
104 .map(|d| d.as_millis() as u64)
105 .unwrap_or(0);
106
107 Self {
108 carrier,
109 carrier_handle: None,
110 disposables: Arc::new(Mutex::new(DisposableList::new())),
111 pcard: Some(pcard),
112 created_at: now,
113 is_active: true,
114 }
115 }
116
117 pub fn with_handle(mut self, handle: impl Into<String>) -> Self {
119 self.carrier_handle = Some(handle.into());
120 self
121 }
122
123 pub fn with_pcard(mut self, pcard: P) -> Self {
125 self.pcard = Some(pcard);
126 self
127 }
128
129 pub fn register_disposable<F>(&self, cleanup: F) -> Result<(), FibrationError>
131 where
132 F: FnOnce() -> Result<(), String> + Send + 'static,
133 {
134 let mut list = self
135 .disposables
136 .lock()
137 .map_err(|e| FibrationError::LockError(e.to_string()))?;
138 list.push(cleanup);
139 Ok(())
140 }
141
142 pub fn pending_disposers_count(&self) -> Result<usize, FibrationError> {
144 let list = self
145 .disposables
146 .lock()
147 .map_err(|e| FibrationError::LockError(e.to_string()))?;
148 Ok(list.len())
149 }
150
151 pub fn unwind(&self) -> Result<(), FibrationError> {
153 let mut list = self
154 .disposables
155 .lock()
156 .map_err(|e| FibrationError::LockError(e.to_string()))?;
157 let active_list = std::mem::take(&mut *list);
158 active_list
159 .dispose()
160 .map_err(FibrationError::DisposableUnwindError)
161 }
162}
163
164impl<M: Send + Sync, P: Send + Sync> Fibration<M, P> for ProcessObject<M, P> {
165 fn project(&self) -> &M {
166 &self.carrier
167 }
168
169 fn carrier_handle(&self) -> Option<&str> {
170 self.carrier_handle.as_deref()
171 }
172
173 fn lift_mutation(&mut self, next_carrier: M) -> Result<(), FibrationError> {
174 self.unwind()?;
176
177 self.carrier = next_carrier;
179
180 let mut list = self
182 .disposables
183 .lock()
184 .map_err(|e| FibrationError::LockError(e.to_string()))?;
185 *list = DisposableList::new();
186 self.is_active = true;
187
188 Ok(())
189 }
190
191 fn lift_handle_rebind(&mut self, new_handle: impl Into<String>) -> Result<(), FibrationError> {
192 self.carrier_handle = Some(new_handle.into());
193 Ok(())
194 }
195}
196
197pub struct CartesianLiftEngine;
199
200impl CartesianLiftEngine {
201 pub fn lift_mutation<M: Send + Sync, P: Send + Sync>(
203 process: &mut ProcessObject<M, P>,
204 next_carrier: M,
205 ) -> Result<(), FibrationError> {
206 process.lift_mutation(next_carrier)
207 }
208
209 pub fn lift_handle_rebind<M: Send + Sync, P: Send + Sync>(
211 process: &mut ProcessObject<M, P>,
212 new_handle: impl Into<String>,
213 ) -> Result<(), FibrationError> {
214 process.lift_handle_rebind(new_handle)
215 }
216}
217
218pub fn verify_fibration_axioms<M: PartialEq + Send + Sync, P: Send + Sync>(
222 initial: &ProcessObject<M, P>,
223 lifted: &ProcessObject<M, P>,
224 target_carrier: &M,
225) -> Result<(), FibrationError> {
226 if lifted.project() != target_carrier {
228 return Err(FibrationError::AxiomViolation(
229 "Projection commutativity failed: pi(lift(f)) != cod(f)".to_string(),
230 ));
231 }
232
233 if lifted.pending_disposers_count()? != 0 {
235 return Err(FibrationError::AxiomViolation(
236 "Zero-residual state failed: lifted fiber retained pending disposers".to_string(),
237 ));
238 }
239
240 let _ = initial.project();
242
243 Ok(())
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249 use crate::domain::{MCard, MCardPayload};
250 use crate::types::AgentDid;
251
252 #[test]
253 fn test_fibration_projection_and_lifo_unwind() {
254 let author = AgentDid::new("did:key:alice").unwrap();
255 let card1 = MCard::new(
256 "mcard:test/1",
257 MCardPayload::Text("Initial".to_string()),
258 author.clone(),
259 1,
260 );
261 let card2 = MCard::new(
262 "mcard:test/2",
263 MCardPayload::Text("Updated".to_string()),
264 author,
265 2,
266 );
267
268 let mut process = ProcessObject::new(card1.clone()).with_handle("assets:doc.md");
269
270 assert_eq!(process.project().uri, "mcard:test/1");
272 assert_eq!(process.carrier_handle(), Some("assets:doc.md"));
273
274 let log = Arc::new(Mutex::new(Vec::new()));
276 let log1 = log.clone();
277 let log2 = log.clone();
278 let log3 = log.clone();
279
280 process
281 .register_disposable(move || {
282 log1.lock().unwrap().push(1);
283 Ok(())
284 })
285 .unwrap();
286
287 process
288 .register_disposable(move || {
289 log2.lock().unwrap().push(2);
290 Ok(())
291 })
292 .unwrap();
293
294 process
295 .register_disposable(move || {
296 log3.lock().unwrap().push(3);
297 Ok(())
298 })
299 .unwrap();
300
301 assert_eq!(process.pending_disposers_count().unwrap(), 3);
302
303 process.lift_mutation(card2.clone()).unwrap();
305
306 assert_eq!(process.project().uri, "mcard:test/2");
308
309 let recorded = log.lock().unwrap().clone();
311 assert_eq!(recorded, vec![3, 2, 1], "Unwinding order must be strict reverse LIFO");
312
313 assert_eq!(process.pending_disposers_count().unwrap(), 0);
315
316 verify_fibration_axioms(&ProcessObject::new(card1), &process, &card2).unwrap();
318 }
319
320 #[test]
321 fn test_handle_rebinding() {
322 let author = AgentDid::new("did:key:alice").unwrap();
323 let card = MCard::new(
324 "mcard:test/rebind",
325 MCardPayload::Text("Hello".to_string()),
326 author,
327 1,
328 );
329
330 let mut process = ProcessObject::new(card);
331 assert_eq!(process.carrier_handle(), None);
332
333 process.lift_handle_rebind("assets:renamed.txt").unwrap();
334 assert_eq!(process.carrier_handle(), Some("assets:renamed.txt"));
335 }
336}