Skip to main content

reth_engine_tree/tree/txpool_prewarm/
control.rs

1use crate::tree::TxPoolPrewarmCacheSnapshot as Snapshot;
2use alloy_primitives::B256;
3use reth_concurrency::sync::{
4    channel::{unbounded, Receiver, Sender},
5    parking_lot::RwLock,
6};
7use std::{
8    fmt::Debug,
9    sync::{Arc, Weak},
10};
11
12/// Sending side of the txpool prewarming worker's control channel.
13pub(super) struct Control<J> {
14    commands: Sender<Command<J>>,
15    publication: Publication,
16}
17
18impl<J> Debug for Control<J> {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        f.debug_struct("Control")
21            .field(
22                "published",
23                &self.publication.read().as_ref().map(|snapshot| snapshot.parent_hash()),
24            )
25            .finish_non_exhaustive()
26    }
27}
28
29impl<J> Control<J> {
30    pub(super) fn new() -> (Arc<Self>, Receiver<Command<J>>) {
31        let (commands, receiver) = unbounded();
32        let publication = Arc::new(RwLock::new(None));
33        (Arc::new(Self { commands, publication }), receiver)
34    }
35
36    pub(super) fn publication(&self) -> Publication {
37        Arc::clone(&self.publication)
38    }
39
40    pub(super) fn start(&self, parent_hash: B256, job: J) {
41        let _ = self.commands.send(Command::Start { parent_hash, job });
42    }
43
44    pub(super) fn pause(self: &Arc<Self>) -> PauseGuard<J> {
45        // Fire-and-forget: the worker never interrupts a transaction mid-execution, so waiting
46        // for it to observe the pause would only add that execution time to the caller's
47        // latency without reducing the overlap.
48        let _ = self.commands.send(Command::Pause);
49        PauseGuard { control: Arc::downgrade(self) }
50    }
51
52    pub(super) fn snapshot(&self, parent_hash: B256) -> Option<Snapshot> {
53        self.publication
54            .read()
55            .as_ref()
56            .filter(|snapshot| snapshot.parent_hash() == parent_hash)
57            .cloned()
58    }
59}
60
61/// Immutable snapshot publication shared by the handle and worker.
62pub(super) type Publication = Arc<RwLock<Option<Snapshot>>>;
63
64/// Commands sent to the txpool prewarming worker.
65pub(super) enum Command<J> {
66    /// Starts prewarming for a canonical head, replacing any previous job.
67    Start { parent_hash: B256, job: J },
68    /// Pauses prewarming until a matching [`Resume`](Self::Resume).
69    Pause,
70    /// Releases one active pause.
71    Resume,
72}
73
74/// One outstanding pause, released when dropped.
75pub(super) struct PauseGuard<J> {
76    control: Weak<Control<J>>,
77}
78
79impl<J> Drop for PauseGuard<J> {
80    fn drop(&mut self) {
81        // If the pause was never delivered the channel is disconnected, and this send fails
82        // just the same, so the worker can never see an unmatched resume.
83        if let Some(control) = self.control.upgrade() {
84            let _ = control.commands.send(Command::Resume);
85        }
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92
93    type TestControl = Control<u64>;
94
95    fn control() -> (Arc<TestControl>, Receiver<Command<u64>>) {
96        TestControl::new()
97    }
98
99    fn snapshot(parent_hash: B256) -> Snapshot {
100        Snapshot::new(parent_hash, Default::default())
101    }
102
103    #[reth_concurrency::test]
104    fn snapshot_is_published_for_matching_parent() {
105        let (control, _receiver) = control();
106        let parent_hash = B256::repeat_byte(0x01);
107        *control.publication.write() = Some(snapshot(parent_hash));
108
109        assert_eq!(
110            control.snapshot(parent_hash).map(|snapshot| snapshot.parent_hash()),
111            Some(parent_hash)
112        );
113        assert!(control.snapshot(B256::ZERO).is_none());
114    }
115
116    #[reth_concurrency::test]
117    fn start_sends_job() {
118        let (control, receiver) = control();
119        let parent_hash = B256::repeat_byte(0x01);
120        control.start(parent_hash, 1);
121
122        assert!(matches!(
123            receiver.try_recv(),
124            Ok(Command::Start { parent_hash: received_parent, job: 1 })
125                if received_parent == parent_hash
126        ));
127    }
128
129    #[reth_concurrency::test]
130    fn pause_guard_does_not_retain_control() {
131        let (control, _receiver) = control();
132        let weak_control = Arc::downgrade(&control);
133        let guard = control.pause();
134
135        drop(control);
136        assert!(weak_control.upgrade().is_none());
137        drop(guard);
138    }
139
140    #[reth_concurrency::test]
141    fn overlapping_pause_guards_send_matching_resumes() {
142        let (control, receiver) = control();
143        let first = control.pause();
144        let second = control.pause();
145        assert!(matches!(receiver.try_recv(), Ok(Command::Pause)));
146        assert!(matches!(receiver.try_recv(), Ok(Command::Pause)));
147
148        drop(first);
149        assert!(matches!(receiver.try_recv(), Ok(Command::Resume)));
150        drop(second);
151        assert!(matches!(receiver.try_recv(), Ok(Command::Resume)));
152    }
153}