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 : mod conn_pool;
7 : mod json;
8 : mod sql_over_http;
9 : mod websocket;
10 :
11 : pub use conn_pool::GlobalConnPoolOptions;
12 :
13 : use anyhow::bail;
14 : use hyper::StatusCode;
15 : use metrics::IntCounterPairGuard;
16 : use rand::rngs::StdRng;
17 : use rand::SeedableRng;
18 : pub use reqwest_middleware::{ClientWithMiddleware, Error};
19 : pub use reqwest_retry::{policies::ExponentialBackoff, RetryTransientMiddleware};
20 : use tokio_util::task::TaskTracker;
21 :
22 : use crate::context::RequestMonitoring;
23 : use crate::metrics::NUM_CLIENT_CONNECTION_GAUGE;
24 : use crate::protocol2::{ProxyProtocolAccept, WithClientIp};
25 : use crate::rate_limiter::EndpointRateLimiter;
26 : use crate::serverless::backend::PoolingBackend;
27 : use crate::{cancellation::CancellationHandler, config::ProxyConfig};
28 : use futures::StreamExt;
29 : use hyper::{
30 : server::{
31 : accept,
32 : conn::{AddrIncoming, AddrStream},
33 : },
34 : Body, Method, Request, Response,
35 : };
36 :
37 : use std::net::IpAddr;
38 : use std::task::Poll;
39 : use std::{future::ready, sync::Arc};
40 : use tls_listener::TlsListener;
41 : use tokio::net::TcpListener;
42 : use tokio_util::sync::CancellationToken;
43 : use tracing::{error, info, info_span, warn, Instrument};
44 : use utils::http::{error::ApiError, json::json_response};
45 :
46 : pub const SERVERLESS_DRIVER_SNI: &str = "api";
47 :
48 25 : pub async fn task_main(
49 25 : config: &'static ProxyConfig,
50 25 : ws_listener: TcpListener,
51 25 : cancellation_token: CancellationToken,
52 25 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
53 25 : cancellation_handler: Arc<CancellationHandler>,
54 25 : ) -> anyhow::Result<()> {
55 25 : scopeguard::defer! {
56 25 : info!("websocket server has shut down");
57 : }
58 :
59 25 : let conn_pool = conn_pool::GlobalConnPool::new(&config.http_config);
60 25 : {
61 25 : let conn_pool = Arc::clone(&conn_pool);
62 25 : tokio::spawn(async move {
63 32 : conn_pool.gc_worker(StdRng::from_entropy()).await;
64 25 : });
65 25 : }
66 25 :
67 25 : // shutdown the connection pool
68 25 : tokio::spawn({
69 25 : let cancellation_token = cancellation_token.clone();
70 25 : let conn_pool = conn_pool.clone();
71 25 : async move {
72 25 : cancellation_token.cancelled().await;
73 25 : tokio::task::spawn_blocking(move || conn_pool.shutdown())
74 25 : .await
75 25 : .unwrap();
76 25 : }
77 25 : });
78 25 :
79 25 : let backend = Arc::new(PoolingBackend {
80 25 : pool: Arc::clone(&conn_pool),
81 25 : config,
82 25 : });
83 :
84 25 : let tls_config = match config.tls_config.as_ref() {
85 25 : Some(config) => config,
86 : None => {
87 0 : warn!("TLS config is missing, WebSocket Secure server will not be started");
88 0 : return Ok(());
89 : }
90 : };
91 25 : let tls_acceptor: tokio_rustls::TlsAcceptor = tls_config.to_server_config().into();
92 :
93 25 : let mut addr_incoming = AddrIncoming::from_listener(ws_listener)?;
94 25 : let _ = addr_incoming.set_nodelay(true);
95 25 : let addr_incoming = ProxyProtocolAccept {
96 25 : incoming: addr_incoming,
97 25 : };
98 25 :
99 25 : let ws_connections = tokio_util::task::task_tracker::TaskTracker::new();
100 25 : ws_connections.close(); // allows `ws_connections.wait to complete`
101 25 :
102 47 : let tls_listener = TlsListener::new(tls_acceptor, addr_incoming).filter(|conn| {
103 47 : if let Err(err) = conn {
104 0 : error!("failed to accept TLS connection for websockets: {err:?}");
105 0 : ready(false)
106 : } else {
107 47 : ready(true)
108 : }
109 47 : });
110 25 :
111 25 : let make_svc = hyper::service::make_service_fn(
112 47 : |stream: &tokio_rustls::server::TlsStream<WithClientIp<AddrStream>>| {
113 47 : let (io, _) = stream.get_ref();
114 47 : let client_addr = io.client_addr();
115 47 : let remote_addr = io.inner.remote_addr();
116 47 : let backend = backend.clone();
117 47 : let ws_connections = ws_connections.clone();
118 47 : let endpoint_rate_limiter = endpoint_rate_limiter.clone();
119 47 : let cancellation_handler = cancellation_handler.clone();
120 47 : async move {
121 47 : let peer_addr = match client_addr {
122 0 : Some(addr) => addr,
123 0 : None if config.require_client_ip => bail!("missing required client ip"),
124 47 : None => remote_addr,
125 : };
126 47 : Ok(MetricService::new(hyper::service::service_fn(
127 47 : move |req: Request<Body>| {
128 47 : let backend = backend.clone();
129 47 : let ws_connections = ws_connections.clone();
130 47 : let endpoint_rate_limiter = endpoint_rate_limiter.clone();
131 47 : let cancellation_handler = cancellation_handler.clone();
132 :
133 47 : async move {
134 47 : let session_id = uuid::Uuid::new_v4();
135 47 :
136 47 : request_handler(
137 47 : req,
138 47 : config,
139 47 : backend,
140 47 : ws_connections,
141 47 : cancellation_handler,
142 47 : session_id,
143 47 : peer_addr.ip(),
144 47 : endpoint_rate_limiter,
145 47 : )
146 47 : .instrument(info_span!(
147 47 : "serverless",
148 47 : session = %session_id,
149 47 : %peer_addr,
150 47 : ))
151 980 : .await
152 47 : }
153 47 : },
154 47 : )))
155 47 : }
156 47 : },
157 25 : );
158 25 :
159 25 : hyper::Server::builder(accept::from_stream(tls_listener))
160 25 : .serve(make_svc)
161 25 : .with_graceful_shutdown(cancellation_token.cancelled())
162 232 : .await?;
163 :
164 : // await websocket connections
165 25 : ws_connections.wait().await;
166 :
167 25 : Ok(())
168 25 : }
169 :
170 : struct MetricService<S> {
171 : inner: S,
172 : _gauge: IntCounterPairGuard,
173 : }
174 :
175 : impl<S> MetricService<S> {
176 47 : fn new(inner: S) -> MetricService<S> {
177 47 : MetricService {
178 47 : inner,
179 47 : _gauge: NUM_CLIENT_CONNECTION_GAUGE
180 47 : .with_label_values(&["http"])
181 47 : .guard(),
182 47 : }
183 47 : }
184 : }
185 :
186 : impl<S, ReqBody> hyper::service::Service<Request<ReqBody>> for MetricService<S>
187 : where
188 : S: hyper::service::Service<Request<ReqBody>>,
189 : {
190 : type Response = S::Response;
191 : type Error = S::Error;
192 : type Future = S::Future;
193 :
194 125 : fn poll_ready(&mut self, cx: &mut std::task::Context<'_>) -> Poll<Result<(), Self::Error>> {
195 125 : self.inner.poll_ready(cx)
196 125 : }
197 :
198 47 : fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
199 47 : self.inner.call(req)
200 47 : }
201 : }
202 :
203 : #[allow(clippy::too_many_arguments)]
204 47 : async fn request_handler(
205 47 : mut request: Request<Body>,
206 47 : config: &'static ProxyConfig,
207 47 : backend: Arc<PoolingBackend>,
208 47 : ws_connections: TaskTracker,
209 47 : cancellation_handler: Arc<CancellationHandler>,
210 47 : session_id: uuid::Uuid,
211 47 : peer_addr: IpAddr,
212 47 : endpoint_rate_limiter: Arc<EndpointRateLimiter>,
213 47 : ) -> Result<Response<Body>, ApiError> {
214 47 : let host = request
215 47 : .headers()
216 47 : .get("host")
217 47 : .and_then(|h| h.to_str().ok())
218 47 : .and_then(|h| h.split(':').next())
219 47 : .map(|s| s.to_string());
220 47 :
221 47 : // Check if the request is a websocket upgrade request.
222 47 : if hyper_tungstenite::is_upgrade_request(&request) {
223 0 : info!(session_id = ?session_id, "performing websocket upgrade");
224 :
225 0 : let (response, websocket) = hyper_tungstenite::upgrade(&mut request, None)
226 0 : .map_err(|e| ApiError::BadRequest(e.into()))?;
227 :
228 0 : ws_connections.spawn(
229 0 : async move {
230 0 : let ctx = RequestMonitoring::new(session_id, peer_addr, "ws", &config.region);
231 :
232 0 : if let Err(e) = websocket::serve_websocket(
233 0 : config,
234 0 : ctx,
235 0 : websocket,
236 0 : cancellation_handler,
237 0 : host,
238 0 : endpoint_rate_limiter,
239 0 : )
240 0 : .await
241 : {
242 0 : error!(session_id = ?session_id, "error in websocket connection: {e:#}");
243 0 : }
244 0 : }
245 0 : .in_current_span(),
246 0 : );
247 0 :
248 0 : // Return the response so the spawned future can continue.
249 0 : Ok(response)
250 47 : } else if request.uri().path() == "/sql" && request.method() == Method::POST {
251 47 : let ctx = RequestMonitoring::new(session_id, peer_addr, "http", &config.region);
252 47 :
253 980 : sql_over_http::handle(config, ctx, request, backend).await
254 0 : } else if request.uri().path() == "/sql" && request.method() == Method::OPTIONS {
255 0 : Response::builder()
256 0 : .header("Allow", "OPTIONS, POST")
257 0 : .header("Access-Control-Allow-Origin", "*")
258 0 : .header(
259 0 : "Access-Control-Allow-Headers",
260 0 : "Neon-Connection-String, Neon-Raw-Text-Output, Neon-Array-Mode, Neon-Pool-Opt-In, Neon-Batch-Read-Only, Neon-Batch-Isolation-Level",
261 0 : )
262 0 : .header("Access-Control-Max-Age", "86400" /* 24 hours */)
263 0 : .status(StatusCode::OK) // 204 is also valid, but see: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/OPTIONS#status_code
264 0 : .body(Body::empty())
265 0 : .map_err(|e| ApiError::InternalServerError(e.into()))
266 : } else {
267 0 : json_response(StatusCode::BAD_REQUEST, "query is not supported")
268 : }
269 47 : }
|