1use 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#[derive(Clone)]
22pub struct LazyHandle<T> {
23 inner: Arc<LazyHandleInner<T>>,
24}
25
26struct LazyHandleInner<T> {
27 rx: Mutex<Option<oneshot::Receiver<T>>>,
29 value: OnceLock<T>,
31}
32
33impl<T: Send + 'static> LazyHandle<T> {
34 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 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 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 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 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 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}