|
| 1 | +//! Lazy outbound wrapper — defers initialisation until first connection. |
| 2 | +
|
| 3 | +use std::{future::Future, pin::Pin, sync::Arc}; |
| 4 | + |
| 5 | +use async_trait::async_trait; |
| 6 | +use eyre; |
| 7 | +use tokio::sync::{Mutex, Notify}; |
| 8 | +use wind_core::{OutboundAction, tcp::AbstractTcpStream, types::TargetAddr, udp::UdpStream}; |
| 9 | + |
| 10 | +/// Wraps a future that produces an [`OutboundAction`] and only executes it |
| 11 | +/// once, on the first call to [`handle_tcp`] or [`handle_udp`]. Subsequent |
| 12 | +/// calls delegate to the already-initialised handler. |
| 13 | +/// |
| 14 | +/// Concurrent first-use callers are serialised: one runs the factory while |
| 15 | +/// others wait on a notification. |
| 16 | +pub struct LazyOutbound { |
| 17 | + /// Quad-state: the async factory, a sentinel meaning "another task |
| 18 | + /// is initialising", or the ready handler / a permanent error. |
| 19 | + state: Mutex<LazyState>, |
| 20 | + /// Signalled once initialisation finishes (success or failure) so that |
| 21 | + /// waiters can re-check `state`. |
| 22 | + ready: Notify, |
| 23 | +} |
| 24 | + |
| 25 | +enum LazyState { |
| 26 | + /// Factory has not yet been called. |
| 27 | + Uninit(Pin<Box<dyn Future<Output = eyre::Result<Arc<dyn OutboundAction>>> + Send>>), |
| 28 | + /// One caller is currently running the factory; others must wait. |
| 29 | + Initializing, |
| 30 | + /// The handler is ready. |
| 31 | + Initialized(Arc<dyn OutboundAction>), |
| 32 | + /// Permanent failure — all future calls will return this error. |
| 33 | + Failed(String), |
| 34 | +} |
| 35 | + |
| 36 | +impl LazyOutbound { |
| 37 | + /// Wrap `factory` — an async closure that builds the real outbound — |
| 38 | + /// so that it runs at most once, on first use. |
| 39 | + pub fn new(factory: Pin<Box<dyn Future<Output = eyre::Result<Arc<dyn OutboundAction>>> + Send>>) -> Self { |
| 40 | + Self { |
| 41 | + state: Mutex::new(LazyState::Uninit(factory)), |
| 42 | + ready: Notify::new(), |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + /// Ensure the inner handler is initialised and return a clone of the |
| 47 | + /// `Arc`. This is the core synchronisation point — every public method |
| 48 | + /// calls it first. |
| 49 | + async fn get_or_init(&self) -> eyre::Result<Arc<dyn OutboundAction>> { |
| 50 | + loop { |
| 51 | + { |
| 52 | + let guard = self.state.lock().await; |
| 53 | + match &*guard { |
| 54 | + LazyState::Initialized(h) => return Ok(h.clone()), |
| 55 | + LazyState::Failed(msg) => return Err(eyre::eyre!("LazyOutbound: {msg}")), |
| 56 | + LazyState::Uninit(_) => {} |
| 57 | + LazyState::Initializing => {} |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // Re-check: under the lock we may have seen Uninit or |
| 62 | + // Initializing. Handle each case *outside* the lock so we |
| 63 | + // don't hold it across the (possibly slow) factory future. |
| 64 | + let future = { |
| 65 | + let mut guard = self.state.lock().await; |
| 66 | + match &*guard { |
| 67 | + LazyState::Initialized(h) => return Ok(h.clone()), |
| 68 | + LazyState::Failed(msg) => return Err(eyre::eyre!("LazyOutbound: {msg}")), |
| 69 | + LazyState::Initializing => { |
| 70 | + // Another task is running the factory — wait. |
| 71 | + drop(guard); |
| 72 | + self.ready.notified().await; |
| 73 | + continue; |
| 74 | + } |
| 75 | + LazyState::Uninit(_) => { |
| 76 | + // Take ownership of the future. |
| 77 | + let LazyState::Uninit(fut) = std::mem::replace(&mut *guard, LazyState::Initializing) else { |
| 78 | + unreachable!() |
| 79 | + }; |
| 80 | + fut |
| 81 | + } |
| 82 | + } |
| 83 | + }; |
| 84 | + |
| 85 | + // Run the factory *without* holding the lock. |
| 86 | + let result = future.await; |
| 87 | + let mut guard = self.state.lock().await; |
| 88 | + match result { |
| 89 | + Ok(handler) => { |
| 90 | + *guard = LazyState::Initialized(handler.clone()); |
| 91 | + self.ready.notify_waiters(); |
| 92 | + return Ok(handler); |
| 93 | + } |
| 94 | + Err(e) => { |
| 95 | + let msg = format!("{e:#}"); |
| 96 | + *guard = LazyState::Failed(msg.clone()); |
| 97 | + self.ready.notify_waiters(); |
| 98 | + return Err(eyre::eyre!("LazyOutbound init failed: {msg}")); |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + } |
| 103 | +} |
| 104 | + |
| 105 | +#[async_trait] |
| 106 | +impl OutboundAction for LazyOutbound { |
| 107 | + async fn handle_tcp(&self, target: TargetAddr, stream: Box<dyn AbstractTcpStream + 'static>) -> eyre::Result<()> { |
| 108 | + let handler = self.get_or_init().await?; |
| 109 | + handler.handle_tcp(target, stream).await |
| 110 | + } |
| 111 | + |
| 112 | + async fn handle_udp(&self, stream: UdpStream) -> eyre::Result<()> { |
| 113 | + let handler = self.get_or_init().await?; |
| 114 | + handler.handle_udp(stream).await |
| 115 | + } |
| 116 | +} |
0 commit comments