Skip to content

Commit 10d6e1c

Browse files
committed
feat: lazy outbound
1 parent 57ca876 commit 10d6e1c

9 files changed

Lines changed: 147 additions & 35 deletions

File tree

‎crates/wind-base/src/lazy.rs‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
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+
}

‎crates/wind-base/src/lib.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
pub mod direct;
2+
pub mod lazy;
23
pub mod load_balance;
34
pub mod loopback;
45
pub mod resolve;
56
pub mod tunnel;
7+
8+
pub use lazy::LazyOutbound;

‎crates/wind-base/src/load_balance.rs‎

Lines changed: 8 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,7 @@ use tokio::{
1414
sync::Mutex,
1515
};
1616
use tracing::Instrument;
17-
use wind_core::{
18-
OutboundAction,
19-
tcp::AbstractTcpStream,
20-
types::TargetAddr,
21-
udp::UdpStream,
22-
};
17+
use wind_core::{OutboundAction, tcp::AbstractTcpStream, types::TargetAddr, udp::UdpStream};
2318

2419
// ---------------------------------------------------------------------------
2520
// Configuration types
@@ -193,11 +188,7 @@ impl LoadBalanceOutbound {
193188

194189
#[async_trait]
195190
impl OutboundAction for LoadBalanceOutbound {
196-
async fn handle_tcp(
197-
&self,
198-
target: TargetAddr,
199-
stream: Box<dyn AbstractTcpStream + 'static>,
200-
) -> eyre::Result<()> {
191+
async fn handle_tcp(&self, target: TargetAddr, stream: Box<dyn AbstractTcpStream + 'static>) -> eyre::Result<()> {
201192
let idx = self.select_index(&target).await;
202193
let span = tracing::debug_span!("lb_tcp", target = %target, proxy_index = idx);
203194
async move {
@@ -350,9 +341,10 @@ fn parse_http_url(url: &str) -> Option<(&str, u16, &str)> {
350341

351342
#[cfg(test)]
352343
mod tests {
353-
use super::*;
354344
use std::sync::atomic::AtomicBool;
355345

346+
use super::*;
347+
356348
struct DummyOutbound {
357349
_called: AtomicBool,
358350
}
@@ -367,11 +359,7 @@ mod tests {
367359

368360
#[async_trait]
369361
impl OutboundAction for DummyOutbound {
370-
async fn handle_tcp(
371-
&self,
372-
_target: TargetAddr,
373-
_stream: Box<dyn AbstractTcpStream + 'static>,
374-
) -> eyre::Result<()> {
362+
async fn handle_tcp(&self, _target: TargetAddr, _stream: Box<dyn AbstractTcpStream + 'static>) -> eyre::Result<()> {
375363
Ok(())
376364
}
377365

@@ -390,8 +378,9 @@ mod tests {
390378
}
391379

392380
fn make_lb(strategy: LoadBalanceStrategy, n: usize) -> LoadBalanceOutbound {
393-
let proxies: Vec<Arc<dyn OutboundAction>> =
394-
(0..n).map(|_| Arc::new(DummyOutbound::new()) as Arc<dyn OutboundAction>).collect();
381+
let proxies: Vec<Arc<dyn OutboundAction>> = (0..n)
382+
.map(|_| Arc::new(DummyOutbound::new()) as Arc<dyn OutboundAction>)
383+
.collect();
395384
LoadBalanceOutbound::new(make_opts(strategy), proxies)
396385
}
397386

‎crates/wind-base/src/loopback.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,10 @@ pub fn check_loopback(addr: &SocketAddr) -> eyre::Result<()> {
3232

3333
#[cfg(test)]
3434
mod tests {
35-
use super::*;
3635
use std::net::{Ipv4Addr, Ipv6Addr};
3736

37+
use super::*;
38+
3839
#[test]
3940
fn rejects_ipv4_loopback() {
4041
let addr: SocketAddr = ([127, 0, 0, 1], 8080).into();

‎crates/wind-base/src/resolve.rs‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
11
use std::net::SocketAddr;
22

3-
use wind_core::{
4-
resolve::Resolver,
5-
types::TargetAddr,
6-
utils::StackPrefer,
7-
};
3+
use wind_core::{resolve::Resolver, types::TargetAddr, utils::StackPrefer};
84

95
/// Resolve a `TargetAddr` to a single `SocketAddr` using the given resolver.
106
///

‎crates/wind-core/src/app.rs‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,13 @@ type InboundFactory = Box<dyn FnOnce(InboundHooks, Arc<AppContext>) -> Box<dyn D
6767

6868
/// A composable unit of configuration, applied to the [`App`] via
6969
/// [`App::add_plugin`].
70+
///
71+
/// The `build` method is async so plugins can perform I/O (DNS, QUIC
72+
/// handshakes, etc.) during construction. It is called once, immediately
73+
/// inside [`App::add_plugin`].
74+
#[allow(async_fn_in_trait)]
7075
pub trait Plugin {
71-
fn build(self, app: App) -> App;
76+
async fn build(self, app: App) -> App;
7277
}
7378

7479
/// The runtime builder. Construct with [`App::new`], register everything, then
@@ -113,8 +118,8 @@ impl App {
113118
&self.ctx
114119
}
115120

116-
pub fn add_plugin(self, plugin: impl Plugin) -> Self {
117-
plugin.build(self)
121+
pub async fn add_plugin(self, plugin: impl Plugin) -> Self {
122+
plugin.build(self).await
118123
}
119124

120125
pub fn add_outbound(mut self, name: impl Into<String>, handler: Arc<dyn OutboundAction>) -> Self {

‎crates/wind-core/src/dispatcher.rs‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -370,12 +370,10 @@ impl<O: AbstractOutbound + Send + Sync + 'static> OutboundAction for OutboundAsA
370370
}
371371
}
372372

373+
// ---------------------------------------------------------------------------
373374
#[cfg(test)]
374375
mod tests {
375-
use std::sync::{
376-
Arc,
377-
atomic::{AtomicBool, Ordering},
378-
};
376+
use std::sync::atomic::{AtomicBool, Ordering};
379377

380378
use super::*;
381379

‎crates/wind-tuic/src/quinn/outbound.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ use crate::{
2121
proto::{ClientProtoExt, UdpStream as TuicUdpStream},
2222
};
2323

24+
#[derive(Clone)]
2425
pub struct TuicOutboundOpts {
2526
pub peer_addr: SocketAddr,
2627
pub sni: String,

‎crates/wind/src/main.rs‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,8 +146,8 @@ async fn build_dispatcher(outbounds: Vec<OutboundRuntime>, ctx: Arc<AppContext>)
146146

147147
// Two-phase construction:
148148
// 1. Build regular outbounds (tuic, naive) and stash them by tag.
149-
// 2. Build load-balance outbounds, resolving child proxy tags from
150-
// the map built in phase 1.
149+
// 2. Build load-balance outbounds, resolving child proxy tags from the map
150+
// built in phase 1.
151151
let mut handlers: HashMap<String, Arc<dyn wind_core::dispatcher::OutboundAction>> = HashMap::new();
152152
let mut lb_configs: Vec<(String, crate::conf::runtime::LoadBalanceRuntimeOpts)> = Vec::new();
153153

@@ -176,7 +176,10 @@ async fn build_dispatcher(outbounds: Vec<OutboundRuntime>, ctx: Arc<AppContext>)
176176
.iter()
177177
.map(|t| {
178178
handlers.get(t).cloned().ok_or_else(|| {
179-
eyre::eyre!("load-balance '{tag}' references unknown proxy '{t}'; proxies must be declared before the load-balance group")
179+
eyre::eyre!(
180+
"load-balance '{tag}' references unknown proxy '{t}'; proxies must be declared before the \
181+
load-balance group"
182+
)
180183
})
181184
})
182185
.collect::<eyre::Result<Vec<_>>>()?

0 commit comments

Comments
 (0)