cranpose_core/
applier_host.rs1use 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#[derive(Default)]
14pub struct NodeDisposal {
15 nodes: Vec<(NodeId, u32)>,
16 lifecycle: SlotLifecycleCoordinator,
17 slot_hosts: Vec<Rc<SlotsHost>>,
18}
19
20impl NodeDisposal {
21 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 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
125pub trait ApplierHost {
127 fn borrow_dyn(&self) -> ApplierGuard<'_, dyn Applier>;
130
131 fn dispose_nodes(&self, disposal: NodeDisposal) -> Result<(), NodeError>;
153
154 fn compact(&self) {}
156}
157
158pub struct ConcreteApplierHost<A: Applier + 'static> {
160 inner: RefCell<A>,
161 disposals: NodeDisposalQueue,
162}
163
164impl<A: Applier + 'static> ConcreteApplierHost<A> {
165 pub fn new(applier: A) -> Self {
167 Self {
168 inner: RefCell::new(applier),
169 disposals: NodeDisposalQueue::default(),
170 }
171 }
172
173 pub fn borrow_typed(&self) -> ApplierGuard<'_, A> {
175 self.guard(self.inner.borrow_mut())
176 }
177
178 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 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
247pub 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 #[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}