mirror of
https://github.com/eycorsican/leaf.git
synced 2026-12-06 16:01:29 +00:00
outbound/select: refactor
This commit is contained in:
1 parent
aad085fbaa
commit
698529bdf3
6 files changed
+118
-61
No files matched your search
@@ -11,17 +11,20 @@ use crate::RuntimeManager;
|
||||
mod models {
|
||||
use serde_derive::{Deserialize, Serialize};
|
||||
|
||||
#[cfg(feature = "outbound-select")]
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct SelectOptions {
|
||||
pub outbound: Option<String>,
|
||||
pub select: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "outbound-select")]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct SelectReply {
|
||||
pub selected: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "stat")]
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct Stat {
|
||||
pub network: String,
|
||||
@@ -41,6 +44,7 @@ mod handlers {
|
||||
use super::*;
|
||||
use warp::http::StatusCode;
|
||||
|
||||
#[cfg(feature = "outbound-select")]
|
||||
pub async fn select_update(
|
||||
opts: models::SelectOptions,
|
||||
rm: Arc<RuntimeManager>,
|
||||
@@ -57,6 +61,7 @@ mod handlers {
|
||||
Ok(StatusCode::ACCEPTED)
|
||||
}
|
||||
|
||||
#[cfg(feature = "outbound-select")]
|
||||
pub async fn select_get(
|
||||
opts: models::SelectOptions,
|
||||
rm: Arc<RuntimeManager>,
|
||||
@@ -75,6 +80,23 @@ mod handlers {
|
||||
Ok(warp::reply::json(&models::SelectReply { selected: None }))
|
||||
}
|
||||
|
||||
#[cfg(feature = "outbound-select")]
|
||||
pub async fn select_list(
|
||||
opts: models::SelectOptions,
|
||||
rm: Arc<RuntimeManager>,
|
||||
) -> Result<impl warp::Reply, Infallible> {
|
||||
if let models::SelectOptions {
|
||||
outbound: Some(outbound),
|
||||
..
|
||||
} = opts
|
||||
{
|
||||
if let Ok(selects) = rm.get_outbound_selects(&outbound).await {
|
||||
return Ok(warp::reply::json(&selects));
|
||||
}
|
||||
}
|
||||
Ok(warp::reply::json(&models::SelectReply { selected: None }))
|
||||
}
|
||||
|
||||
pub async fn runtime_reload(rm: Arc<RuntimeManager>) -> Result<impl warp::Reply, Infallible> {
|
||||
if rm.reload().await.is_ok() {
|
||||
Ok(StatusCode::OK)
|
||||
@@ -191,6 +213,7 @@ mod filters {
|
||||
}
|
||||
|
||||
// POST /api/v1/app/outbound/select?outbound=Proxy&select=p3
|
||||
#[cfg(feature = "outbound-select")]
|
||||
pub fn select_update(
|
||||
rm: Arc<RuntimeManager>,
|
||||
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
|
||||
@@ -202,6 +225,7 @@ mod filters {
|
||||
}
|
||||
|
||||
// GET /api/v1/app/outbound/select?outbound=Proxy
|
||||
#[cfg(feature = "outbound-select")]
|
||||
pub fn select_get(
|
||||
rm: Arc<RuntimeManager>,
|
||||
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
|
||||
@@ -212,6 +236,18 @@ mod filters {
|
||||
.and_then(handlers::select_get)
|
||||
}
|
||||
|
||||
// GET /api/v1/app/outbound/selects?outbound=Proxy
|
||||
#[cfg(feature = "outbound-select")]
|
||||
pub fn select_list(
|
||||
rm: Arc<RuntimeManager>,
|
||||
) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
|
||||
warp::path!("api" / "v1" / "app" / "outbound" / "selects")
|
||||
.and(warp::get())
|
||||
.and(warp::query::<models::SelectOptions>())
|
||||
.and(with_runtime_manager(rm))
|
||||
.and_then(handlers::select_list)
|
||||
}
|
||||
|
||||
// POST /api/v1/runtime/reload
|
||||
pub fn runtime_reload(
|
||||
rm: Arc<RuntimeManager>,
|
||||
@@ -265,11 +301,15 @@ impl ApiServer {
|
||||
}
|
||||
|
||||
pub fn serve(&self, listen_addr: SocketAddr) -> crate::Runner {
|
||||
let routes = filters::select_update(self.runtime_manager.clone())
|
||||
.or(filters::select_get(self.runtime_manager.clone()))
|
||||
.or(filters::runtime_reload(self.runtime_manager.clone()))
|
||||
let routes = filters::runtime_reload(self.runtime_manager.clone())
|
||||
.or(filters::runtime_shutdown(self.runtime_manager.clone()));
|
||||
|
||||
#[cfg(feature = "outbound-select")]
|
||||
let routes = routes
|
||||
.or(filters::select_update(self.runtime_manager.clone()))
|
||||
.or(filters::select_get(self.runtime_manager.clone()))
|
||||
.or(filters::select_list(self.runtime_manager.clone()));
|
||||
|
||||
#[cfg(feature = "stat")]
|
||||
let routes = routes
|
||||
.or(filters::stat_html(self.runtime_manager.clone()))
|
||||
|
||||
@@ -564,10 +564,10 @@ impl OutboundManager {
|
||||
.map_err(|e| {
|
||||
anyhow!("invalid [{}] outbound settings: {}", &tag, e)
|
||||
})?;
|
||||
let mut actors = HashMap::new();
|
||||
let mut actors = Vec::new();
|
||||
for actor in settings.actors.iter() {
|
||||
if let Some(a) = handlers.get(actor) {
|
||||
actors.insert(actor.to_owned(), a.clone());
|
||||
actors.push(a.clone());
|
||||
} else {
|
||||
continue 'outbounds;
|
||||
}
|
||||
@@ -576,7 +576,14 @@ impl OutboundManager {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut selector = OutboundSelector::new(tag.clone(), actors);
|
||||
let actors_tags: Vec<String> =
|
||||
actors.iter().map(|x| x.tag().to_owned()).collect();
|
||||
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
let selected = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let mut selector =
|
||||
OutboundSelector::new(tag.clone(), actors_tags, selected.clone());
|
||||
if let Ok(Some(selected)) = super::selector::get_selected_from_cache(&tag) {
|
||||
// FIXME handle error
|
||||
let _ = selector.set_selected(&selected);
|
||||
@@ -586,11 +593,10 @@ impl OutboundManager {
|
||||
let selector = Arc::new(RwLock::new(selector));
|
||||
|
||||
let tcp = Box::new(select::TcpHandler {
|
||||
selector: selector.clone(),
|
||||
});
|
||||
let udp = Box::new(select::UdpHandler {
|
||||
selector: selector.clone(),
|
||||
actors: actors.clone(),
|
||||
selected: selected.clone(),
|
||||
});
|
||||
let udp = Box::new(select::UdpHandler { actors, selected });
|
||||
selectors.insert(tag.clone(), selector);
|
||||
let handler = HandlerBuilder::default()
|
||||
.tag(tag.clone())
|
||||
@@ -655,9 +661,7 @@ impl OutboundManager {
|
||||
for (k, v) in selected_outbounds.iter() {
|
||||
for (k2, v2) in selectors.iter_mut() {
|
||||
if k == k2 {
|
||||
if let Some(v) = v {
|
||||
let _ = v2.write().await.set_selected(v);
|
||||
}
|
||||
let _ = v2.write().await.set_selected(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use protobuf::Message;
|
||||
|
||||
use crate::proxy::AnyOutboundHandler;
|
||||
use anyhow::{anyhow, Result};
|
||||
|
||||
fn get_cache_file_path() -> Result<PathBuf> {
|
||||
@@ -44,41 +44,36 @@ pub fn persist_selected_to_cache(id: String, selected: String) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
type OutboundList = Vec<String>;
|
||||
type OutboundIndex = Arc<AtomicUsize>;
|
||||
|
||||
/// OutboundSelector typically associates to a `select` outbound.
|
||||
pub struct OutboundSelector {
|
||||
id: String,
|
||||
handlers: HashMap<String, AnyOutboundHandler>,
|
||||
selected: Option<String>,
|
||||
handlers: OutboundList,
|
||||
selected: OutboundIndex,
|
||||
}
|
||||
|
||||
impl OutboundSelector {
|
||||
pub fn new(id: String, handlers: HashMap<String, AnyOutboundHandler>) -> Self {
|
||||
pub fn new(id: String, handlers: OutboundList, selected: OutboundIndex) -> Self {
|
||||
Self {
|
||||
id,
|
||||
handlers,
|
||||
selected: None,
|
||||
selected,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_selected(&self) -> Option<AnyOutboundHandler> {
|
||||
if let Some(tag) = self.selected.as_ref() {
|
||||
if let Some(h) = self.handlers.get(tag) {
|
||||
return Some(h.clone());
|
||||
}
|
||||
}
|
||||
None
|
||||
pub fn get_available_tags(&self) -> Vec<String> {
|
||||
self.handlers.clone()
|
||||
}
|
||||
|
||||
pub fn get_selected_tag(&self) -> Option<String> {
|
||||
if let Some(tag) = self.selected.as_ref() {
|
||||
return Some(tag.to_owned());
|
||||
}
|
||||
None
|
||||
pub fn get_selected_tag(&self) -> String {
|
||||
self.handlers[self.selected.load(Ordering::Relaxed)].to_owned()
|
||||
}
|
||||
|
||||
pub fn set_selected(&mut self, tag: &str) -> Result<()> {
|
||||
if self.handlers.contains_key(tag) {
|
||||
self.selected.replace(tag.to_string());
|
||||
if let Some(i) = self.handlers.iter().position(|x| x == tag) {
|
||||
self.selected.store(i, Ordering::Relaxed);
|
||||
if let Err(e) = persist_selected_to_cache(self.id.clone(), tag.to_string()) {
|
||||
log::warn!("persist selector state failed: {}", e);
|
||||
}
|
||||
|
||||
+8
-3
@@ -131,9 +131,14 @@ impl RuntimeManager {
|
||||
|
||||
pub async fn get_outbound_selected(&self, outbound: &str) -> Result<String, Error> {
|
||||
if let Some(selector) = self.outbound_manager.read().await.get_selector(outbound) {
|
||||
if let Some(tag) = selector.read().await.get_selected_tag() {
|
||||
return Ok(tag);
|
||||
}
|
||||
return Ok(selector.read().await.get_selected_tag());
|
||||
}
|
||||
Err(Error::Config(anyhow!("not found")))
|
||||
}
|
||||
|
||||
pub async fn get_outbound_selects(&self, outbound: &str) -> Result<Vec<String>, Error> {
|
||||
if let Some(selector) = self.outbound_manager.read().await.get_selector(outbound) {
|
||||
return Ok(selector.read().await.get_available_tags());
|
||||
}
|
||||
Err(Error::Config(anyhow!("not found")))
|
||||
}
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::{io, sync::Arc};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::*;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::{app::outbound::selector::OutboundSelector, proxy::*, session::Session};
|
||||
use crate::{proxy::*, session::Session};
|
||||
|
||||
pub struct Handler {
|
||||
pub selector: Arc<RwLock<OutboundSelector>>,
|
||||
pub actors: Vec<AnyOutboundHandler>,
|
||||
pub selected: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TcpOutboundHandler for Handler {
|
||||
fn connect_addr(&self) -> Option<OutboundConnect> {
|
||||
None
|
||||
fn connect_addr(&self) -> OutboundConnect {
|
||||
let a = &self.actors[self.selected.load(Ordering::Relaxed)];
|
||||
match a.tcp() {
|
||||
Ok(h) => return h.connect_addr(),
|
||||
_ => match a.udp() {
|
||||
Ok(h) => return h.connect_addr(),
|
||||
_ => (),
|
||||
},
|
||||
}
|
||||
OutboundConnect::Unknown
|
||||
}
|
||||
|
||||
async fn handle<'a>(
|
||||
@@ -21,11 +29,8 @@ impl TcpOutboundHandler for Handler {
|
||||
sess: &'a Session,
|
||||
stream: Option<AnyStream>,
|
||||
) -> io::Result<AnyStream> {
|
||||
if let Some(a) = self.selector.read().await.get_selected() {
|
||||
debug!("select handles tcp [{}] to [{}]", sess.destination, a.tag());
|
||||
TcpOutboundHandler::handle(a.as_ref(), sess, stream).await
|
||||
} else {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "no selected outbound"))
|
||||
}
|
||||
let a = &self.actors[self.selected.load(Ordering::Relaxed)];
|
||||
log::debug!("select handles to [{}]", a.tag());
|
||||
a.tcp()?.handle(sess, stream).await
|
||||
}
|
||||
}
|
||||
@@ -1,24 +1,35 @@
|
||||
use std::io;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use log::*;
|
||||
use tokio::sync::RwLock;
|
||||
|
||||
use crate::{app::outbound::selector::OutboundSelector, proxy::*, session::Session};
|
||||
use crate::{proxy::*, session::Session};
|
||||
|
||||
pub struct Handler {
|
||||
pub selector: Arc<RwLock<OutboundSelector>>,
|
||||
pub actors: Vec<AnyOutboundHandler>,
|
||||
pub selected: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UdpOutboundHandler for Handler {
|
||||
fn connect_addr(&self) -> Option<OutboundConnect> {
|
||||
None
|
||||
fn connect_addr(&self) -> OutboundConnect {
|
||||
let a = &self.actors[self.selected.load(Ordering::Relaxed)];
|
||||
match a.udp() {
|
||||
Ok(h) => return h.connect_addr(),
|
||||
_ => match a.tcp() {
|
||||
Ok(h) => return h.connect_addr(),
|
||||
_ => (),
|
||||
},
|
||||
}
|
||||
OutboundConnect::Unknown
|
||||
}
|
||||
|
||||
fn transport_type(&self) -> DatagramTransportType {
|
||||
DatagramTransportType::Undefined
|
||||
let a = &self.actors[self.selected.load(Ordering::Relaxed)];
|
||||
a.udp()
|
||||
.map(|x| x.transport_type())
|
||||
.unwrap_or(DatagramTransportType::Unknown)
|
||||
}
|
||||
|
||||
async fn handle<'a>(
|
||||
@@ -26,11 +37,8 @@ impl UdpOutboundHandler for Handler {
|
||||
sess: &'a Session,
|
||||
transport: Option<AnyOutboundTransport>,
|
||||
) -> io::Result<AnyOutboundDatagram> {
|
||||
if let Some(a) = self.selector.read().await.get_selected() {
|
||||
debug!("select handles tcp [{}] to [{}]", sess.destination, a.tag());
|
||||
UdpOutboundHandler::handle(a.as_ref(), sess, transport).await
|
||||
} else {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "no selected outbound"))
|
||||
}
|
||||
let a = &self.actors[self.selected.load(Ordering::Relaxed)];
|
||||
log::debug!("select handles to [{}]", a.tag());
|
||||
a.udp()?.handle(sess, transport).await
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user