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