1pub mod auth_middleware;
2pub mod cors;
3mod request;
4pub mod response;
5mod router;
6
7pub use request::{HttpRequest, Method};
8#[doc(hidden)]
9pub use request::{ParseError, parse_request, parse_request_with_limits, resolve_body_limit};
10pub use response::ResponseWriter;
11pub use router::ConnWriter;
12pub use router::{Handler, Router};
13
14use rtflow_core::error::{Error, Result};
15use rtflow_security::SecurityConfig;
16use std::{net::SocketAddr, sync::Arc, time::Duration};
17use tokio::{net::TcpListener, sync::RwLock};
18use tokio_util::sync::CancellationToken;
19
20const DEFAULT_MAX_CONNECTIONS: usize = 1024;
21const DEFAULT_MAX_CONNECTIONS_PER_IP: usize = 24;
23const READ_BUF_SIZE: usize = 8192;
24
25#[derive(Clone)]
26pub struct HttpConfig {
27 pub listen: SocketAddr,
28 pub max_connections: usize,
29 pub max_connections_per_ip: usize,
31 pub read_timeout: Duration,
32 pub header_timeout: Duration,
36 pub body_timeout: Duration,
38 pub shutdown_timeout: Duration,
39 pub max_header_bytes: usize,
40 pub max_body_bytes: usize,
41 pub route_body_limits: Vec<(String, usize)>,
46 pub response_timeout: Duration,
50 pub security: SecurityConfig,
51 pub metrics: Option<Arc<rtflow_core::metrics::MetricsRegistry>>,
53 #[cfg(feature = "tls")]
55 pub tls: Option<rtflow_security::TlsServerConfig>,
56 #[cfg(feature = "tls")]
58 pub tls_handshake_timeout: Duration,
59}
60
61impl HttpConfig {
62 pub fn new(listen: SocketAddr) -> Self {
63 Self {
64 listen,
65 max_connections: DEFAULT_MAX_CONNECTIONS,
66 max_connections_per_ip: DEFAULT_MAX_CONNECTIONS_PER_IP,
67 read_timeout: Duration::from_secs(30),
68 header_timeout: Duration::from_secs(10),
69 body_timeout: Duration::from_secs(60),
70 shutdown_timeout: Duration::from_secs(5),
71 max_header_bytes: 8 * 1024,
72 max_body_bytes: 256 * 1024,
73 route_body_limits: Vec::new(),
74 response_timeout: Duration::from_secs(60),
75 security: SecurityConfig::default(),
76 metrics: None,
77 #[cfg(feature = "tls")]
78 tls: None,
79 #[cfg(feature = "tls")]
80 tls_handshake_timeout: Duration::from_secs(5),
81 }
82 }
83
84 #[cfg(feature = "tls")]
86 pub fn with_tls(mut self, tls: rtflow_security::TlsServerConfig) -> Self {
87 self.tls = Some(tls);
88 self
89 }
90
91 pub fn validate(&self) -> Result<()> {
92 if self.max_connections == 0 {
93 return Err(Error::Limit("HTTP max connections"));
94 }
95 if self.read_timeout == Duration::ZERO
96 || self.header_timeout == Duration::ZERO
97 || self.body_timeout == Duration::ZERO
98 || self.response_timeout == Duration::ZERO
99 || self.shutdown_timeout == Duration::ZERO
100 {
101 return Err(Error::Limit("HTTP timeout"));
102 }
103 if self.max_header_bytes == 0 || self.max_body_bytes == 0 {
104 return Err(Error::Limit("HTTP message size"));
105 }
106 if self
107 .route_body_limits
108 .iter()
109 .any(|(prefix, limit)| prefix.is_empty() || *limit == 0)
110 {
111 return Err(Error::Limit("HTTP route body limit"));
112 }
113 Ok(())
114 }
115
116 pub fn with_metrics(mut self, metrics: Arc<rtflow_core::metrics::MetricsRegistry>) -> Self {
118 self.metrics = Some(metrics);
119 self
120 }
121}
122
123static ACTIVE_CONNS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
125
126struct ActiveConn;
128
129impl Drop for ActiveConn {
130 fn drop(&mut self) {
131 ACTIVE_CONNS.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
132 }
133}
134
135pub fn active_connections() -> usize {
137 ACTIVE_CONNS.load(std::sync::atomic::Ordering::Relaxed)
138}
139
140struct PerIpConnections {
145 limit: usize,
146 counts: std::sync::Mutex<std::collections::HashMap<std::net::IpAddr, usize>>,
147}
148
149impl PerIpConnections {
150 fn new(limit: usize) -> Self {
151 Self {
152 limit,
153 counts: std::sync::Mutex::new(std::collections::HashMap::new()),
154 }
155 }
156
157 fn acquire(self: &std::sync::Arc<Self>, ip: std::net::IpAddr) -> Option<PerIpLease> {
158 if self.limit == 0 {
159 return Some(PerIpLease {
160 owner: self.clone(),
161 ip,
162 });
163 }
164 let mut counts = self
165 .counts
166 .lock()
167 .unwrap_or_else(std::sync::PoisonError::into_inner);
168 let used = counts.entry(ip).or_insert(0);
169 if *used >= self.limit {
170 return None;
171 }
172 *used += 1;
173 drop(counts);
174 Some(PerIpLease {
175 owner: self.clone(),
176 ip,
177 })
178 }
179}
180
181struct PerIpLease {
182 owner: std::sync::Arc<PerIpConnections>,
183 ip: std::net::IpAddr,
184}
185
186impl Drop for PerIpLease {
187 fn drop(&mut self) {
188 let mut counts = self
189 .owner
190 .counts
191 .lock()
192 .unwrap_or_else(std::sync::PoisonError::into_inner);
193 if let Some(used) = counts.get_mut(&self.ip) {
194 *used = used.saturating_sub(1);
195 if *used == 0 {
196 counts.remove(&self.ip);
197 }
198 }
199 }
200}
201pub struct HttpServer {
202 listener: Option<TcpListener>,
203 router: Arc<RwLock<Router>>,
204 cancel: CancellationToken,
205 config: HttpConfig,
206 local_addr: SocketAddr,
207}
208
209impl HttpServer {
210 pub async fn bind(config: HttpConfig) -> Result<Self> {
211 config.validate()?;
212 let listener = TcpListener::bind(config.listen).await?;
213 let local_addr = listener.local_addr()?;
214 Ok(Self {
215 listener: Some(listener),
216 router: Arc::new(RwLock::new(Router::new())),
217 cancel: CancellationToken::new(),
218 config,
219 local_addr,
220 })
221 }
222
223 pub fn local_addr(&self) -> SocketAddr {
224 self.local_addr
225 }
226
227 pub async fn add_route(&self, method: Method, pattern: &str, handler: Handler) {
228 let mut router = self.router.write().await;
229 router.add(method, pattern, handler);
230 }
231
232 pub async fn run(&mut self) -> Result<()> {
233 let Some(listener) = self.listener.take() else {
234 return Err(Error::InvalidConfig(
235 "HTTP server run() can only be called once".into(),
236 ));
237 };
238 let router = self.router.clone();
239 let cancel = self.cancel.clone();
240 let security = self.config.security.clone();
241 let metrics = self.config.metrics.clone();
242 let read_timeout = self.config.read_timeout;
243 let header_timeout = self.config.header_timeout;
244 let body_timeout = self.config.body_timeout;
245 let shutdown_timeout = self.config.shutdown_timeout;
246 let max_header_bytes = self.config.max_header_bytes;
247 let max_body_bytes = self.config.max_body_bytes;
248 let route_body_limits = Arc::new(self.config.route_body_limits.clone());
249 let response_timeout = self.config.response_timeout;
250 #[cfg(feature = "tls")]
251 let tls = self.config.tls.clone();
252 #[cfg(feature = "tls")]
253 let tls_handshake_timeout = self.config.tls_handshake_timeout;
254 let connections = Arc::new(tokio::sync::Semaphore::new(self.config.max_connections));
255 let per_ip = Arc::new(PerIpConnections::new(self.config.max_connections_per_ip));
256 let rate_limiter = Arc::new(rtflow_security::ConnectionRateLimiter::new(
257 self.config.security.connection_rate_limit,
258 )?);
259
260 tokio::spawn(async move {
261 let mut tasks = tokio::task::JoinSet::new();
262 loop {
263 tokio::select! {
264 result = listener.accept() => {
265 let (stream, addr) = match result {
266 Ok(value) => value,
267 Err(_) => {
268 tokio::time::sleep(Duration::from_millis(10)).await;
271 continue;
272 }
273 };
274 let _ = stream.set_nodelay(true);
278 if !security.ip_acl.permits(addr.ip()) {
279 tracing::warn!(peer = %addr, "HTTP connection rejected by IP ACL");
280 continue;
281 }
282 if !rate_limiter.admit(addr.ip(), std::time::Instant::now()) {
283 tracing::warn!(peer = %addr, "HTTP connection rejected by rate limit");
284 tokio::spawn(async move {
287 let mut writer = ResponseWriter::new(stream);
288 let _ = writer
289 .write_body(429, "text/plain", b"Too Many Requests")
290 .await;
291 });
292 continue;
293 }
294 let Some(ip_lease) = per_ip.clone().acquire(addr.ip()) else {
295 tracing::warn!(peer = %addr, "HTTP connection rejected: per-IP limit");
296 tokio::spawn(async move {
297 let mut writer = ResponseWriter::new(stream);
298 let _ = writer
299 .write_body(503, "text/plain", b"Too Many Connections")
300 .await;
301 });
302 continue;
303 };
304 let Ok(permit) = connections.clone().try_acquire_owned() else {
305 tokio::spawn(async move {
308 let mut writer = ResponseWriter::new(stream);
309 let _ = writer
310 .write_body(429, "text/plain", b"Too Many Requests")
311 .await;
312 });
313 continue;
314 };
315 let router = router.clone();
316 let security = security.clone();
317 let metrics = metrics.clone();
318 let route_body_limits = route_body_limits.clone();
319 #[cfg(feature = "tls")]
320 let tls = tls.clone();
321 tasks.spawn(async move {
322 let _permit = permit;
323 let _ip_lease = ip_lease;
324 ACTIVE_CONNS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
325 let _active = ActiveConn;
326 if let Some(metrics) = &metrics {
327 use std::sync::atomic::Ordering;
328 metrics.http_requests_total.fetch_add(1, Ordering::Relaxed);
329 }
330 let result = {
331 #[cfg(feature = "tls")]
332 {
333 if let Some(tls) = tls {
334 let acceptor = tokio_rustls::TlsAcceptor::from(tls.config);
335 match tokio::time::timeout(
336 tls_handshake_timeout,
337 acceptor.accept(stream),
338 )
339 .await
340 {
341 Ok(Ok(tls_stream)) => {
342 let (reader, writer) = tokio::io::split(tls_stream);
343 handle_connection(
344 Some(addr),
345 reader,
346 ConnWriter::Tls(writer),
347 router,
348 security,
349 read_timeout,
350 header_timeout,
351 body_timeout,
352 max_header_bytes,
353 max_body_bytes,
354 &route_body_limits,
355 response_timeout,
356 )
357 .await
358 }
359 Ok(Err(error)) => Err(Error::Tls(error.to_string())),
360 Err(_) => Err(Error::Tls("TLS handshake timeout".into())),
361 }
362 } else {
363 let (reader, writer) = stream.into_split();
364 handle_connection(
365 Some(addr),
366 reader,
367 ConnWriter::Tcp(writer),
368 router,
369 security,
370 read_timeout,
371 header_timeout,
372 body_timeout,
373 max_header_bytes,
374 max_body_bytes,
375 &route_body_limits,
376 response_timeout,
377 )
378 .await
379 }
380 }
381 #[cfg(not(feature = "tls"))]
382 {
383 let (reader, writer) = stream.into_split();
384 handle_connection(
385 Some(addr),
386 reader,
387 ConnWriter::Tcp(writer),
388 router,
389 security,
390 read_timeout,
391 header_timeout,
392 body_timeout,
393 max_header_bytes,
394 max_body_bytes,
395 &route_body_limits,
396 response_timeout,
397 )
398 .await
399 }
400 };
401 if let Err(e) = result {
402 tracing::debug!("http connection error: {e}");
403 }
404 });
405 }
406 _ = cancel.cancelled() => break,
407 }
408 while tasks.try_join_next().is_some() {}
418 }
419 let _ = tokio::time::timeout(shutdown_timeout, async {
420 while tasks.join_next().await.is_some() {}
421 })
422 .await;
423 tasks.abort_all();
424 });
425
426 tracing::info!("http server listening on {}", self.local_addr);
427 Ok(())
428 }
429
430 pub fn shutdown(&self) {
431 self.cancel.cancel();
432 }
433
434 pub fn cancellation_token(&self) -> tokio_util::sync::CancellationToken {
437 self.cancel.clone()
438 }
439}
440
441#[allow(clippy::too_many_arguments)]
442async fn handle_connection<R>(
443 peer: Option<SocketAddr>,
444 mut read_half: R,
445 write_half: ConnWriter,
446 router: Arc<RwLock<Router>>,
447 security: SecurityConfig,
448 read_timeout: Duration,
449 header_timeout: Duration,
450 body_timeout: Duration,
451 max_header_bytes: usize,
452 max_body_bytes: usize,
453 route_body_limits: &[(String, usize)],
454 response_timeout: Duration,
455) -> Result<()>
456where
457 R: tokio::io::AsyncRead + Unpin,
458{
459 if let Some(peer_addr) = peer
461 && !security.ip_acl.permits(peer_addr.ip())
462 {
463 return Err(Error::Unauthorized);
464 }
465
466 let mut writer =
467 Some(ResponseWriter::new(write_half).with_write_timeout(Some(response_timeout)));
468 let mut buf = Vec::with_capacity(READ_BUF_SIZE);
469 let mut request_started: Option<std::time::Instant> = None;
472
473 loop {
474 let started = *request_started.get_or_insert_with(std::time::Instant::now);
475 let limit = if buf.windows(4).any(|w| w == b"\r\n\r\n") {
476 body_timeout
477 } else {
478 header_timeout
479 };
480 let elapsed = started.elapsed();
481 if elapsed >= limit {
482 if let Some(writer) = writer.as_mut() {
484 let _ = writer
485 .write_body(408, "text/plain", b"Request Timeout")
486 .await;
487 }
488 return Err(Error::Limit("request timeout"));
489 }
490 let budget = (limit - elapsed).min(read_timeout);
491 let mut temp = [0u8; READ_BUF_SIZE];
493 let n = tokio::time::timeout(
494 budget,
495 tokio::io::AsyncReadExt::read(&mut read_half, &mut temp),
496 )
497 .await
498 .map_err(|_| Error::Limit("read timeout"))?
499 .map_err(Error::Io)?;
500
501 if n == 0 {
502 break;
503 }
504 buf.extend_from_slice(&temp[..n]);
505
506 let req = match request::parse_request_with_limits(
508 &buf,
509 max_header_bytes,
510 max_body_bytes,
511 route_body_limits,
512 ) {
513 Ok(Some((req, consumed))) => {
514 buf.drain(..consumed);
515 request_started = None;
516 let mut req = req;
517 req.peer = peer;
518 req
519 }
520 Ok(None) => {
521 if buf.len() > max_header_bytes {
522 return Err(Error::Limit("request headers too large"));
523 }
524 continue;
525 }
526 Err(request::ParseError::Incomplete) => continue,
527 Err(request::ParseError::TooLarge) => {
528 if let Some(writer) = writer.as_mut() {
530 let _ = writer
531 .write_body(413, "text/plain", b"Payload Too Large")
532 .await;
533 }
534 return Err(Error::Limit("request too large"));
535 }
536 Err(request::ParseError::Invalid) => {
537 if let Some(writer) = writer.as_mut() {
541 let _ = writer.write_body(400, "text/plain", b"Bad Request").await;
542 }
543 return Err(Error::Http("invalid HTTP request".into()));
544 }
545 };
546
547 tracing::trace!(peer = ?peer, method = ?req.method, path = %req.path, "HTTP request");
548 let keep_alive = !req
549 .header("connection")
550 .is_some_and(|value| value.eq_ignore_ascii_case("close"));
551
552 let req_method = req.method.clone();
553 let req_path = req.path.clone();
554 let mut w = writer.take().expect("writer should be available");
555 w.reset();
559 let guard = router.read().await;
560 let (handler, params) = guard.route(&req.method, &req.path.clone());
561 let handler = handler.clone();
562 let mut req = req;
563 req.path = request::percent_decode(&req.path);
566 req.path_params = params
567 .into_iter()
568 .map(|param| request::percent_decode(¶m))
569 .collect();
570 drop(guard);
571
572 match handler(req, w).await {
573 Ok(returned_writer) => {
574 let close = returned_writer.should_close();
575 writer = Some(returned_writer);
576 if close {
577 break;
578 }
579 }
580 Err(e) => {
581 let msg = e.to_string();
584 let peer_gone = msg.contains("Connection reset by peer")
585 || msg.contains("Broken pipe")
586 || msg.contains("connection closed")
587 || msg.contains("UnexpectedEof");
588 if peer_gone {
589 tracing::debug!(peer = ?peer, method = ?req_method, path = %req_path, %e, "客户端提前断开");
590 } else {
591 tracing::warn!(peer = ?peer, method = ?req_method, path = %req_path, %e, "HTTP handler error");
592 }
593 break;
594 }
595 }
596
597 if !keep_alive {
598 break;
599 }
600 }
601
602 if let Some(mut w) = writer.take() {
606 let _ = w.flush().await;
607 let mut inner = w.into_inner();
608 let _ = tokio::io::AsyncWriteExt::shutdown(&mut inner).await;
609 }
610
611 Ok(())
612}