praborrow_core/
lib.rs

1//! Core primitives for distributed ownership enforcement.
2//!
3//! This crate provides `Sovereign<T>`, a wrapper type that tracks ownership
4//! across network boundaries. When a resource is "annexed" (moved to another node),
5//! local access is prohibited.
6//!
7//! # Safety
8//! Uses `UnsafeCell` and `AtomicU8` for interior mutability with thread-safety.
9//! The `Send`/`Sync` implementations are safe when `T` is `Send`/`Sync`.
10
11use std::ops::{Deref, DerefMut};
12use std::sync::atomic::{AtomicU8, Ordering};
13use std::cell::UnsafeCell;
14
15/// The state of a Sovereign resource.
16/// 0: Domestic (Local jurisdiction)
17/// 1: Exiled (Foreign jurisdiction - moved to another node)
18#[derive(Debug, PartialEq, Eq, Clone, Copy)]
19#[repr(u8)]
20pub enum SovereignState {
21    Domestic = 0,
22    Exiled = 1,
23}
24
25/// A wrapper that enforces ownership semantics across network boundaries.
26///
27/// "Memory safety with sovereign integrity."
28pub struct Sovereign<T> {
29    inner: UnsafeCell<T>,
30    state: AtomicU8,
31}
32
33impl<T> Sovereign<T> {
34    /// Creates a new Sovereign resource under domestic jurisdiction.
35    pub fn new(value: T) -> Self {
36        Self {
37            inner: UnsafeCell::new(value),
38            state: AtomicU8::new(SovereignState::Domestic as u8),
39        }
40    }
41
42    /// Annexes the resource, moving it to foreign jurisdiction.
43    ///
44    /// Once annexed, the resource cannot be accessed locally.
45    /// Access attempts will result in a Sovereignty Violation (panic).
46    pub fn annex(&self) -> Result<(), String> {
47        let current = self.state.load(Ordering::SeqCst);
48        if current == SovereignState::Exiled as u8 {
49            return Err("Resource is already under foreign jurisdiction.".to_string());
50        }
51
52        // Diplomatically transition state
53        self.state.store(SovereignState::Exiled as u8, Ordering::SeqCst);
54        Ok(())
55    }
56
57    /// Checks if the resource is currently domestic.
58    fn verify_jurisdiction(&self) {
59        if self.state.load(Ordering::SeqCst) == SovereignState::Exiled as u8 {
60            panic!("SOVEREIGNTY VIOLATION: Resource is under foreign jurisdiction.");
61        }
62    }
63}
64
65impl<T> Deref for Sovereign<T> {
66    type Target = T;
67
68    fn deref(&self) -> &Self::Target {
69        self.verify_jurisdiction();
70        unsafe { &*self.inner.get() }
71    }
72}
73
74impl<T> DerefMut for Sovereign<T> {
75    fn deref_mut(&mut self) -> &mut Self::Target {
76        self.verify_jurisdiction();
77        unsafe { &mut *self.inner.get() }
78    }
79}
80
81// Safety: Sovereign<T> is Send/Sync if T is Send/Sync, as we use AtomicU8 for state
82// and check it before access.
83unsafe impl<T: Send> Send for Sovereign<T> {}
84unsafe impl<T: Sync> Sync for Sovereign<T> {}
85
86/// Protocol for enforcing constitutional invariants.
87pub trait CheckProtocol {
88    fn enforce_law(&self);
89}
90
91/// Error returned when a lease operation fails.
92#[derive(Debug, Clone, PartialEq, Eq)]
93pub enum LeaseError {
94    /// Resource is already leased to another holder.
95    AlreadyLeased,
96    /// Resource is under foreign jurisdiction.
97    ForeignJurisdiction,
98}
99
100/// Represents a lease on a Sovereign resource.
101pub struct Lease<T> {
102    /// The holder's unique identifier.
103    pub holder: u128,
104    /// Duration of the lease.
105    pub duration: std::time::Duration,
106    /// Phantom data for the resource type.
107    _phantom: std::marker::PhantomData<T>,
108}
109
110impl<T> Lease<T> {
111    /// Creates a new lease.
112    pub fn new(holder: u128, duration: std::time::Duration) -> Self {
113        Self {
114            holder,
115            duration,
116            _phantom: std::marker::PhantomData,
117        }
118    }
119}
120
121/// Trait for distributed borrow operations.
122pub trait DistributedBorrow<T> {
123    /// Attempt to acquire a lease on the resource.
124    fn try_hire(&self, candidate_id: u128, term: std::time::Duration) -> Result<Lease<T>, LeaseError>;
125}
126
127impl<T> DistributedBorrow<T> for Sovereign<T> {
128    fn try_hire(&self, candidate_id: u128, term: std::time::Duration) -> Result<Lease<T>, LeaseError> {
129        let current = self.state.load(Ordering::SeqCst);
130        if current == SovereignState::Exiled as u8 {
131            return Err(LeaseError::AlreadyLeased);
132        }
133        
134        // Transition to exiled state (leased)
135        self.state.store(SovereignState::Exiled as u8, Ordering::SeqCst);
136        Ok(Lease::new(candidate_id, term))
137    }
138}