commonware_runtime/utils/
cell.rs1use crate::{signal, Error, Handle};
2use governor::clock::{Clock as GClock, ReasonablyRealtime};
3use prometheus_client::registry::Metric;
4use rand::{CryptoRng, RngCore};
5use std::{
6 future::Future,
7 net::SocketAddr,
8 num::NonZeroUsize,
9 ops::RangeInclusive,
10 time::{Duration, SystemTime},
11};
12
13const MISSING_CONTEXT: &str = "runtime context missing";
14const DUPLICATE_CONTEXT: &str = "runtime context already present";
15
16#[macro_export]
23macro_rules! spawn_cell {
24 ($cell:expr, $body:expr $(,)?) => {{
25 let __commonware_context = $cell.take();
26 __commonware_context.spawn(move |context| async move {
27 $cell.restore(context);
28 $body
29 })
30 }};
31}
32
33#[derive(Clone, Debug)]
37pub enum Cell<C> {
38 Present(C),
40 Missing,
42}
43
44impl<C> Cell<C> {
45 pub const fn new(context: C) -> Self {
47 Self::Present(context)
48 }
49
50 pub fn take(&mut self) -> C {
52 match std::mem::replace(self, Self::Missing) {
53 Self::Present(context) => context,
54 Self::Missing => panic!("{}", MISSING_CONTEXT),
55 }
56 }
57
58 pub fn restore(&mut self, context: C) {
60 match self {
61 Self::Present(_) => panic!("{}", DUPLICATE_CONTEXT),
62 Self::Missing => {
63 *self = Self::Present(context);
64 }
65 }
66 }
67
68 pub fn as_present(&self) -> &C {
74 match self {
75 Self::Present(context) => context,
76 Self::Missing => panic!("{}", MISSING_CONTEXT),
77 }
78 }
79
80 pub fn as_present_mut(&mut self) -> &mut C {
86 match self {
87 Self::Present(context) => context,
88 Self::Missing => panic!("{}", MISSING_CONTEXT),
89 }
90 }
91
92 pub fn into_present(self) -> C {
98 match self {
99 Self::Present(context) => context,
100 Self::Missing => panic!("{}", MISSING_CONTEXT),
101 }
102 }
103}
104
105impl<C> crate::Spawner for Cell<C>
106where
107 C: crate::Spawner,
108{
109 fn dedicated(self) -> Self {
110 Self::Present(self.into_present().dedicated())
111 }
112
113 fn shared(self, blocking: bool) -> Self {
114 Self::Present(self.into_present().shared(blocking))
115 }
116
117 fn instrumented(self) -> Self {
118 Self::Present(self.into_present().instrumented())
119 }
120
121 fn spawn<F, Fut, T>(self, f: F) -> Handle<T>
122 where
123 F: FnOnce(Self) -> Fut + Send + 'static,
124 Fut: Future<Output = T> + Send + 'static,
125 T: Send + 'static,
126 {
127 self.into_present()
128 .spawn(move |context| f(Self::Present(context)))
129 }
130
131 fn stop(
132 self,
133 value: i32,
134 timeout: Option<Duration>,
135 ) -> impl Future<Output = Result<(), Error>> + Send {
136 self.into_present().stop(value, timeout)
137 }
138
139 fn stopped(&self) -> signal::Signal {
140 self.as_present().stopped()
141 }
142}
143
144impl<C> crate::Metrics for Cell<C>
145where
146 C: crate::Metrics,
147{
148 fn label(&self) -> String {
149 self.as_present().label()
150 }
151
152 fn with_label(&self, label: &str) -> Self {
153 Self::Present(self.as_present().with_label(label))
154 }
155
156 fn register<N: Into<String>, H: Into<String>>(&self, name: N, help: H, metric: impl Metric) {
157 self.as_present().register(name, help, metric)
158 }
159
160 fn encode(&self) -> String {
161 self.as_present().encode()
162 }
163
164 fn with_attribute(&self, key: &str, value: impl std::fmt::Display) -> Self {
165 Self::Present(self.as_present().with_attribute(key, value))
166 }
167}
168
169impl<C> crate::Clock for Cell<C>
170where
171 C: crate::Clock,
172{
173 fn current(&self) -> SystemTime {
174 self.as_present().current()
175 }
176
177 fn sleep(&self, duration: Duration) -> impl Future<Output = ()> + Send + 'static {
178 self.as_present().sleep(duration)
179 }
180
181 fn sleep_until(&self, deadline: SystemTime) -> impl Future<Output = ()> + Send + 'static {
182 self.as_present().sleep_until(deadline)
183 }
184}
185
186#[cfg(feature = "external")]
187impl<C> crate::Pacer for Cell<C>
188where
189 C: crate::Pacer,
190{
191 fn pace<'a, F, T>(&'a self, latency: Duration, future: F) -> impl Future<Output = T> + Send + 'a
192 where
193 F: Future<Output = T> + Send + 'a,
194 T: Send + 'a,
195 {
196 self.as_present().pace(latency, future)
197 }
198}
199
200commonware_macros::stability_scope!(BETA {
201 use crate::{SinkOf, StreamOf};
202 use commonware_parallel::ThreadPool;
203 use rayon::ThreadPoolBuildError;
204
205 impl<C> crate::ThreadPooler for Cell<C>
206 where
207 C: crate::ThreadPooler,
208 {
209 fn create_thread_pool(
210 &self,
211 concurrency: NonZeroUsize,
212 ) -> Result<ThreadPool, ThreadPoolBuildError> {
213 self.as_present().create_thread_pool(concurrency)
214 }
215 }
216
217 impl<C> crate::Network for Cell<C>
218 where
219 C: crate::Network,
220 {
221 type Listener = <C as crate::Network>::Listener;
222
223 fn bind(
224 &self,
225 socket: SocketAddr,
226 ) -> impl Future<Output = Result<Self::Listener, Error>> + Send {
227 self.as_present().bind(socket)
228 }
229
230 fn dial(
231 &self,
232 socket: SocketAddr,
233 ) -> impl Future<Output = Result<(SinkOf<Self>, StreamOf<Self>), Error>> + Send {
234 self.as_present().dial(socket)
235 }
236 }
237
238 impl<C> crate::Storage for Cell<C>
239 where
240 C: crate::Storage,
241 {
242 type Blob = <C as crate::Storage>::Blob;
243
244 fn open_versioned(
245 &self,
246 partition: &str,
247 name: &[u8],
248 versions: RangeInclusive<u16>,
249 ) -> impl Future<Output = Result<(Self::Blob, u64, u16), Error>> + Send {
250 self.as_present().open_versioned(partition, name, versions)
251 }
252
253 fn remove(
254 &self,
255 partition: &str,
256 name: Option<&[u8]>,
257 ) -> impl Future<Output = Result<(), Error>> + Send {
258 self.as_present().remove(partition, name)
259 }
260
261 fn scan(
262 &self,
263 partition: &str,
264 ) -> impl Future<Output = Result<Vec<Vec<u8>>, Error>> + Send {
265 self.as_present().scan(partition)
266 }
267 }
268
269 impl<C> crate::Resolver for Cell<C>
270 where
271 C: crate::Resolver,
272 {
273 fn resolve(
274 &self,
275 host: &str,
276 ) -> impl Future<Output = Result<Vec<std::net::IpAddr>, crate::Error>> + Send {
277 self.as_present().resolve(host)
278 }
279 }
280});
281
282impl<C> RngCore for Cell<C>
283where
284 C: RngCore,
285{
286 fn next_u32(&mut self) -> u32 {
287 self.as_present_mut().next_u32()
288 }
289
290 fn next_u64(&mut self) -> u64 {
291 self.as_present_mut().next_u64()
292 }
293
294 fn fill_bytes(&mut self, dest: &mut [u8]) {
295 self.as_present_mut().fill_bytes(dest)
296 }
297
298 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> {
299 self.as_present_mut().try_fill_bytes(dest)
300 }
301}
302
303impl<C> CryptoRng for Cell<C> where C: CryptoRng {}
304
305impl<C> GClock for Cell<C>
306where
307 C: GClock,
308{
309 type Instant = <C as GClock>::Instant;
310
311 fn now(&self) -> Self::Instant {
312 self.as_present().now()
313 }
314}
315
316impl<C> ReasonablyRealtime for Cell<C> where C: ReasonablyRealtime {}
317
318impl<C> crate::BufferPooler for Cell<C>
319where
320 C: crate::BufferPooler,
321{
322 fn network_buffer_pool(&self) -> &crate::BufferPool {
323 self.as_present().network_buffer_pool()
324 }
325
326 fn storage_buffer_pool(&self) -> &crate::BufferPool {
327 self.as_present().storage_buffer_pool()
328 }
329}