use crate::domain::{MCard, PCardDefinition};
use crate::fiber::disposable::DisposableList;
use std::sync::{Arc, Mutex};
use std::time::{SystemTime, UNIX_EPOCH};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FibrationError {
DisposableUnwindError(Vec<String>),
LockError(String),
AxiomViolation(String),
CarrierMismatch(String),
}
impl std::fmt::Display for FibrationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::DisposableUnwindError(errs) => {
write!(f, "Fibration LIFO unwinding failed: {}", errs.join("; "))
}
Self::LockError(msg) => write!(f, "Fibration lock error: {}", msg),
Self::AxiomViolation(msg) => write!(f, "Fibration axiom violation: {}", msg),
Self::CarrierMismatch(msg) => write!(f, "Fibration carrier mismatch: {}", msg),
}
}
}
impl std::error::Error for FibrationError {}
pub trait Fibration<M = MCard, P = PCardDefinition>: Send + Sync {
fn project(&self) -> &M;
fn carrier_handle(&self) -> Option<&str>;
fn lift_mutation(&mut self, next_carrier: M) -> Result<(), FibrationError>;
fn lift_handle_rebind(&mut self, new_handle: impl Into<String>) -> Result<(), FibrationError>;
}
#[derive(Clone)]
pub struct ProcessObject<M = MCard, P = PCardDefinition> {
pub carrier: M,
pub carrier_handle: Option<String>,
pub disposables: Arc<Mutex<DisposableList>>,
pub pcard: Option<P>,
pub created_at: u64,
pub is_active: bool,
}
impl<M> ProcessObject<M, PCardDefinition> {
pub fn new(carrier: M) -> Self {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
Self {
carrier,
carrier_handle: None,
disposables: Arc::new(Mutex::new(DisposableList::new())),
pcard: None,
created_at: now,
is_active: true,
}
}
}
impl<M, P> ProcessObject<M, P> {
pub fn new_with_pcard(carrier: M, pcard: P) -> Self {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_millis() as u64)
.unwrap_or(0);
Self {
carrier,
carrier_handle: None,
disposables: Arc::new(Mutex::new(DisposableList::new())),
pcard: Some(pcard),
created_at: now,
is_active: true,
}
}
pub fn with_handle(mut self, handle: impl Into<String>) -> Self {
self.carrier_handle = Some(handle.into());
self
}
pub fn with_pcard(mut self, pcard: P) -> Self {
self.pcard = Some(pcard);
self
}
pub fn register_disposable<F>(&self, cleanup: F) -> Result<(), FibrationError>
where
F: FnOnce() -> Result<(), String> + Send + 'static,
{
let mut list = self
.disposables
.lock()
.map_err(|e| FibrationError::LockError(e.to_string()))?;
list.push(cleanup);
Ok(())
}
pub fn pending_disposers_count(&self) -> Result<usize, FibrationError> {
let list = self
.disposables
.lock()
.map_err(|e| FibrationError::LockError(e.to_string()))?;
Ok(list.len())
}
pub fn unwind(&self) -> Result<(), FibrationError> {
let mut list = self
.disposables
.lock()
.map_err(|e| FibrationError::LockError(e.to_string()))?;
let active_list = std::mem::take(&mut *list);
active_list
.dispose()
.map_err(FibrationError::DisposableUnwindError)
}
}
impl<M: Send + Sync, P: Send + Sync> Fibration<M, P> for ProcessObject<M, P> {
fn project(&self) -> &M {
&self.carrier
}
fn carrier_handle(&self) -> Option<&str> {
self.carrier_handle.as_deref()
}
fn lift_mutation(&mut self, next_carrier: M) -> Result<(), FibrationError> {
self.unwind()?;
self.carrier = next_carrier;
let mut list = self
.disposables
.lock()
.map_err(|e| FibrationError::LockError(e.to_string()))?;
*list = DisposableList::new();
self.is_active = true;
Ok(())
}
fn lift_handle_rebind(&mut self, new_handle: impl Into<String>) -> Result<(), FibrationError> {
self.carrier_handle = Some(new_handle.into());
Ok(())
}
}
pub struct CartesianLiftEngine;
impl CartesianLiftEngine {
pub fn lift_mutation<M: Send + Sync, P: Send + Sync>(
process: &mut ProcessObject<M, P>,
next_carrier: M,
) -> Result<(), FibrationError> {
process.lift_mutation(next_carrier)
}
pub fn lift_handle_rebind<M: Send + Sync, P: Send + Sync>(
process: &mut ProcessObject<M, P>,
new_handle: impl Into<String>,
) -> Result<(), FibrationError> {
process.lift_handle_rebind(new_handle)
}
}
pub fn verify_fibration_axioms<M: PartialEq + Send + Sync, P: Send + Sync>(
initial: &ProcessObject<M, P>,
lifted: &ProcessObject<M, P>,
target_carrier: &M,
) -> Result<(), FibrationError> {
if lifted.project() != target_carrier {
return Err(FibrationError::AxiomViolation(
"Projection commutativity failed: pi(lift(f)) != cod(f)".to_string(),
));
}
if lifted.pending_disposers_count()? != 0 {
return Err(FibrationError::AxiomViolation(
"Zero-residual state failed: lifted fiber retained pending disposers".to_string(),
));
}
let _ = initial.project();
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::domain::{MCard, MCardPayload};
use crate::types::AgentDid;
#[test]
fn test_fibration_projection_and_lifo_unwind() {
let author = AgentDid::new("did:key:alice").unwrap();
let card1 = MCard::new(
"mcard:test/1",
MCardPayload::Text("Initial".to_string()),
author.clone(),
1,
);
let card2 = MCard::new(
"mcard:test/2",
MCardPayload::Text("Updated".to_string()),
author,
2,
);
let mut process = ProcessObject::new(card1.clone()).with_handle("assets:doc.md");
assert_eq!(process.project().uri, "mcard:test/1");
assert_eq!(process.carrier_handle(), Some("assets:doc.md"));
let log = Arc::new(Mutex::new(Vec::new()));
let log1 = log.clone();
let log2 = log.clone();
let log3 = log.clone();
process
.register_disposable(move || {
log1.lock().unwrap().push(1);
Ok(())
})
.unwrap();
process
.register_disposable(move || {
log2.lock().unwrap().push(2);
Ok(())
})
.unwrap();
process
.register_disposable(move || {
log3.lock().unwrap().push(3);
Ok(())
})
.unwrap();
assert_eq!(process.pending_disposers_count().unwrap(), 3);
process.lift_mutation(card2.clone()).unwrap();
assert_eq!(process.project().uri, "mcard:test/2");
let recorded = log.lock().unwrap().clone();
assert_eq!(recorded, vec![3, 2, 1], "Unwinding order must be strict reverse LIFO");
assert_eq!(process.pending_disposers_count().unwrap(), 0);
verify_fibration_axioms(&ProcessObject::new(card1), &process, &card2).unwrap();
}
#[test]
fn test_handle_rebinding() {
let author = AgentDid::new("did:key:alice").unwrap();
let card = MCard::new(
"mcard:test/rebind",
MCardPayload::Text("Hello".to_string()),
author,
1,
);
let mut process = ProcessObject::new(card);
assert_eq!(process.carrier_handle(), None);
process.lift_handle_rebind("assets:renamed.txt").unwrap();
assert_eq!(process.carrier_handle(), Some("assets:renamed.txt"));
}
}