faucet_server/server/router/
mod.rs1use std::{
2 collections::HashSet, ffi::OsStr, net::SocketAddr, num::NonZeroUsize, path::PathBuf, pin::pin,
3 sync::Arc,
4};
5
6use hyper::{body::Incoming, server::conn::http1, service::service_fn, Request, Uri};
7use hyper_util::rt::TokioIo;
8use tokio::net::TcpListener;
9use tokio_tungstenite::tungstenite::http::uri::PathAndQuery;
10
11use super::{onion::Service, FaucetServerBuilder, FaucetServerService};
12use crate::{
13 client::{
14 load_balancing::{IpExtractor, Strategy},
15 worker::{WorkerConfigs, WorkerType},
16 ExclusiveBody,
17 },
18 error::{FaucetError, FaucetResult},
19 shutdown::ShutdownSignal,
20};
21
22fn default_workdir() -> PathBuf {
23 PathBuf::from(".")
24}
25
26#[derive(serde::Deserialize)]
27struct ReducedServerConfig {
28 pub strategy: Option<Strategy>,
29 #[serde(default = "default_workdir")]
30 pub workdir: PathBuf,
31 pub app_dir: Option<String>,
32 pub workers: NonZeroUsize,
33 pub server_type: WorkerType,
34 pub qmd: Option<PathBuf>,
35 pub max_rps: Option<f64>,
36}
37
38#[derive(serde::Deserialize)]
39struct RouteConfig {
40 route: String,
41 #[serde(flatten)]
42 config: ReducedServerConfig,
43}
44
45#[derive(serde::Deserialize)]
46pub struct RouterConfig {
47 route: Vec<RouteConfig>,
48}
49
50#[derive(Clone)]
51struct RouterService {
52 routes: &'static [String],
53 clients: Arc<[FaucetServerService]>,
54}
55
56fn strip_prefix_exact(path_and_query: &PathAndQuery, prefix: &str) -> Option<PathAndQuery> {
57 if path_and_query.path() == prefix {
58 return Some(match path_and_query.query() {
59 Some(query) => format!("/?{query}").parse().unwrap(),
60 None => "/".parse().unwrap(),
61 });
62 }
63 None
64}
65
66fn strip_prefix_relative(path_and_query: &PathAndQuery, prefix: &str) -> Option<PathAndQuery> {
67 let after_prefix = path_and_query.path().strip_prefix(prefix)?;
69
70 let start_slash = after_prefix.starts_with('/');
71
72 Some(match (start_slash, path_and_query.query()) {
73 (true, None) => after_prefix.parse().unwrap(),
74 (true, Some(query)) => format!("{after_prefix}?{query}").parse().unwrap(),
75 (false, None) => format!("/{after_prefix}").parse().unwrap(),
76 (false, Some(query)) => format!("/{after_prefix}?{query}").parse().unwrap(),
77 })
78}
79
80fn strip_prefix(uri: &Uri, prefix: &str) -> Option<Uri> {
81 let path_and_query = uri.path_and_query()?;
82
83 let new_path_and_query = match prefix.ends_with('/') {
84 true => strip_prefix_relative(path_and_query, prefix)?,
85 false => strip_prefix_exact(path_and_query, prefix)?,
86 };
87
88 let mut parts = uri.clone().into_parts();
89 parts.path_and_query = Some(new_path_and_query);
90
91 Some(Uri::from_parts(parts).unwrap())
92}
93
94impl Service<hyper::Request<Incoming>> for RouterService {
95 type Error = FaucetError;
96 type Response = hyper::Response<ExclusiveBody>;
97 async fn call(
98 &self,
99 mut req: hyper::Request<Incoming>,
100 ip_addr: Option<std::net::IpAddr>,
101 ) -> Result<Self::Response, Self::Error> {
102 let mut client = None;
103 for i in 0..self.routes.len() {
104 let route = &self.routes[i];
105 if let Some(new_uri) = strip_prefix(req.uri(), route) {
106 client = Some(&self.clients[i]);
107 *req.uri_mut() = new_uri;
108 break;
109 }
110 }
111 match client {
112 None => Ok(hyper::Response::builder()
113 .status(404)
114 .body(ExclusiveBody::plain_text("404 not found"))
115 .expect("Response should build")),
116 Some(client) => client.call(req, ip_addr).await,
117 }
118 }
119}
120
121impl RouterConfig {
122 async fn into_service(
123 self,
124 rscript: impl AsRef<OsStr>,
125 quarto: impl AsRef<OsStr>,
126 ip_from: IpExtractor,
127 shutdown: &'static ShutdownSignal,
128 ) -> FaucetResult<(RouterService, Vec<WorkerConfigs>)> {
129 let mut all_workers = Vec::with_capacity(self.route.len());
130 let mut routes = Vec::with_capacity(self.route.len());
131 let mut clients = Vec::with_capacity(self.route.len());
132 let mut routes_set = HashSet::with_capacity(self.route.len());
133 for route_conf in self.route.into_iter() {
134 let route = route_conf.route;
135 if !routes_set.insert(route.clone()) {
136 return Err(FaucetError::DuplicateRoute(route));
137 }
138 let (client, workers) = FaucetServerBuilder::new()
139 .workdir(route_conf.config.workdir)
140 .server_type(route_conf.config.server_type)
141 .strategy(route_conf.config.strategy)
142 .rscript(&rscript)
143 .quarto(&quarto)
144 .qmd(route_conf.config.qmd)
145 .workers(route_conf.config.workers.get())
146 .extractor(ip_from)
147 .app_dir(route_conf.config.app_dir)
148 .route(route.clone())
149 .max_rps(route_conf.config.max_rps)
150 .build()?
151 .extract_service(shutdown)
152 .await?;
153 routes.push(route);
154 all_workers.push(workers);
155 clients.push(client);
156 }
157 let routes = routes.leak();
158 let clients = clients.into();
159 let service = RouterService { clients, routes };
160 Ok((service, all_workers))
161 }
162}
163
164impl RouterConfig {
165 pub async fn run(
166 self,
167 rscript: impl AsRef<OsStr>,
168 quarto: impl AsRef<OsStr>,
169 ip_from: IpExtractor,
170 addr: SocketAddr,
171 shutdown: &'static ShutdownSignal,
172 ) -> FaucetResult<()> {
173 let (service, all_workers) = self
174 .into_service(rscript, quarto, ip_from, shutdown)
175 .await?;
176 let listener = TcpListener::bind(addr).await?;
178 log::info!(target: "faucet", "Listening on http://{addr}");
179 let main_loop = || async {
180 loop {
181 match listener.accept().await {
182 Err(e) => {
183 log::error!(target: "faucet", "Unable to accept TCP connection: {e}");
184 return;
185 }
186 Ok((tcp, client_addr)) => {
187 let tcp = TokioIo::new(tcp);
188 log::debug!(target: "faucet", "Accepted TCP connection from {client_addr}");
189
190 let service = service.clone();
191
192 tokio::task::spawn(async move {
193 let mut conn = http1::Builder::new()
194 .serve_connection(
195 tcp,
196 service_fn(|req: Request<Incoming>| {
197 service.call(req, Some(client_addr.ip()))
198 }),
199 )
200 .with_upgrades();
201
202 let conn = pin!(&mut conn);
203
204 tokio::select! {
205 result = conn => {
206 if let Err(e) = result {
207 log::error!(target: "faucet", "Connection error: {e:?}");
208 }
209 }
210 _ = shutdown.wait() => ()
211 }
212 });
213 }
214 }
215 }
216 };
217
218 tokio::select! {
220 _ = shutdown.wait() => (),
221 _ = main_loop() => (),
222 }
223
224 for w in all_workers.iter().flat_map(|ws| &ws.workers) {
226 w.wait_until_done().await;
227 }
228
229 FaucetResult::Ok(())
230 }
231}