LCOV - code coverage report
Current view: top level - compute_tools/src/http - server.rs (source / functions) Coverage Total Hit
Test: ac1e0b9bf1b4ead74961174b01ba016322d3f9a6.info Lines: 0.0 % 115 0
Test Date: 2025-07-08 09:16:10 Functions: 0.0 % 16 0

            Line data    Source code
       1              : use std::fmt::Display;
       2              : use std::net::{IpAddr, Ipv6Addr, SocketAddr};
       3              : use std::sync::Arc;
       4              : use std::time::Duration;
       5              : 
       6              : use anyhow::Result;
       7              : use axum::Router;
       8              : use axum::middleware::{self};
       9              : use axum::response::IntoResponse;
      10              : use axum::routing::{get, post};
      11              : use compute_api::responses::ComputeCtlConfig;
      12              : use http::StatusCode;
      13              : use tokio::net::TcpListener;
      14              : use tower::ServiceBuilder;
      15              : use tower_http::{
      16              :     auth::AsyncRequireAuthorizationLayer, request_id::PropagateRequestIdLayer, trace::TraceLayer,
      17              : };
      18              : use tracing::{Span, error, info};
      19              : 
      20              : use super::middleware::request_id::maybe_add_request_id_header;
      21              : use super::{
      22              :     headers::X_REQUEST_ID,
      23              :     middleware::authorize::Authorize,
      24              :     routes::{
      25              :         check_writability, configure, database_schema, dbs_and_roles, extension_server, extensions,
      26              :         grants, insights, lfc, metrics, metrics_json, status, terminate,
      27              :     },
      28              : };
      29              : use crate::compute::ComputeNode;
      30              : 
      31              : /// `compute_ctl` has two servers: internal and external. The internal server
      32              : /// binds to the loopback interface and handles communication from clients on
      33              : /// the compute. The external server is what receives communication from the
      34              : /// control plane, the metrics scraper, etc. We make the distinction because
      35              : /// certain routes in `compute_ctl` only need to be exposed to local processes
      36              : /// like Postgres via the neon extension and local_proxy.
      37              : #[derive(Clone, Debug)]
      38              : pub enum Server {
      39              :     Internal {
      40              :         port: u16,
      41              :     },
      42              :     External {
      43              :         port: u16,
      44              :         config: ComputeCtlConfig,
      45              :         compute_id: String,
      46              :     },
      47              : }
      48              : 
      49              : impl Display for Server {
      50            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      51            0 :         match self {
      52            0 :             Server::Internal { .. } => f.write_str("internal"),
      53            0 :             Server::External { .. } => f.write_str("external"),
      54              :         }
      55            0 :     }
      56              : }
      57              : 
      58              : impl From<&Server> for Router<Arc<ComputeNode>> {
      59            0 :     fn from(server: &Server) -> Self {
      60            0 :         let mut router = Router::<Arc<ComputeNode>>::new();
      61              : 
      62            0 :         router = match server {
      63              :             Server::Internal { .. } => {
      64            0 :                 router = router
      65            0 :                     .route(
      66            0 :                         "/extension_server/{*filename}",
      67            0 :                         post(extension_server::download_extension),
      68              :                     )
      69            0 :                     .route("/extensions", post(extensions::install_extension))
      70            0 :                     .route("/grants", post(grants::add_grant));
      71              : 
      72              :                 // Add in any testing support
      73            0 :                 if cfg!(feature = "testing") {
      74              :                     use super::routes::failpoints;
      75              : 
      76            0 :                     router = router.route("/failpoints", post(failpoints::configure_failpoints));
      77            0 :                 }
      78              : 
      79            0 :                 router
      80              :             }
      81              :             Server::External {
      82            0 :                 config, compute_id, ..
      83              :             } => {
      84            0 :                 let unauthenticated_router =
      85            0 :                     Router::<Arc<ComputeNode>>::new().route("/metrics", get(metrics::get_metrics));
      86              : 
      87            0 :                 let authenticated_router = Router::<Arc<ComputeNode>>::new()
      88            0 :                     .route("/lfc/prewarm", get(lfc::prewarm_state).post(lfc::prewarm))
      89            0 :                     .route("/lfc/offload", get(lfc::offload_state).post(lfc::offload))
      90            0 :                     .route("/check_writability", post(check_writability::is_writable))
      91            0 :                     .route("/configure", post(configure::configure))
      92            0 :                     .route("/database_schema", get(database_schema::get_schema_dump))
      93            0 :                     .route("/dbs_and_roles", get(dbs_and_roles::get_catalog_objects))
      94            0 :                     .route("/insights", get(insights::get_insights))
      95            0 :                     .route("/metrics.json", get(metrics_json::get_metrics))
      96            0 :                     .route("/status", get(status::get_status))
      97            0 :                     .route("/terminate", post(terminate::terminate))
      98            0 :                     .layer(AsyncRequireAuthorizationLayer::new(Authorize::new(
      99            0 :                         compute_id.clone(),
     100            0 :                         config.jwks.clone(),
     101              :                     )));
     102              : 
     103            0 :                 router
     104            0 :                     .merge(unauthenticated_router)
     105            0 :                     .merge(authenticated_router)
     106              :             }
     107              :         };
     108              : 
     109            0 :         router
     110            0 :             .fallback(Server::handle_404)
     111            0 :             .method_not_allowed_fallback(Server::handle_405)
     112            0 :             .layer(
     113            0 :                 ServiceBuilder::new()
     114            0 :                     .layer(tower_otel::trace::HttpLayer::server(tracing::Level::INFO))
     115              :                     // Add this middleware since we assume the request ID exists
     116            0 :                     .layer(middleware::from_fn(maybe_add_request_id_header))
     117            0 :                     .layer(
     118            0 :                         TraceLayer::new_for_http()
     119            0 :                             .on_request(|request: &http::Request<_>, _span: &Span| {
     120            0 :                                 let request_id = request
     121            0 :                                     .headers()
     122            0 :                                     .get(X_REQUEST_ID)
     123            0 :                                     .unwrap()
     124            0 :                                     .to_str()
     125            0 :                                     .unwrap();
     126              : 
     127            0 :                                 info!(%request_id, "{} {}", request.method(), request.uri());
     128            0 :                             })
     129            0 :                             .on_response(
     130            0 :                                 |response: &http::Response<_>, latency: Duration, _span: &Span| {
     131            0 :                                     let request_id = response
     132            0 :                                         .headers()
     133            0 :                                         .get(X_REQUEST_ID)
     134            0 :                                         .unwrap()
     135            0 :                                         .to_str()
     136            0 :                                         .unwrap();
     137              : 
     138            0 :                                     info!(
     139              :                                         %request_id,
     140            0 :                                         code = response.status().as_u16(),
     141            0 :                                         latency = latency.as_millis()
     142              :                                     );
     143            0 :                                 },
     144              :                             ),
     145              :                     )
     146            0 :                     .layer(PropagateRequestIdLayer::x_request_id()),
     147              :             )
     148            0 :     }
     149              : }
     150              : 
     151              : impl Server {
     152            0 :     async fn handle_404() -> impl IntoResponse {
     153            0 :         StatusCode::NOT_FOUND
     154            0 :     }
     155              : 
     156            0 :     async fn handle_405() -> impl IntoResponse {
     157            0 :         StatusCode::METHOD_NOT_ALLOWED
     158            0 :     }
     159              : 
     160            0 :     async fn listener(&self) -> Result<TcpListener> {
     161            0 :         let addr = SocketAddr::new(self.ip(), self.port());
     162            0 :         let listener = TcpListener::bind(&addr).await?;
     163              : 
     164            0 :         Ok(listener)
     165            0 :     }
     166              : 
     167            0 :     fn ip(&self) -> IpAddr {
     168            0 :         match self {
     169              :             // TODO: Change this to Ipv6Addr::LOCALHOST when the GitHub runners
     170              :             // allow binding to localhost
     171            0 :             Server::Internal { .. } => IpAddr::from(Ipv6Addr::UNSPECIFIED),
     172            0 :             Server::External { .. } => IpAddr::from(Ipv6Addr::UNSPECIFIED),
     173              :         }
     174            0 :     }
     175              : 
     176            0 :     fn port(&self) -> u16 {
     177            0 :         match self {
     178            0 :             Server::Internal { port, .. } => *port,
     179            0 :             Server::External { port, .. } => *port,
     180              :         }
     181            0 :     }
     182              : 
     183            0 :     async fn serve(self, compute: Arc<ComputeNode>) {
     184            0 :         let listener = self.listener().await.unwrap_or_else(|e| {
     185              :             // If we can't bind, the compute cannot operate correctly
     186            0 :             panic!(
     187            0 :                 "failed to bind the compute_ctl {} HTTP server to {}: {}",
     188              :                 self,
     189            0 :                 SocketAddr::new(self.ip(), self.port()),
     190              :                 e
     191              :             );
     192              :         });
     193              : 
     194            0 :         if tracing::enabled!(tracing::Level::INFO) {
     195            0 :             let local_addr = match listener.local_addr() {
     196            0 :                 Ok(local_addr) => local_addr,
     197            0 :                 Err(_) => SocketAddr::new(self.ip(), self.port()),
     198              :             };
     199              : 
     200            0 :             info!(
     201            0 :                 "compute_ctl {} HTTP server listening at {}",
     202              :                 self, local_addr
     203              :             );
     204            0 :         }
     205              : 
     206            0 :         let router = Router::from(&self)
     207            0 :             .with_state(compute)
     208            0 :             .into_make_service_with_connect_info::<SocketAddr>();
     209              : 
     210            0 :         if let Err(e) = axum::serve(listener, router).await {
     211            0 :             error!("compute_ctl {} HTTP server error: {}", self, e);
     212            0 :         }
     213            0 :     }
     214              : 
     215            0 :     pub fn launch(self, compute: &Arc<ComputeNode>) {
     216            0 :         let state = Arc::clone(compute);
     217              : 
     218            0 :         info!("Launching the {} server", self);
     219              : 
     220            0 :         tokio::spawn(self.serve(state));
     221            0 :     }
     222              : }
        

Generated by: LCOV version 2.1-beta