LCOV - code coverage report
Current view: top level - proxy/src/serverless - mod.rs (source / functions) Coverage Total Hit
Test: 20b6afc7b7f34578dcaab2b3acdaecfe91cd8bf1.info Lines: 0.0 % 343 0
Test Date: 2024-11-25 17:48:16 Functions: 0.0 % 30 0

            Line data    Source code
       1              : //! Routers for our serverless APIs
       2              : //!
       3              : //! Handles both SQL over HTTP and SQL over Websockets.
       4              : 
       5              : mod backend;
       6              : pub mod cancel_set;
       7              : mod conn_pool;
       8              : mod conn_pool_lib;
       9              : mod error;
      10              : mod http_conn_pool;
      11              : mod http_util;
      12              : mod json;
      13              : mod local_conn_pool;
      14              : mod sql_over_http;
      15              : mod websocket;
      16              : 
      17              : use std::net::{IpAddr, SocketAddr};
      18              : use std::pin::{pin, Pin};
      19              : use std::sync::Arc;
      20              : 
      21              : use anyhow::Context;
      22              : use async_trait::async_trait;
      23              : use atomic_take::AtomicTake;
      24              : use bytes::Bytes;
      25              : pub use conn_pool_lib::GlobalConnPoolOptions;
      26              : use futures::future::{select, Either};
      27              : use futures::TryFutureExt;
      28              : use http::{Method, Response, StatusCode};
      29              : use http_body_util::combinators::BoxBody;
      30              : use http_body_util::{BodyExt, Empty};
      31              : use hyper::body::Incoming;
      32              : use hyper_util::rt::TokioExecutor;
      33              : use hyper_util::server::conn::auto::Builder;
      34              : use rand::rngs::StdRng;
      35              : use rand::SeedableRng;
      36              : use sql_over_http::{uuid_to_header_value, NEON_REQUEST_ID};
      37              : use tokio::io::{AsyncRead, AsyncWrite};
      38              : use tokio::net::{TcpListener, TcpStream};
      39              : use tokio::time::timeout;
      40              : use tokio_rustls::TlsAcceptor;
      41              : use tokio_util::sync::CancellationToken;
      42              : use tokio_util::task::TaskTracker;
      43              : use tracing::{info, warn, Instrument};
      44              : use utils::http::error::ApiError;
      45              : 
      46              : use crate::cancellation::CancellationHandlerMain;
      47              : use crate::config::{ProxyConfig, ProxyProtocolV2};
      48              : use crate::context::RequestContext;
      49              : use crate::metrics::Metrics;
      50              : use crate::protocol2::{read_proxy_protocol, ChainRW, ConnectHeader, ConnectionInfo};
      51              : use crate::proxy::run_until_cancelled;
      52              : use crate::rate_limiter::EndpointRateLimiter;
      53              : use crate::serverless::backend::PoolingBackend;
      54              : use crate::serverless::http_util::{api_error_into_response, json_response};
      55              : 
      56              : pub(crate) const SERVERLESS_DRIVER_SNI: &str = "api";
      57              : 
      58            0 : pub async fn task_main(
      59            0 :     config: &'static ProxyConfig,
      60            0 :     auth_backend: &'static crate::auth::Backend<'static, ()>,
      61            0 :     ws_listener: TcpListener,
      62            0 :     cancellation_token: CancellationToken,
      63            0 :     cancellation_handler: Arc<CancellationHandlerMain>,
      64            0 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
      65            0 : ) -> anyhow::Result<()> {
      66            0 :     scopeguard::defer! {
      67            0 :         info!("websocket server has shut down");
      68            0 :     }
      69            0 : 
      70            0 :     let local_pool = local_conn_pool::LocalConnPool::new(&config.http_config);
      71            0 :     let conn_pool = conn_pool_lib::GlobalConnPool::new(&config.http_config);
      72            0 :     {
      73            0 :         let conn_pool = Arc::clone(&conn_pool);
      74            0 :         tokio::spawn(async move {
      75            0 :             conn_pool.gc_worker(StdRng::from_entropy()).await;
      76            0 :         });
      77            0 :     }
      78            0 : 
      79            0 :     // shutdown the connection pool
      80            0 :     tokio::spawn({
      81            0 :         let cancellation_token = cancellation_token.clone();
      82            0 :         let conn_pool = conn_pool.clone();
      83            0 :         async move {
      84            0 :             cancellation_token.cancelled().await;
      85            0 :             tokio::task::spawn_blocking(move || conn_pool.shutdown())
      86            0 :                 .await
      87            0 :                 .unwrap();
      88            0 :         }
      89            0 :     });
      90            0 : 
      91            0 :     let http_conn_pool = conn_pool_lib::GlobalConnPool::new(&config.http_config);
      92            0 :     {
      93            0 :         let http_conn_pool = Arc::clone(&http_conn_pool);
      94            0 :         tokio::spawn(async move {
      95            0 :             http_conn_pool.gc_worker(StdRng::from_entropy()).await;
      96            0 :         });
      97            0 :     }
      98            0 : 
      99            0 :     // shutdown the connection pool
     100            0 :     tokio::spawn({
     101            0 :         let cancellation_token = cancellation_token.clone();
     102            0 :         let http_conn_pool = http_conn_pool.clone();
     103            0 :         async move {
     104            0 :             cancellation_token.cancelled().await;
     105            0 :             tokio::task::spawn_blocking(move || http_conn_pool.shutdown())
     106            0 :                 .await
     107            0 :                 .unwrap();
     108            0 :         }
     109            0 :     });
     110            0 : 
     111            0 :     let backend = Arc::new(PoolingBackend {
     112            0 :         http_conn_pool: Arc::clone(&http_conn_pool),
     113            0 :         local_pool,
     114            0 :         pool: Arc::clone(&conn_pool),
     115            0 :         config,
     116            0 :         auth_backend,
     117            0 :         endpoint_rate_limiter: Arc::clone(&endpoint_rate_limiter),
     118            0 :     });
     119            0 :     let tls_acceptor: Arc<dyn MaybeTlsAcceptor> = match config.tls_config.as_ref() {
     120            0 :         Some(config) => {
     121            0 :             let mut tls_server_config = rustls::ServerConfig::clone(&config.to_server_config());
     122            0 :             // prefer http2, but support http/1.1
     123            0 :             tls_server_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
     124            0 :             Arc::new(tls_server_config)
     125              :         }
     126              :         None => {
     127            0 :             warn!("TLS config is missing");
     128            0 :             Arc::new(NoTls)
     129              :         }
     130              :     };
     131              : 
     132            0 :     let connections = tokio_util::task::task_tracker::TaskTracker::new();
     133            0 :     connections.close(); // allows `connections.wait to complete`
     134              : 
     135            0 :     while let Some(res) = run_until_cancelled(ws_listener.accept(), &cancellation_token).await {
     136            0 :         let (conn, peer_addr) = res.context("could not accept TCP stream")?;
     137            0 :         if let Err(e) = conn.set_nodelay(true) {
     138            0 :             tracing::error!("could not set nodelay: {e}");
     139            0 :             continue;
     140            0 :         }
     141            0 :         let conn_id = uuid::Uuid::new_v4();
     142            0 :         let http_conn_span = tracing::info_span!("http_conn", ?conn_id);
     143              : 
     144            0 :         let n_connections = Metrics::get()
     145            0 :             .proxy
     146            0 :             .client_connections
     147            0 :             .sample(crate::metrics::Protocol::Http);
     148            0 :         tracing::trace!(?n_connections, threshold = ?config.http_config.client_conn_threshold, "check");
     149            0 :         if n_connections > config.http_config.client_conn_threshold {
     150            0 :             tracing::trace!("attempting to cancel a random connection");
     151            0 :             if let Some(token) = config.http_config.cancel_set.take() {
     152            0 :                 tracing::debug!("cancelling a random connection");
     153            0 :                 token.cancel();
     154            0 :             }
     155            0 :         }
     156              : 
     157            0 :         let conn_token = cancellation_token.child_token();
     158            0 :         let tls_acceptor = tls_acceptor.clone();
     159            0 :         let backend = backend.clone();
     160            0 :         let connections2 = connections.clone();
     161            0 :         let cancellation_handler = cancellation_handler.clone();
     162            0 :         let endpoint_rate_limiter = endpoint_rate_limiter.clone();
     163            0 :         connections.spawn(
     164            0 :             async move {
     165            0 :                 let conn_token2 = conn_token.clone();
     166            0 :                 let _cancel_guard = config.http_config.cancel_set.insert(conn_id, conn_token2);
     167            0 : 
     168            0 :                 let session_id = uuid::Uuid::new_v4();
     169            0 : 
     170            0 :                 let _gauge = Metrics::get()
     171            0 :                     .proxy
     172            0 :                     .client_connections
     173            0 :                     .guard(crate::metrics::Protocol::Http);
     174              : 
     175            0 :                 let startup_result = Box::pin(connection_startup(
     176            0 :                     config,
     177            0 :                     tls_acceptor,
     178            0 :                     session_id,
     179            0 :                     conn,
     180            0 :                     peer_addr,
     181            0 :                 ))
     182            0 :                 .await;
     183            0 :                 let Some((conn, conn_info)) = startup_result else {
     184            0 :                     return;
     185              :                 };
     186              : 
     187            0 :                 Box::pin(connection_handler(
     188            0 :                     config,
     189            0 :                     backend,
     190            0 :                     connections2,
     191            0 :                     cancellation_handler,
     192            0 :                     endpoint_rate_limiter,
     193            0 :                     conn_token,
     194            0 :                     conn,
     195            0 :                     conn_info,
     196            0 :                     session_id,
     197            0 :                 ))
     198            0 :                 .await;
     199            0 :             }
     200            0 :             .instrument(http_conn_span),
     201            0 :         );
     202              :     }
     203              : 
     204            0 :     connections.wait().await;
     205              : 
     206            0 :     Ok(())
     207            0 : }
     208              : 
     209              : pub(crate) trait AsyncReadWrite: AsyncRead + AsyncWrite + Send + 'static {}
     210              : impl<T: AsyncRead + AsyncWrite + Send + 'static> AsyncReadWrite for T {}
     211              : pub(crate) type AsyncRW = Pin<Box<dyn AsyncReadWrite>>;
     212              : 
     213              : #[async_trait]
     214              : trait MaybeTlsAcceptor: Send + Sync + 'static {
     215              :     async fn accept(self: Arc<Self>, conn: ChainRW<TcpStream>) -> std::io::Result<AsyncRW>;
     216              : }
     217              : 
     218              : #[async_trait]
     219              : impl MaybeTlsAcceptor for rustls::ServerConfig {
     220            0 :     async fn accept(self: Arc<Self>, conn: ChainRW<TcpStream>) -> std::io::Result<AsyncRW> {
     221            0 :         Ok(Box::pin(TlsAcceptor::from(self).accept(conn).await?))
     222            0 :     }
     223              : }
     224              : 
     225              : struct NoTls;
     226              : 
     227              : #[async_trait]
     228              : impl MaybeTlsAcceptor for NoTls {
     229            0 :     async fn accept(self: Arc<Self>, conn: ChainRW<TcpStream>) -> std::io::Result<AsyncRW> {
     230            0 :         Ok(Box::pin(conn))
     231            0 :     }
     232              : }
     233              : 
     234              : /// Handles the TCP startup lifecycle.
     235              : /// 1. Parses PROXY protocol V2
     236              : /// 2. Handles TLS handshake
     237            0 : async fn connection_startup(
     238            0 :     config: &ProxyConfig,
     239            0 :     tls_acceptor: Arc<dyn MaybeTlsAcceptor>,
     240            0 :     session_id: uuid::Uuid,
     241            0 :     conn: TcpStream,
     242            0 :     peer_addr: SocketAddr,
     243            0 : ) -> Option<(AsyncRW, ConnectionInfo)> {
     244              :     // handle PROXY protocol
     245            0 :     let (conn, peer) = match read_proxy_protocol(conn).await {
     246            0 :         Ok(c) => c,
     247            0 :         Err(e) => {
     248            0 :             tracing::warn!(?session_id, %peer_addr, "failed to accept TCP connection: invalid PROXY protocol V2 header: {e:#}");
     249            0 :             return None;
     250              :         }
     251              :     };
     252              : 
     253            0 :     let conn_info = match peer {
     254              :         // our load balancers will not send any more data. let's just exit immediately
     255              :         ConnectHeader::Local => {
     256            0 :             tracing::debug!("healthcheck received");
     257            0 :             return None;
     258              :         }
     259            0 :         ConnectHeader::Missing if config.proxy_protocol_v2 == ProxyProtocolV2::Required => {
     260            0 :             tracing::warn!("missing required proxy protocol header");
     261            0 :             return None;
     262              :         }
     263            0 :         ConnectHeader::Proxy(_) if config.proxy_protocol_v2 == ProxyProtocolV2::Rejected => {
     264            0 :             tracing::warn!("proxy protocol header not supported");
     265            0 :             return None;
     266              :         }
     267            0 :         ConnectHeader::Proxy(info) => info,
     268            0 :         ConnectHeader::Missing => ConnectionInfo {
     269            0 :             addr: peer_addr,
     270            0 :             extra: None,
     271            0 :         },
     272              :     };
     273              : 
     274            0 :     let has_private_peer_addr = match conn_info.addr.ip() {
     275            0 :         IpAddr::V4(ip) => ip.is_private(),
     276            0 :         IpAddr::V6(_) => false,
     277              :     };
     278            0 :     info!(?session_id, %conn_info, "accepted new TCP connection");
     279              : 
     280              :     // try upgrade to TLS, but with a timeout.
     281            0 :     let conn = match timeout(config.handshake_timeout, tls_acceptor.accept(conn)).await {
     282            0 :         Ok(Ok(conn)) => {
     283            0 :             info!(?session_id, %conn_info, "accepted new TLS connection");
     284            0 :             conn
     285              :         }
     286              :         // The handshake failed
     287            0 :         Ok(Err(e)) => {
     288            0 :             if !has_private_peer_addr {
     289            0 :                 Metrics::get().proxy.tls_handshake_failures.inc();
     290            0 :             }
     291            0 :             warn!(?session_id, %conn_info, "failed to accept TLS connection: {e:?}");
     292            0 :             return None;
     293              :         }
     294              :         // The handshake timed out
     295            0 :         Err(e) => {
     296            0 :             if !has_private_peer_addr {
     297            0 :                 Metrics::get().proxy.tls_handshake_failures.inc();
     298            0 :             }
     299            0 :             warn!(?session_id, %conn_info, "failed to accept TLS connection: {e:?}");
     300            0 :             return None;
     301              :         }
     302              :     };
     303              : 
     304            0 :     Some((conn, conn_info))
     305            0 : }
     306              : 
     307              : /// Handles HTTP connection
     308              : /// 1. With graceful shutdowns
     309              : /// 2. With graceful request cancellation with connection failure
     310              : /// 3. With websocket upgrade support.
     311              : #[allow(clippy::too_many_arguments)]
     312            0 : async fn connection_handler(
     313            0 :     config: &'static ProxyConfig,
     314            0 :     backend: Arc<PoolingBackend>,
     315            0 :     connections: TaskTracker,
     316            0 :     cancellation_handler: Arc<CancellationHandlerMain>,
     317            0 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
     318            0 :     cancellation_token: CancellationToken,
     319            0 :     conn: AsyncRW,
     320            0 :     conn_info: ConnectionInfo,
     321            0 :     session_id: uuid::Uuid,
     322            0 : ) {
     323            0 :     let session_id = AtomicTake::new(session_id);
     324            0 : 
     325            0 :     // Cancel all current inflight HTTP requests if the HTTP connection is closed.
     326            0 :     let http_cancellation_token = CancellationToken::new();
     327            0 :     let _cancel_connection = http_cancellation_token.clone().drop_guard();
     328            0 : 
     329            0 :     let conn_info2 = conn_info.clone();
     330            0 :     let server = Builder::new(TokioExecutor::new());
     331            0 :     let conn = server.serve_connection_with_upgrades(
     332            0 :         hyper_util::rt::TokioIo::new(conn),
     333            0 :         hyper::service::service_fn(move |req: hyper::Request<Incoming>| {
     334            0 :             // First HTTP request shares the same session ID
     335            0 :             let mut session_id = session_id.take().unwrap_or_else(uuid::Uuid::new_v4);
     336              : 
     337            0 :             if matches!(backend.auth_backend, crate::auth::Backend::Local(_)) {
     338              :                 // take session_id from request, if given.
     339            0 :                 if let Some(id) = req
     340            0 :                     .headers()
     341            0 :                     .get(&NEON_REQUEST_ID)
     342            0 :                     .and_then(|id| uuid::Uuid::try_parse_ascii(id.as_bytes()).ok())
     343            0 :                 {
     344            0 :                     session_id = id;
     345            0 :                 }
     346            0 :             }
     347              : 
     348              :             // Cancel the current inflight HTTP request if the requets stream is closed.
     349              :             // This is slightly different to `_cancel_connection` in that
     350              :             // h2 can cancel individual requests with a `RST_STREAM`.
     351            0 :             let http_request_token = http_cancellation_token.child_token();
     352            0 :             let cancel_request = http_request_token.clone().drop_guard();
     353            0 : 
     354            0 :             // `request_handler` is not cancel safe. It expects to be cancelled only at specific times.
     355            0 :             // By spawning the future, we ensure it never gets cancelled until it decides to.
     356            0 :             let handler = connections.spawn(
     357            0 :                 request_handler(
     358            0 :                     req,
     359            0 :                     config,
     360            0 :                     backend.clone(),
     361            0 :                     connections.clone(),
     362            0 :                     cancellation_handler.clone(),
     363            0 :                     session_id,
     364            0 :                     conn_info2.clone(),
     365            0 :                     http_request_token,
     366            0 :                     endpoint_rate_limiter.clone(),
     367            0 :                 )
     368            0 :                 .in_current_span()
     369            0 :                 .map_ok_or_else(api_error_into_response, |r| r),
     370            0 :             );
     371            0 :             async move {
     372            0 :                 let mut res = handler.await;
     373            0 :                 cancel_request.disarm();
     374              : 
     375              :                 // add the session ID to the response
     376            0 :                 if let Ok(resp) = &mut res {
     377            0 :                     resp.headers_mut()
     378            0 :                         .append(&NEON_REQUEST_ID, uuid_to_header_value(session_id));
     379            0 :                 }
     380              : 
     381            0 :                 res
     382            0 :             }
     383            0 :         }),
     384            0 :     );
     385              : 
     386              :     // On cancellation, trigger the HTTP connection handler to shut down.
     387            0 :     let res = match select(pin!(cancellation_token.cancelled()), pin!(conn)).await {
     388            0 :         Either::Left((_cancelled, mut conn)) => {
     389            0 :             tracing::debug!(%conn_info, "cancelling connection");
     390            0 :             conn.as_mut().graceful_shutdown();
     391            0 :             conn.await
     392              :         }
     393            0 :         Either::Right((res, _)) => res,
     394              :     };
     395              : 
     396            0 :     match res {
     397            0 :         Ok(()) => tracing::info!(%conn_info, "HTTP connection closed"),
     398            0 :         Err(e) => tracing::warn!(%conn_info, "HTTP connection error {e}"),
     399              :     }
     400            0 : }
     401              : 
     402              : #[allow(clippy::too_many_arguments)]
     403            0 : async fn request_handler(
     404            0 :     mut request: hyper::Request<Incoming>,
     405            0 :     config: &'static ProxyConfig,
     406            0 :     backend: Arc<PoolingBackend>,
     407            0 :     ws_connections: TaskTracker,
     408            0 :     cancellation_handler: Arc<CancellationHandlerMain>,
     409            0 :     session_id: uuid::Uuid,
     410            0 :     conn_info: ConnectionInfo,
     411            0 :     // used to cancel in-flight HTTP requests. not used to cancel websockets
     412            0 :     http_cancellation_token: CancellationToken,
     413            0 :     endpoint_rate_limiter: Arc<EndpointRateLimiter>,
     414            0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, ApiError> {
     415            0 :     let host = request
     416            0 :         .headers()
     417            0 :         .get("host")
     418            0 :         .and_then(|h| h.to_str().ok())
     419            0 :         .and_then(|h| h.split(':').next())
     420            0 :         .map(|s| s.to_string());
     421            0 : 
     422            0 :     // Check if the request is a websocket upgrade request.
     423            0 :     if config.http_config.accept_websockets
     424            0 :         && framed_websockets::upgrade::is_upgrade_request(&request)
     425              :     {
     426            0 :         let ctx = RequestContext::new(
     427            0 :             session_id,
     428            0 :             conn_info,
     429            0 :             crate::metrics::Protocol::Ws,
     430            0 :             &config.region,
     431            0 :         );
     432            0 : 
     433            0 :         let span = ctx.span();
     434            0 :         info!(parent: &span, "performing websocket upgrade");
     435              : 
     436            0 :         let (response, websocket) = framed_websockets::upgrade::upgrade(&mut request)
     437            0 :             .map_err(|e| ApiError::BadRequest(e.into()))?;
     438              : 
     439            0 :         ws_connections.spawn(
     440            0 :             async move {
     441            0 :                 if let Err(e) = websocket::serve_websocket(
     442            0 :                     config,
     443            0 :                     backend.auth_backend,
     444            0 :                     ctx,
     445            0 :                     websocket,
     446            0 :                     cancellation_handler,
     447            0 :                     endpoint_rate_limiter,
     448            0 :                     host,
     449            0 :                 )
     450            0 :                 .await
     451              :                 {
     452            0 :                     warn!("error in websocket connection: {e:#}");
     453            0 :                 }
     454            0 :             }
     455            0 :             .instrument(span),
     456            0 :         );
     457            0 : 
     458            0 :         // Return the response so the spawned future can continue.
     459            0 :         Ok(response.map(|b| b.map_err(|x| match x {}).boxed()))
     460            0 :     } else if request.uri().path() == "/sql" && *request.method() == Method::POST {
     461            0 :         let ctx = RequestContext::new(
     462            0 :             session_id,
     463            0 :             conn_info,
     464            0 :             crate::metrics::Protocol::Http,
     465            0 :             &config.region,
     466            0 :         );
     467            0 :         let span = ctx.span();
     468            0 : 
     469            0 :         sql_over_http::handle(config, ctx, request, backend, http_cancellation_token)
     470            0 :             .instrument(span)
     471            0 :             .await
     472            0 :     } else if request.uri().path() == "/sql" && *request.method() == Method::OPTIONS {
     473            0 :         Response::builder()
     474            0 :             .header("Allow", "OPTIONS, POST")
     475            0 :             .header("Access-Control-Allow-Origin", "*")
     476            0 :             .header(
     477            0 :                 "Access-Control-Allow-Headers",
     478            0 :                 "Authorization, Neon-Connection-String, Neon-Raw-Text-Output, Neon-Array-Mode, Neon-Pool-Opt-In, Neon-Batch-Read-Only, Neon-Batch-Isolation-Level",
     479            0 :             )
     480            0 :             .header("Access-Control-Max-Age", "86400" /* 24 hours */)
     481            0 :             .status(StatusCode::OK) // 204 is also valid, but see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#status_code
     482            0 :             .body(Empty::new().map_err(|x| match x {}).boxed())
     483            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))
     484              :     } else {
     485            0 :         json_response(StatusCode::BAD_REQUEST, "query is not supported")
     486              :     }
     487            0 : }
        

Generated by: LCOV version 2.1-beta