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