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