Skip to main content

reth_tasks/
lazy.rs

1//! A lazily-resolved handle to a value computed on a background thread.
2
3use reth_concurrency::sync::{parking_lot::Mutex, OnceLock};
4use std::sync::Arc;
5use tokio::sync::oneshot;
6
7#[cfg(all(feature = "fuzz", dst))]
8use reth_concurrency::sync::time::{self, Duration};
9#[cfg(all(feature = "fuzz", dst))]
10use tokio::sync::oneshot::error::TryRecvError;
11
12/// Handle to a value computed on a background thread.
13///
14/// The computation is spawned immediately on creation and runs concurrently.
15/// The result is resolved on first access via [`Self::get`] and cached in a
16/// [`OnceLock`] for subsequent calls.
17///
18/// This type is cheaply cloneable via internal [`Arc`].
19///
20/// Create via [`Runtime::spawn_blocking_named`](crate::Runtime::spawn_blocking_named).
21#[derive(Clone)]
22pub struct LazyHandle<T> {
23    inner: Arc<LazyHandleInner<T>>,
24}
25
26struct LazyHandleInner<T> {
27    /// Pending receiver, taken on first access.
28    rx: Mutex<Option<oneshot::Receiver<T>>>,
29    /// Cached result after the first successful receive.
30    value: OnceLock<T>,
31}
32
33impl<T: Send + 'static> LazyHandle<T> {
34    /// Creates a new handle from a background task receiver.
35    pub(crate) fn new(rx: oneshot::Receiver<T>) -> Self {
36        Self {
37            inner: Arc::new(LazyHandleInner { rx: Mutex::new(Some(rx)), value: OnceLock::new() }),
38        }
39    }
40
41    /// Creates a handle that is already resolved with the given value.
42    pub fn ready(value: T) -> Self {
43        let inner = LazyHandleInner { rx: Mutex::new(None), value: OnceLock::from(value) };
44        Self { inner: Arc::new(inner) }
45    }
46
47    /// Blocks until the background task completes and returns a reference to the result.
48    ///
49    /// On the first call this awaits the receiver; subsequent calls return the cached value
50    /// without blocking.
51    ///
52    /// # Panics
53    ///
54    /// Panics if the background task was dropped without producing a value.
55    pub fn get(&self) -> &T {
56        self.inner.value.get_or_init(|| {
57            let rx = self
58                .inner
59                .rx
60                .lock()
61                .take()
62                .expect("LazyHandle receiver already taken without value being set");
63            #[cfg(not(all(feature = "fuzz", dst)))]
64            {
65                rx.blocking_recv().expect("LazyHandle task dropped without producing a value")
66            }
67            #[cfg(all(feature = "fuzz", dst))]
68            {
69                // Poll and yield to the simulator; Tokio's blocking receive would
70                // park the simulator's only OS thread.
71                let mut rx = rx;
72                loop {
73                    match rx.try_recv() {
74                        Ok(value) => break value,
75                        Err(TryRecvError::Empty) => time::sleep(Duration::from_millis(1)),
76                        Err(TryRecvError::Closed) => {
77                            panic!("LazyHandle task dropped without producing a value")
78                        }
79                    }
80                }
81            }
82        })
83    }
84
85    /// Consumes the handle and returns the inner value if this is the only handle.
86    ///
87    /// Returns `Err(self)` if other clones exist, so the caller can fall back
88    /// to a reference-based path (e.g. `clone_into_sorted` instead of `into_sorted`).
89    ///
90    /// Blocks if the background task hasn't completed yet.
91    pub fn try_into_inner(self) -> Result<T, Self> {
92        self.get();
93        match Arc::try_unwrap(self.inner) {
94            Ok(inner) => Ok(inner.value.into_inner().expect("value was just set by get()")),
95            Err(arc) => Err(Self { inner: arc }),
96        }
97    }
98}
99
100impl<T: Send + std::fmt::Debug + 'static> std::fmt::Debug for LazyHandle<T> {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        let mut s = f.debug_struct("LazyHandle");
103        if let Some(value) = self.inner.value.get() {
104            s.field("value", value);
105        } else {
106            s.field("value", &"<pending>");
107        }
108        s.finish()
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115
116    #[reth_concurrency::test]
117    fn test_lazy_handle_resolves() {
118        let (tx, rx) = oneshot::channel();
119        let handle = LazyHandle::new(rx);
120        tx.send(42u64).unwrap();
121        assert_eq!(*handle.get(), 42);
122        // subsequent calls return cached value
123        assert_eq!(*handle.get(), 42);
124    }
125
126    #[reth_concurrency::test]
127    fn test_lazy_handle_clone_shares_value() {
128        let (tx, rx) = oneshot::channel();
129        let handle = LazyHandle::new(rx);
130        let handle2 = handle.clone();
131        tx.send(99u64).unwrap();
132        assert_eq!(*handle.get(), 99);
133        assert_eq!(*handle2.get(), 99);
134    }
135
136    #[reth_concurrency::test]
137    fn test_lazy_handle_try_into_inner() {
138        let (tx, rx) = oneshot::channel();
139        let handle = LazyHandle::new(rx);
140        tx.send(String::from("hello")).unwrap();
141        assert_eq!(handle.try_into_inner().unwrap(), "hello");
142    }
143
144    #[reth_concurrency::test]
145    fn test_lazy_handle_try_into_inner_returns_self_with_clone() {
146        let (tx, rx) = oneshot::channel();
147        let handle = LazyHandle::new(rx);
148        let _clone = handle.clone();
149        tx.send(String::from("hello")).unwrap();
150        let handle = handle.try_into_inner().unwrap_err();
151        assert_eq!(*handle.get(), "hello");
152    }
153
154    #[reth_concurrency::test]
155    #[should_panic(expected = "LazyHandle task dropped without producing a value")]
156    fn test_lazy_handle_panics_on_dropped_sender() {
157        let (_tx, rx) = oneshot::channel::<u64>();
158        let handle = LazyHandle::new(rx);
159        drop(_tx);
160        handle.get();
161    }
162}