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