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 0 :
135 0 : let cancellations = tokio_util::task::task_tracker::TaskTracker::new();
136 0 : while let Some(res) = run_until_cancelled(ws_listener.accept(), &cancellation_token).await {
137 0 : let (conn, peer_addr) = res.context("could not accept TCP stream")?;
138 0 : if let Err(e) = conn.set_nodelay(true) {
139 0 : tracing::error!("could not set nodelay: {e}");
140 0 : continue;
141 0 : }
142 0 : let conn_id = uuid::Uuid::new_v4();
143 0 : let http_conn_span = tracing::info_span!("http_conn", ?conn_id);
144 :
145 0 : let n_connections = Metrics::get()
146 0 : .proxy
147 0 : .client_connections
148 0 : .sample(crate::metrics::Protocol::Http);
149 0 : tracing::trace!(?n_connections, threshold = ?config.http_config.client_conn_threshold, "check");
150 0 : if n_connections > config.http_config.client_conn_threshold {
151 0 : tracing::trace!("attempting to cancel a random connection");
152 0 : if let Some(token) = config.http_config.cancel_set.take() {
153 0 : tracing::debug!("cancelling a random connection");
154 0 : token.cancel();
155 0 : }
156 0 : }
157 :
158 0 : let conn_token = cancellation_token.child_token();
159 0 : let tls_acceptor = tls_acceptor.clone();
160 0 : let backend = backend.clone();
161 0 : let connections2 = connections.clone();
162 0 : let cancellation_handler = cancellation_handler.clone();
163 0 : let endpoint_rate_limiter = endpoint_rate_limiter.clone();
164 0 : let cancellations = cancellations.clone();
165 0 : connections.spawn(
166 0 : async move {
167 0 : let conn_token2 = conn_token.clone();
168 0 : let _cancel_guard = config.http_config.cancel_set.insert(conn_id, conn_token2);
169 0 :
170 0 : let session_id = uuid::Uuid::new_v4();
171 0 :
172 0 : let _gauge = Metrics::get()
173 0 : .proxy
174 0 : .client_connections
175 0 : .guard(crate::metrics::Protocol::Http);
176 :
177 0 : let startup_result = Box::pin(connection_startup(
178 0 : config,
179 0 : tls_acceptor,
180 0 : session_id,
181 0 : conn,
182 0 : peer_addr,
183 0 : ))
184 0 : .await;
185 0 : let Some((conn, conn_info)) = startup_result else {
186 0 : return;
187 : };
188 :
189 0 : Box::pin(connection_handler(
190 0 : config,
191 0 : backend,
192 0 : connections2,
193 0 : cancellations,
194 0 : cancellation_handler,
195 0 : endpoint_rate_limiter,
196 0 : conn_token,
197 0 : conn,
198 0 : conn_info,
199 0 : session_id,
200 0 : ))
201 0 : .await;
202 0 : }
203 0 : .instrument(http_conn_span),
204 0 : );
205 : }
206 :
207 0 : connections.wait().await;
208 :
209 0 : Ok(())
210 0 : }
211 :
212 : pub(crate) trait AsyncReadWrite: AsyncRead + AsyncWrite + Send + 'static {}
213 : impl<T: AsyncRead + AsyncWrite + Send + 'static> AsyncReadWrite for T {}
214 : pub(crate) type AsyncRW = Pin<Box<dyn AsyncReadWrite>>;
215 :
216 : #[async_trait]
217 : trait MaybeTlsAcceptor: Send + Sync + 'static {
218 : async fn accept(self: Arc<Self>, conn: ChainRW<TcpStream>) -> std::io::Result<AsyncRW>;
219 : }
220 :
221 : #[async_trait]
222 : impl MaybeTlsAcceptor for rustls::ServerConfig {
223 0 : async fn accept(self: Arc<Self>, conn: ChainRW<TcpStream>) -> std::io::Result<AsyncRW> {
224 0 : Ok(Box::pin(TlsAcceptor::from(self).accept(conn).await?))
225 0 : }
226 : }
227 :
228 : struct NoTls;
229 :
230 : #[async_trait]
231 : impl MaybeTlsAcceptor for NoTls {
232 0 : async fn accept(self: Arc<Self>, conn: ChainRW<TcpStream>) -> std::io::Result<AsyncRW> {
233 0 : Ok(Box::pin(conn))
234 0 : }
235 : }
236 :
237 : /// Handles the TCP startup lifecycle.
238 : /// 1. Parses PROXY protocol V2
239 : /// 2. Handles TLS handshake
240 0 : async fn connection_startup(
241 0 : config: &ProxyConfig,
242 0 : tls_acceptor: Arc<dyn MaybeTlsAcceptor>,
243 0 : session_id: uuid::Uuid,
244 0 : conn: TcpStream,
245 0 : peer_addr: SocketAddr,
246 0 : ) -> Option<(AsyncRW, ConnectionInfo)> {
247 : // handle PROXY protocol
248 0 : let (conn, peer) = match read_proxy_protocol(conn).await {
249 0 : Ok(c) => c,
250 0 : Err(e) => {
251 0 : tracing::warn!(?session_id, %peer_addr, "failed to accept TCP connection: invalid PROXY protocol V2 header: {e:#}");
252 0 : return None;
253 : }
254 : };
255 :
256 0 : let conn_info = match peer {
257 : // our load balancers will not send any more data. let's just exit immediately
258 : ConnectHeader::Local => {
259 0 : tracing::debug!("healthcheck received");
260 0 : return None;
261 : }
262 0 : ConnectHeader::Missing if config.proxy_protocol_v2 == ProxyProtocolV2::Required => {
263 0 : tracing::warn!("missing required proxy protocol header");
264 0 : return None;
265 : }
266 0 : ConnectHeader::Proxy(_) if config.proxy_protocol_v2 == ProxyProtocolV2::Rejected => {
267 0 : tracing::warn!("proxy protocol header not supported");
268 0 : return None;
269 : }
270 0 : ConnectHeader::Proxy(info) => info,
271 0 : ConnectHeader::Missing => ConnectionInfo {
272 0 : addr: peer_addr,
273 0 : extra: None,
274 0 : },
275 : };
276 :
277 0 : let has_private_peer_addr = match conn_info.addr.ip() {
278 0 : IpAddr::V4(ip) => ip.is_private(),
279 0 : IpAddr::V6(_) => false,
280 : };
281 0 : info!(?session_id, %conn_info, "accepted new TCP connection");
282 :
283 : // try upgrade to TLS, but with a timeout.
284 0 : let conn = match timeout(config.handshake_timeout, tls_acceptor.accept(conn)).await {
285 0 : Ok(Ok(conn)) => {
286 0 : info!(?session_id, %conn_info, "accepted new TLS connection");
287 0 : conn
288 : }
289 : // The handshake failed
290 0 : Ok(Err(e)) => {
291 0 : if !has_private_peer_addr {
292 0 : Metrics::get().proxy.tls_handshake_failures.inc();
293 0 : }
294 0 : warn!(?session_id, %conn_info, "failed to accept TLS connection: {e:?}");
295 0 : return None;
296 : }
297 : // The handshake timed out
298 0 : Err(e) => {
299 0 : if !has_private_peer_addr {
300 0 : Metrics::get().proxy.tls_handshake_failures.inc();
301 0 : }
302 0 : warn!(?session_id, %conn_info, "failed to accept TLS connection: {e:?}");
303 0 : return None;
304 : }
305 : };
306 :
307 0 : Some((conn, conn_info))
308 0 : }
309 :
310 : /// Handles HTTP connection
311 : /// 1. With graceful shutdowns
312 : /// 2. With graceful request cancellation with connection failure
313 : /// 3. With websocket upgrade support.
314 : #[allow(clippy::too_many_arguments)]
315 0 : async fn connection_handler(
316 0 : config: &'static ProxyConfig,
317 0 : backend: Arc<PoolingBackend>,
318 0 : connections: TaskTracker,
319 0 : cancellations: TaskTracker,
320 0 : cancellation_handler: Arc<CancellationHandlerMain>,
321 0 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
322 0 : cancellation_token: CancellationToken,
323 0 : conn: AsyncRW,
324 0 : conn_info: ConnectionInfo,
325 0 : session_id: uuid::Uuid,
326 0 : ) {
327 0 : let session_id = AtomicTake::new(session_id);
328 0 :
329 0 : // Cancel all current inflight HTTP requests if the HTTP connection is closed.
330 0 : let http_cancellation_token = CancellationToken::new();
331 0 : let _cancel_connection = http_cancellation_token.clone().drop_guard();
332 0 :
333 0 : let conn_info2 = conn_info.clone();
334 0 : let server = Builder::new(TokioExecutor::new());
335 0 : let conn = server.serve_connection_with_upgrades(
336 0 : hyper_util::rt::TokioIo::new(conn),
337 0 : hyper::service::service_fn(move |req: hyper::Request<Incoming>| {
338 0 : // First HTTP request shares the same session ID
339 0 : let mut session_id = session_id.take().unwrap_or_else(uuid::Uuid::new_v4);
340 :
341 0 : if matches!(backend.auth_backend, crate::auth::Backend::Local(_)) {
342 : // take session_id from request, if given.
343 0 : if let Some(id) = req
344 0 : .headers()
345 0 : .get(&NEON_REQUEST_ID)
346 0 : .and_then(|id| uuid::Uuid::try_parse_ascii(id.as_bytes()).ok())
347 0 : {
348 0 : session_id = id;
349 0 : }
350 0 : }
351 :
352 : // Cancel the current inflight HTTP request if the requets stream is closed.
353 : // This is slightly different to `_cancel_connection` in that
354 : // h2 can cancel individual requests with a `RST_STREAM`.
355 0 : let http_request_token = http_cancellation_token.child_token();
356 0 : let cancel_request = http_request_token.clone().drop_guard();
357 0 :
358 0 : // `request_handler` is not cancel safe. It expects to be cancelled only at specific times.
359 0 : // By spawning the future, we ensure it never gets cancelled until it decides to.
360 0 : let cancellations = cancellations.clone();
361 0 : let handler = connections.spawn(
362 0 : request_handler(
363 0 : req,
364 0 : config,
365 0 : backend.clone(),
366 0 : connections.clone(),
367 0 : cancellation_handler.clone(),
368 0 : session_id,
369 0 : conn_info2.clone(),
370 0 : http_request_token,
371 0 : endpoint_rate_limiter.clone(),
372 0 : cancellations,
373 0 : )
374 0 : .in_current_span()
375 0 : .map_ok_or_else(api_error_into_response, |r| r),
376 0 : );
377 0 : async move {
378 0 : let mut res = handler.await;
379 0 : cancel_request.disarm();
380 :
381 : // add the session ID to the response
382 0 : if let Ok(resp) = &mut res {
383 0 : resp.headers_mut()
384 0 : .append(&NEON_REQUEST_ID, uuid_to_header_value(session_id));
385 0 : }
386 :
387 0 : res
388 0 : }
389 0 : }),
390 0 : );
391 :
392 : // On cancellation, trigger the HTTP connection handler to shut down.
393 0 : let res = match select(pin!(cancellation_token.cancelled()), pin!(conn)).await {
394 0 : Either::Left((_cancelled, mut conn)) => {
395 0 : tracing::debug!(%conn_info, "cancelling connection");
396 0 : conn.as_mut().graceful_shutdown();
397 0 : conn.await
398 : }
399 0 : Either::Right((res, _)) => res,
400 : };
401 :
402 0 : match res {
403 0 : Ok(()) => tracing::info!(%conn_info, "HTTP connection closed"),
404 0 : Err(e) => tracing::warn!(%conn_info, "HTTP connection error {e}"),
405 : }
406 0 : }
407 :
408 : #[allow(clippy::too_many_arguments)]
409 0 : async fn request_handler(
410 0 : mut request: hyper::Request<Incoming>,
411 0 : config: &'static ProxyConfig,
412 0 : backend: Arc<PoolingBackend>,
413 0 : ws_connections: TaskTracker,
414 0 : cancellation_handler: Arc<CancellationHandlerMain>,
415 0 : session_id: uuid::Uuid,
416 0 : conn_info: ConnectionInfo,
417 0 : // used to cancel in-flight HTTP requests. not used to cancel websockets
418 0 : http_cancellation_token: CancellationToken,
419 0 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
420 0 : cancellations: TaskTracker,
421 0 : ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, ApiError> {
422 0 : let host = request
423 0 : .headers()
424 0 : .get("host")
425 0 : .and_then(|h| h.to_str().ok())
426 0 : .and_then(|h| h.split(':').next())
427 0 : .map(|s| s.to_string());
428 0 :
429 0 : // Check if the request is a websocket upgrade request.
430 0 : if config.http_config.accept_websockets
431 0 : && framed_websockets::upgrade::is_upgrade_request(&request)
432 : {
433 0 : let ctx = RequestContext::new(
434 0 : session_id,
435 0 : conn_info,
436 0 : crate::metrics::Protocol::Ws,
437 0 : &config.region,
438 0 : );
439 0 :
440 0 : let span = ctx.span();
441 0 : info!(parent: &span, "performing websocket upgrade");
442 :
443 0 : let (response, websocket) = framed_websockets::upgrade::upgrade(&mut request)
444 0 : .map_err(|e| ApiError::BadRequest(e.into()))?;
445 :
446 0 : let cancellations = cancellations.clone();
447 0 : ws_connections.spawn(
448 0 : async move {
449 0 : if let Err(e) = websocket::serve_websocket(
450 0 : config,
451 0 : backend.auth_backend,
452 0 : ctx,
453 0 : websocket,
454 0 : cancellation_handler,
455 0 : endpoint_rate_limiter,
456 0 : host,
457 0 : cancellations,
458 0 : )
459 0 : .await
460 : {
461 0 : warn!("error in websocket connection: {e:#}");
462 0 : }
463 0 : }
464 0 : .instrument(span),
465 0 : );
466 0 :
467 0 : // Return the response so the spawned future can continue.
468 0 : Ok(response.map(|b| b.map_err(|x| match x {}).boxed()))
469 0 : } else if request.uri().path() == "/sql" && *request.method() == Method::POST {
470 0 : let ctx = RequestContext::new(
471 0 : session_id,
472 0 : conn_info,
473 0 : crate::metrics::Protocol::Http,
474 0 : &config.region,
475 0 : );
476 0 : let span = ctx.span();
477 0 :
478 0 : sql_over_http::handle(config, ctx, request, backend, http_cancellation_token)
479 0 : .instrument(span)
480 0 : .await
481 0 : } else if request.uri().path() == "/sql" && *request.method() == Method::OPTIONS {
482 0 : Response::builder()
483 0 : .header("Allow", "OPTIONS, POST")
484 0 : .header("Access-Control-Allow-Origin", "*")
485 0 : .header(
486 0 : "Access-Control-Allow-Headers",
487 0 : "Authorization, Neon-Connection-String, Neon-Raw-Text-Output, Neon-Array-Mode, Neon-Pool-Opt-In, Neon-Batch-Read-Only, Neon-Batch-Isolation-Level",
488 0 : )
489 0 : .header("Access-Control-Max-Age", "86400" /* 24 hours */)
490 0 : .status(StatusCode::OK) // 204 is also valid, but see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#status_code
491 0 : .body(Empty::new().map_err(|x| match x {}).boxed())
492 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
493 : } else {
494 0 : json_response(StatusCode::BAD_REQUEST, "query is not supported")
495 : }
496 0 : }
|