Skip to main content

cranpose_core/
applier_host.rs

1use std::{
2    cell::{BorrowMutError, Cell, RefCell, RefMut},
3    ops::{Deref, DerefMut},
4    rc::Rc,
5};
6
7use crate::{
8    Applier, NodeError, NodeId, SlotsHost,
9    slot::{DetachedSubtree, SlotLifecycleCoordinator, dispose_detached_node_now},
10};
11
12/// Detached node identities and the resources that must outlive their unmount.
13#[derive(Default)]
14pub struct NodeDisposal {
15    nodes: Vec<(NodeId, u32)>,
16    lifecycle: SlotLifecycleCoordinator,
17    slot_hosts: Vec<Rc<SlotsHost>>,
18}
19
20impl NodeDisposal {
21    /// Creates a disposal batch from node IDs and their current generations.
22    ///
23    /// ```
24    /// use cranpose_core::{Applier, MemoryApplier, Node, NodeDisposal};
25    /// struct Leaf;
26    /// impl Node for Leaf {}
27    /// let mut applier = MemoryApplier::new();
28    /// let id = applier.create(Box::new(Leaf));
29    /// let disposal = NodeDisposal::new(vec![(id, applier.node_generation(id))]);
30    /// ```
31    pub fn new(nodes: Vec<(NodeId, u32)>) -> Self {
32        Self {
33            nodes,
34            lifecycle: SlotLifecycleCoordinator::default(),
35            slot_hosts: Vec::new(),
36        }
37    }
38
39    pub(crate) fn from_subcomposed(
40        disposal: crate::subcompose::SubcomposeDisposal,
41        applier: &dyn Applier,
42    ) -> Self {
43        Self {
44            nodes: disposal
45                .nodes
46                .into_iter()
47                .map(|id| (id, applier.node_generation(id)))
48                .collect(),
49            lifecycle: SlotLifecycleCoordinator::default(),
50            slot_hosts: disposal.slot_hosts,
51        }
52    }
53
54    pub(crate) fn from_host_parts(
55        nodes: Vec<(NodeId, u32)>,
56        lifecycle: SlotLifecycleCoordinator,
57    ) -> Self {
58        Self {
59            nodes,
60            lifecycle,
61            slot_hosts: Vec::new(),
62        }
63    }
64
65    pub(crate) fn retain_subtree(&mut self, subtree: DetachedSubtree) {
66        subtree.append_disposal_roots(&mut self.nodes);
67        self.lifecycle.queue_subtree_disposal(subtree);
68    }
69}
70
71#[derive(Default)]
72struct NodeDisposalQueue {
73    batches: RefCell<Vec<NodeDisposal>>,
74    pending: Cell<bool>,
75}
76
77impl NodeDisposalQueue {
78    fn enqueue(&self, disposal: NodeDisposal) {
79        if !disposal.nodes.is_empty()
80            || !disposal.slot_hosts.is_empty()
81            || disposal.lifecycle.pending_drops_len() != 0
82        {
83            self.batches.borrow_mut().push(disposal);
84            self.pending.set(true);
85        }
86    }
87
88    #[inline(never)]
89    fn flush(&self, applier: &mut dyn Applier) -> Result<(), NodeError> {
90        if !self.pending.get() {
91            return Ok(());
92        }
93        // Keep dropped runtime cells and states alive until every queued node
94        // in this flush unmounts.
95        let _teardown = crate::runtime::enter_state_teardown_scope();
96        while self.pending.get() {
97            let next = self.batches.borrow_mut().pop();
98            let Some(mut batch) = next else {
99                self.pending.set(false);
100                break;
101            };
102            if let Some((node, generation)) = batch.nodes.pop() {
103                let resume_at = self.batches.borrow().len();
104                self.batches.borrow_mut().push(batch);
105                if applier.node_generation(node) == generation
106                    && let Err(error) = dispose_detached_node_now(applier, node)
107                {
108                    self.batches.borrow_mut()[resume_at]
109                        .nodes
110                        .push((node, generation));
111                    return Err(error);
112                }
113            } else if let Some(host) = batch.slot_hosts.pop() {
114                self.batches.borrow_mut().push(batch);
115                drop(host);
116            } else if let Some(payload) = batch.lifecycle.pop_pending_drop() {
117                self.batches.borrow_mut().push(batch);
118                drop(payload);
119            }
120        }
121        Ok(())
122    }
123}
124
125/// Owns an applier and completes node disposal when an outstanding borrow ends.
126pub trait ApplierHost {
127    /// Borrows the applier mutably as a trait object. Dropping the guard finishes any node disposal
128    /// queued while it was held.
129    fn borrow_dyn(&self) -> ApplierGuard<'_, dyn Applier>;
130
131    /// Disposes detached roots, deferring recursive cleanup to the current borrow's guard.
132    ///
133    /// ```
134    /// use cranpose_core::{
135    ///     Applier, ApplierHost, ConcreteApplierHost, MemoryApplier, Node, NodeDisposal,
136    /// };
137    /// # fn example() -> Result<(), cranpose_core::NodeError> {
138    /// struct Leaf;
139    /// impl Node for Leaf {}
140    /// let host = ConcreteApplierHost::new(MemoryApplier::new());
141    /// let mut applier = host.borrow_typed();
142    /// let root = applier.create(Box::new(Leaf));
143    /// host.dispose_nodes(NodeDisposal::new(vec![(
144    ///     root,
145    ///     applier.node_generation(root),
146    /// )]))?;
147    /// drop(applier);
148    /// assert!(host.borrow_typed().get_mut(root).is_err());
149    /// # Ok(())
150    /// # }
151    /// ```
152    fn dispose_nodes(&self, disposal: NodeDisposal) -> Result<(), NodeError>;
153
154    /// Compacts internal storage after commands have been applied.
155    fn compact(&self) {}
156}
157
158/// An [`ApplierHost`] that stores one applier of the concrete type `A`.
159pub struct ConcreteApplierHost<A: Applier + 'static> {
160    inner: RefCell<A>,
161    disposals: NodeDisposalQueue,
162}
163
164impl<A: Applier + 'static> ConcreteApplierHost<A> {
165    /// Creates a host that owns `applier`.
166    pub fn new(applier: A) -> Self {
167        Self {
168            inner: RefCell::new(applier),
169            disposals: NodeDisposalQueue::default(),
170        }
171    }
172
173    /// Borrows the applier mutably with its concrete type. Panics if it is already borrowed.
174    pub fn borrow_typed(&self) -> ApplierGuard<'_, A> {
175        self.guard(self.inner.borrow_mut())
176    }
177
178    /// Borrows the applier mutably with its concrete type. Returns an error if it is already
179    /// borrowed.
180    pub fn try_borrow_typed(&self) -> Result<ApplierGuard<'_, A>, BorrowMutError> {
181        self.inner.try_borrow_mut().map(|inner| self.guard(inner))
182    }
183
184    fn guard<'a>(&'a self, inner: RefMut<'a, A>) -> ApplierGuard<'a, A> {
185        ApplierGuard {
186            inner,
187            disposals: &self.disposals,
188            as_dyn: |applier| applier,
189        }
190    }
191
192    /// Returns the applier after all queued nodes have been disposed.
193    ///
194    /// On failure, returns this host with its pending resources and the error,
195    /// allowing the caller to repair the cause and retry extraction.
196    ///
197    /// ```
198    /// use cranpose_core::{ConcreteApplierHost, MemoryApplier};
199    /// let host = ConcreteApplierHost::new(MemoryApplier::new());
200    /// assert!(host.try_into_inner().is_ok());
201    /// ```
202    pub fn try_into_inner(mut self) -> Result<A, (Self, NodeError)> {
203        if let Err(error) = self.disposals.flush(self.inner.get_mut()) {
204            return Err((self, error));
205        }
206        Ok(self.inner.into_inner())
207    }
208}
209
210impl<A: Applier + 'static> ApplierHost for ConcreteApplierHost<A> {
211    fn borrow_dyn(&self) -> ApplierGuard<'_, dyn Applier> {
212        ApplierGuard {
213            inner: RefMut::map(self.inner.borrow_mut(), |applier| {
214                applier as &mut dyn Applier
215            }),
216            disposals: &self.disposals,
217            as_dyn: |applier| applier,
218        }
219    }
220
221    fn dispose_nodes(&self, mut disposal: NodeDisposal) -> Result<(), NodeError> {
222        if !self.disposals.pending.get()
223            && disposal.nodes.is_empty()
224            && disposal.slot_hosts.is_empty()
225        {
226            flush_drops_in_teardown(&mut disposal.lifecycle);
227            return Ok(());
228        }
229        self.disposals.enqueue(disposal);
230        if let Ok(mut applier) = self.inner.try_borrow_mut() {
231            return self.disposals.flush(&mut *applier);
232        }
233        Ok(())
234    }
235
236    fn compact(&self) {
237        self.borrow_typed().compact();
238    }
239}
240
241#[inline(never)]
242fn flush_drops_in_teardown(lifecycle: &mut SlotLifecycleCoordinator) {
243    let _teardown = crate::runtime::enter_state_teardown_scope();
244    lifecycle.flush_pending_drops();
245}
246
247/// A mutable applier borrow that drains recursive node disposal before returning.
248pub struct ApplierGuard<'a, A: Applier + ?Sized + 'static> {
249    inner: RefMut<'a, A>,
250    disposals: &'a NodeDisposalQueue,
251    as_dyn: fn(&mut A) -> &mut dyn Applier,
252}
253
254impl<A: Applier + ?Sized + 'static> ApplierGuard<'_, A> {
255    // Out of line: few guards have disposals to flush, and every function
256    // that drops a guard stays small.
257    #[cold]
258    #[inline(never)]
259    fn flush_disposals(&mut self) {
260        if let Err(error) = self.disposals.flush((self.as_dyn)(&mut *self.inner)) {
261            log::error!("deferred node disposal failed: {error}");
262        }
263    }
264}
265
266impl<A: Applier + ?Sized + 'static> Deref for ApplierGuard<'_, A> {
267    type Target = A;
268
269    fn deref(&self) -> &Self::Target {
270        &self.inner
271    }
272}
273
274impl<A: Applier + ?Sized + 'static> DerefMut for ApplierGuard<'_, A> {
275    fn deref_mut(&mut self) -> &mut Self::Target {
276        &mut self.inner
277    }
278}
279
280impl<A: Applier + ?Sized + 'static> Drop for ApplierGuard<'_, A> {
281    fn drop(&mut self) {
282        if self.disposals.pending.get() {
283            self.flush_disposals();
284        }
285    }
286}