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 atomic_take::AtomicTake;
14 : use bytes::Bytes;
15 : pub use conn_pool::GlobalConnPoolOptions;
16 :
17 : use anyhow::Context;
18 : use futures::future::{select, Either};
19 : use futures::TryFutureExt;
20 : use http::{Method, Response, StatusCode};
21 : use http_body_util::Full;
22 : use hyper1::body::Incoming;
23 : use hyper_util::rt::TokioExecutor;
24 : use hyper_util::server::conn::auto::Builder;
25 : use rand::rngs::StdRng;
26 : use rand::SeedableRng;
27 : pub use reqwest_middleware::{ClientWithMiddleware, Error};
28 : pub use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
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;
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;
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 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 : scopeguard::defer! {
61 : info!("websocket server has shut down");
62 : }
63 :
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 :
90 0 : let tls_config = match config.tls_config.as_ref() {
91 0 : Some(config) => config,
92 : None => {
93 0 : warn!("TLS config is missing, WebSocket Secure server will not be started");
94 0 : return Ok(());
95 : }
96 : };
97 0 : let mut tls_server_config = rustls::ServerConfig::clone(&tls_config.to_server_config());
98 0 : // prefer http2, but support http/1.1
99 0 : tls_server_config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
100 0 : let tls_acceptor: tokio_rustls::TlsAcceptor = Arc::new(tls_server_config).into();
101 0 :
102 0 : let connections = tokio_util::task::task_tracker::TaskTracker::new();
103 0 : connections.close(); // allows `connections.wait to complete`
104 0 :
105 0 : let server = Builder::new(hyper_util::rt::TokioExecutor::new());
106 :
107 0 : while let Some(res) = run_until_cancelled(ws_listener.accept(), &cancellation_token).await {
108 0 : let (conn, peer_addr) = res.context("could not accept TCP stream")?;
109 0 : if let Err(e) = conn.set_nodelay(true) {
110 0 : tracing::error!("could not set nodelay: {e}");
111 0 : continue;
112 0 : }
113 0 : let conn_id = uuid::Uuid::new_v4();
114 0 : let http_conn_span = tracing::info_span!("http_conn", ?conn_id);
115 :
116 0 : let n_connections = Metrics::get()
117 0 : .proxy
118 0 : .client_connections
119 0 : .sample(crate::metrics::Protocol::Http);
120 0 : tracing::trace!(?n_connections, threshold = ?config.http_config.client_conn_threshold, "check");
121 0 : if n_connections > config.http_config.client_conn_threshold {
122 0 : tracing::trace!("attempting to cancel a random connection");
123 0 : if let Some(token) = config.http_config.cancel_set.take() {
124 0 : tracing::debug!("cancelling a random connection");
125 0 : token.cancel()
126 0 : }
127 0 : }
128 :
129 0 : let conn_token = cancellation_token.child_token();
130 0 : let conn = connection_handler(
131 0 : config,
132 0 : backend.clone(),
133 0 : connections.clone(),
134 0 : cancellation_handler.clone(),
135 0 : endpoint_rate_limiter.clone(),
136 0 : conn_token.clone(),
137 0 : server.clone(),
138 0 : tls_acceptor.clone(),
139 0 : conn,
140 0 : peer_addr,
141 0 : )
142 0 : .instrument(http_conn_span);
143 0 :
144 0 : connections.spawn(async move {
145 0 : let _cancel_guard = config.http_config.cancel_set.insert(conn_id, conn_token);
146 0 : conn.await
147 0 : });
148 : }
149 :
150 0 : connections.wait().await;
151 :
152 0 : Ok(())
153 0 : }
154 :
155 : /// Handles the TCP lifecycle.
156 : ///
157 : /// 1. Parses PROXY protocol V2
158 : /// 2. Handles TLS handshake
159 : /// 3. Handles HTTP connection
160 : /// 1. With graceful shutdowns
161 : /// 2. With graceful request cancellation with connection failure
162 : /// 3. With websocket upgrade support.
163 : #[allow(clippy::too_many_arguments)]
164 0 : async fn connection_handler(
165 0 : config: &'static ProxyConfig,
166 0 : backend: Arc<PoolingBackend>,
167 0 : connections: TaskTracker,
168 0 : cancellation_handler: Arc<CancellationHandlerMain>,
169 0 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
170 0 : cancellation_token: CancellationToken,
171 0 : server: Builder<TokioExecutor>,
172 0 : tls_acceptor: TlsAcceptor,
173 0 : conn: TcpStream,
174 0 : peer_addr: SocketAddr,
175 0 : ) {
176 0 : let session_id = uuid::Uuid::new_v4();
177 0 :
178 0 : let _gauge = Metrics::get()
179 0 : .proxy
180 0 : .client_connections
181 0 : .guard(crate::metrics::Protocol::Http);
182 :
183 : // handle PROXY protocol
184 0 : let (conn, peer) = match read_proxy_protocol(conn).await {
185 0 : Ok(c) => c,
186 0 : Err(e) => {
187 0 : tracing::error!(?session_id, %peer_addr, "failed to accept TCP connection: invalid PROXY protocol V2 header: {e:#}");
188 0 : return;
189 : }
190 : };
191 :
192 0 : let peer_addr = peer.unwrap_or(peer_addr).ip();
193 0 : let has_private_peer_addr = match peer_addr {
194 0 : IpAddr::V4(ip) => ip.is_private(),
195 0 : _ => false,
196 : };
197 0 : info!(?session_id, %peer_addr, "accepted new TCP connection");
198 :
199 : // try upgrade to TLS, but with a timeout.
200 0 : let conn = match timeout(config.handshake_timeout, tls_acceptor.accept(conn)).await {
201 0 : Ok(Ok(conn)) => {
202 0 : info!(?session_id, %peer_addr, "accepted new TLS connection");
203 0 : conn
204 : }
205 : // The handshake failed
206 0 : Ok(Err(e)) => {
207 0 : if !has_private_peer_addr {
208 0 : Metrics::get().proxy.tls_handshake_failures.inc();
209 0 : }
210 0 : warn!(?session_id, %peer_addr, "failed to accept TLS connection: {e:?}");
211 0 : return;
212 : }
213 : // The handshake timed out
214 0 : Err(e) => {
215 0 : if !has_private_peer_addr {
216 0 : Metrics::get().proxy.tls_handshake_failures.inc();
217 0 : }
218 0 : warn!(?session_id, %peer_addr, "failed to accept TLS connection: {e:?}");
219 0 : return;
220 : }
221 : };
222 :
223 0 : let session_id = AtomicTake::new(session_id);
224 0 :
225 0 : // Cancel all current inflight HTTP requests if the HTTP connection is closed.
226 0 : let http_cancellation_token = CancellationToken::new();
227 0 : let _cancel_connection = http_cancellation_token.clone().drop_guard();
228 0 :
229 0 : let conn = server.serve_connection_with_upgrades(
230 0 : hyper_util::rt::TokioIo::new(conn),
231 0 : hyper1::service::service_fn(move |req: hyper1::Request<Incoming>| {
232 0 : // First HTTP request shares the same session ID
233 0 : let session_id = session_id.take().unwrap_or_else(uuid::Uuid::new_v4);
234 0 :
235 0 : // Cancel the current inflight HTTP request if the requets stream is closed.
236 0 : // This is slightly different to `_cancel_connection` in that
237 0 : // h2 can cancel individual requests with a `RST_STREAM`.
238 0 : let http_request_token = http_cancellation_token.child_token();
239 0 : let cancel_request = http_request_token.clone().drop_guard();
240 0 :
241 0 : // `request_handler` is not cancel safe. It expects to be cancelled only at specific times.
242 0 : // By spawning the future, we ensure it never gets cancelled until it decides to.
243 0 : let handler = connections.spawn(
244 0 : request_handler(
245 0 : req,
246 0 : config,
247 0 : backend.clone(),
248 0 : connections.clone(),
249 0 : cancellation_handler.clone(),
250 0 : session_id,
251 0 : peer_addr,
252 0 : http_request_token,
253 0 : endpoint_rate_limiter.clone(),
254 0 : )
255 0 : .in_current_span()
256 0 : .map_ok_or_else(api_error_into_response, |r| r),
257 0 : );
258 :
259 0 : async move {
260 0 : let res = handler.await;
261 0 : cancel_request.disarm();
262 0 : res
263 0 : }
264 0 : }),
265 0 : );
266 :
267 : // On cancellation, trigger the HTTP connection handler to shut down.
268 0 : let res = match select(pin!(cancellation_token.cancelled()), pin!(conn)).await {
269 0 : Either::Left((_cancelled, mut conn)) => {
270 0 : tracing::debug!(%peer_addr, "cancelling connection");
271 0 : conn.as_mut().graceful_shutdown();
272 0 : conn.await
273 : }
274 0 : Either::Right((res, _)) => res,
275 : };
276 :
277 0 : match res {
278 0 : Ok(()) => tracing::info!(%peer_addr, "HTTP connection closed"),
279 0 : Err(e) => tracing::warn!(%peer_addr, "HTTP connection error {e}"),
280 : }
281 0 : }
282 :
283 : #[allow(clippy::too_many_arguments)]
284 0 : async fn request_handler(
285 0 : mut request: hyper1::Request<Incoming>,
286 0 : config: &'static ProxyConfig,
287 0 : backend: Arc<PoolingBackend>,
288 0 : ws_connections: TaskTracker,
289 0 : cancellation_handler: Arc<CancellationHandlerMain>,
290 0 : session_id: uuid::Uuid,
291 0 : peer_addr: IpAddr,
292 0 : // used to cancel in-flight HTTP requests. not used to cancel websockets
293 0 : http_cancellation_token: CancellationToken,
294 0 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
295 0 : ) -> Result<Response<Full<Bytes>>, ApiError> {
296 0 : let host = request
297 0 : .headers()
298 0 : .get("host")
299 0 : .and_then(|h| h.to_str().ok())
300 0 : .and_then(|h| h.split(':').next())
301 0 : .map(|s| s.to_string());
302 0 :
303 0 : // Check if the request is a websocket upgrade request.
304 0 : if hyper_tungstenite::is_upgrade_request(&request) {
305 0 : let ctx = RequestMonitoring::new(
306 0 : session_id,
307 0 : peer_addr,
308 0 : crate::metrics::Protocol::Ws,
309 0 : &config.region,
310 0 : );
311 0 :
312 0 : let span = ctx.span.clone();
313 : info!(parent: &span, "performing websocket upgrade");
314 :
315 0 : let (response, websocket) = hyper_tungstenite::upgrade(&mut request, None)
316 0 : .map_err(|e| ApiError::BadRequest(e.into()))?;
317 :
318 0 : ws_connections.spawn(
319 0 : async move {
320 0 : if let Err(e) = websocket::serve_websocket(
321 0 : config,
322 0 : ctx,
323 0 : websocket,
324 0 : cancellation_handler,
325 0 : endpoint_rate_limiter,
326 0 : host,
327 0 : )
328 0 : .await
329 : {
330 0 : error!("error in websocket connection: {e:#}");
331 0 : }
332 0 : }
333 0 : .instrument(span),
334 0 : );
335 0 :
336 0 : // Return the response so the spawned future can continue.
337 0 : Ok(response)
338 0 : } else if request.uri().path() == "/sql" && *request.method() == Method::POST {
339 0 : let ctx = RequestMonitoring::new(
340 0 : session_id,
341 0 : peer_addr,
342 0 : crate::metrics::Protocol::Http,
343 0 : &config.region,
344 0 : );
345 0 : let span = ctx.span.clone();
346 0 :
347 0 : sql_over_http::handle(config, ctx, request, backend, http_cancellation_token)
348 0 : .instrument(span)
349 0 : .await
350 0 : } else if request.uri().path() == "/sql" && *request.method() == Method::OPTIONS {
351 0 : Response::builder()
352 0 : .header("Allow", "OPTIONS, POST")
353 0 : .header("Access-Control-Allow-Origin", "*")
354 0 : .header(
355 0 : "Access-Control-Allow-Headers",
356 0 : "Neon-Connection-String, Neon-Raw-Text-Output, Neon-Array-Mode, Neon-Pool-Opt-In, Neon-Batch-Read-Only, Neon-Batch-Isolation-Level",
357 0 : )
358 0 : .header("Access-Control-Max-Age", "86400" /* 24 hours */)
359 0 : .status(StatusCode::OK) // 204 is also valid, but see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#status_code
360 0 : .body(Full::new(Bytes::new()))
361 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
362 : } else {
363 0 : json_response(StatusCode::BAD_REQUEST, "query is not supported")
364 : }
365 0 : }
|