Skip to main content

qualia_core_db/bundle/stream/runtime/state/
parents.rs

1//! Stable actual parent bindings plus per-VALUE incarnations, not copied caps.
2use super::super::{RuntimeProfile, TransferRuntime};
3use super::{loans::ParentLoans, RetainedRuntime, RuntimeData};
4use crate::net::peer::runtime::incarnation::CanonicalIncarnation;
5use crate::net::peer::runtime::{
6    FairScheduler, LeaseTable, OperationTable, ReservationLedger, ResourceBudget, ResourceGovernor,
7};
8use crate::net::qdnf::errors::QdnfError as E;
9use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
10use std::sync::Mutex;
11#[derive(Clone, Copy, PartialEq, Eq)]
12pub(super) struct ParentIdentities {
13    pub ledger: CanonicalIncarnation,
14    pub leases: CanonicalIncarnation,
15    pub operations: CanonicalIncarnation,
16    pub scheduler: CanonicalIncarnation,
17}
18/// Exclusive registration of real table BINDINGS, with no long-lived locks.
19/// One retained runtime initially. Independent ledger admissions remain possible.
20pub struct RuntimeParents<'host> {
21    pub(super) ledger: &'host Mutex<ReservationLedger>,
22    pub(super) leases: &'host Mutex<LeaseTable>,
23    pub(super) operations: &'host Mutex<OperationTable>,
24    pub(super) scheduler: &'host Mutex<FairScheduler>,
25    pub(super) governor: &'host ResourceGovernor,
26    pub(super) identities: ParentIdentities,
27    pub(super) registration: CanonicalIncarnation,
28    pub(super) active: AtomicUsize,
29    closed: AtomicBool,
30}
31impl<'host> RuntimeParents<'host> {
32    pub fn adopt(
33        ledger: &'host Mutex<ReservationLedger>,
34        leases: &'host mut Mutex<LeaseTable>,
35        operations: &'host mut Mutex<OperationTable>,
36        scheduler: &'host mut Mutex<FairScheduler>,
37        governor: &'host ResourceGovernor,
38    ) -> Result<Self, E> {
39        let mut loans = ParentLoans::acquire(ledger, leases, operations, scheduler)?;
40        // Only initial adoption binds IDs; reattach NEVER repairs/reassigns IDs.
41        let identities = ParentIdentities {
42            ledger: loans.ledger.bind_incarnation()?,
43            leases: loans.leases.bind_incarnation()?,
44            operations: loans.operations.bind_incarnation()?,
45            scheduler: loans.scheduler.bind_incarnation()?,
46        };
47        drop(loans);
48        Ok(Self {
49            ledger,
50            leases,
51            operations,
52            scheduler,
53            governor,
54            identities,
55            registration: CanonicalIncarnation::fresh()?,
56            active: AtomicUsize::new(0),
57            closed: AtomicBool::new(false),
58        })
59    }
60    pub fn admit<'p>(
61        &'p self,
62        profile: RuntimeProfile,
63        control: ResourceBudget,
64    ) -> Result<RetainedRuntime<'p, 'host>, E> {
65        if self.closed.load(Ordering::Acquire) {
66            return Err(E::Closed);
67        }
68        let mut loans = self.loans()?;
69        self.active
70            .compare_exchange(0, usize::MAX, Ordering::AcqRel, Ordering::Acquire)
71            .map_err(|_| E::Capacity)?;
72        // Guard clears ordinary refusal, but retains unknown ownership on panic.
73        struct Claim<'a> {
74            active: &'a AtomicUsize,
75            committed: bool,
76        }
77        impl Drop for Claim<'_> {
78            fn drop(&mut self) {
79                if !self.committed && !std::thread::panicking() {
80                    self.active.store(0, Ordering::Release);
81                }
82            }
83        }
84        let mut claim = Claim {
85            active: &self.active,
86            committed: false,
87        };
88        let counted = super::charged_bytes()?;
89        let runtime = TransferRuntime::new_counted(
90            &mut loans.ledger,
91            &mut loans.leases,
92            &mut loans.operations,
93            &mut loans.scheduler,
94            self.governor,
95            profile,
96            control,
97            counted,
98        )?;
99        let data = RuntimeData::take(runtime);
100        let owner = data.owner;
101        self.active.store(owner, Ordering::Release);
102        claim.committed = true;
103        Ok(RetainedRuntime {
104            parents: self,
105            registration: self.registration,
106            data: Some(data),
107        })
108    }
109    pub(super) fn loans(&self) -> Result<ParentLoans<'_>, E> {
110        if self.closed.load(Ordering::Acquire) {
111            return Err(E::Closed);
112        }
113        let loans =
114            ParentLoans::acquire(self.ledger, self.leases, self.operations, self.scheduler)?;
115        if loans.identities() != self.identities {
116            return Err(E::StaleGeneration);
117        }
118        Ok(loans)
119    }
120    pub(super) fn association(&self, state: &RetainedRuntime<'_, '_>) -> Result<(), E> {
121        let data = state.data.as_ref().ok_or(E::Incomplete)?;
122        if !core::ptr::eq(self, state.parents)
123            || state.registration != self.registration
124            || self.active.load(Ordering::Acquire) != data.owner
125        {
126            return Err(E::StaleGeneration);
127        }
128        Ok(())
129    }
130    /// Drop/lost state retains active count and canonical charge, so close refuses.
131    pub fn try_close(&mut self) -> Result<(), E> {
132        if self.active.load(Ordering::Acquire) != 0 {
133            return Err(E::WouldBlock);
134        }
135        if self.closed.swap(true, Ordering::AcqRel) {
136            return Err(E::DoubleRelease);
137        }
138        Ok(())
139    }
140}