LCOV - code coverage report
Current view: top level - storage_controller/src - http.rs (source / functions) Coverage Total Hit
Test: d427f6f28cacba33c85e3c88c25b596f8e14b0f1.info Lines: 0.7 % 1538 11
Test Date: 2025-02-15 14:15:22 Functions: 0.7 % 423 3

            Line data    Source code
       1              : use crate::http;
       2              : use crate::metrics::{
       3              :     HttpRequestLatencyLabelGroup, HttpRequestStatusLabelGroup, PageserverRequestLabelGroup,
       4              :     METRICS_REGISTRY,
       5              : };
       6              : use crate::persistence::SafekeeperUpsert;
       7              : use crate::reconciler::ReconcileError;
       8              : use crate::service::{LeadershipStatus, Service, RECONCILE_TIMEOUT, STARTUP_RECONCILE_TIMEOUT};
       9              : use anyhow::Context;
      10              : use futures::Future;
      11              : use http_utils::{
      12              :     endpoint::{self, auth_middleware, check_permission_with, request_span},
      13              :     error::ApiError,
      14              :     failpoints::failpoints_handler,
      15              :     json::{json_request, json_response},
      16              :     request::{must_get_query_param, parse_query_param, parse_request_param},
      17              :     RequestExt, RouterBuilder,
      18              : };
      19              : use hyper::header::CONTENT_TYPE;
      20              : use hyper::{Body, Request, Response};
      21              : use hyper::{StatusCode, Uri};
      22              : use metrics::{BuildInfo, NeonMetrics};
      23              : use pageserver_api::controller_api::{
      24              :     MetadataHealthListOutdatedRequest, MetadataHealthListOutdatedResponse,
      25              :     MetadataHealthListUnhealthyResponse, MetadataHealthUpdateRequest, MetadataHealthUpdateResponse,
      26              :     SafekeeperSchedulingPolicyRequest, ShardsPreferredAzsRequest, TenantCreateRequest,
      27              : };
      28              : use pageserver_api::models::{
      29              :     TenantConfigPatchRequest, TenantConfigRequest, TenantLocationConfigRequest,
      30              :     TenantShardSplitRequest, TenantTimeTravelRequest, TimelineArchivalConfigRequest,
      31              :     TimelineCreateRequest,
      32              : };
      33              : use pageserver_api::shard::TenantShardId;
      34              : use pageserver_client::{mgmt_api, BlockUnblock};
      35              : use std::str::FromStr;
      36              : use std::sync::Arc;
      37              : use std::time::{Duration, Instant};
      38              : use tokio_util::sync::CancellationToken;
      39              : use utils::auth::{Scope, SwappableJwtAuth};
      40              : use utils::id::{NodeId, TenantId, TimelineId};
      41              : 
      42              : use pageserver_api::controller_api::{
      43              :     NodeAvailability, NodeConfigureRequest, NodeRegisterRequest, TenantPolicyRequest,
      44              :     TenantShardMigrateRequest,
      45              : };
      46              : use pageserver_api::upcall_api::{ReAttachRequest, ValidateRequest};
      47              : 
      48              : use control_plane::storage_controller::{AttachHookRequest, InspectRequest};
      49              : 
      50              : use routerify::Middleware;
      51              : 
      52              : /// State available to HTTP request handlers
      53              : pub struct HttpState {
      54              :     service: Arc<crate::service::Service>,
      55              :     auth: Option<Arc<SwappableJwtAuth>>,
      56              :     neon_metrics: NeonMetrics,
      57              :     allowlist_routes: Vec<Uri>,
      58              : }
      59              : 
      60              : impl HttpState {
      61            0 :     pub fn new(
      62            0 :         service: Arc<crate::service::Service>,
      63            0 :         auth: Option<Arc<SwappableJwtAuth>>,
      64            0 :         build_info: BuildInfo,
      65            0 :     ) -> Self {
      66            0 :         let allowlist_routes = ["/status", "/ready", "/metrics"]
      67            0 :             .iter()
      68            0 :             .map(|v| v.parse().unwrap())
      69            0 :             .collect::<Vec<_>>();
      70            0 :         Self {
      71            0 :             service,
      72            0 :             auth,
      73            0 :             neon_metrics: NeonMetrics::new(build_info),
      74            0 :             allowlist_routes,
      75            0 :         }
      76            0 :     }
      77              : }
      78              : 
      79              : #[inline(always)]
      80            0 : fn get_state(request: &Request<Body>) -> &HttpState {
      81            0 :     request
      82            0 :         .data::<Arc<HttpState>>()
      83            0 :         .expect("unknown state type")
      84            0 :         .as_ref()
      85            0 : }
      86              : 
      87              : /// Pageserver calls into this on startup, to learn which tenants it should attach
      88            0 : async fn handle_re_attach(req: Request<Body>) -> Result<Response<Body>, ApiError> {
      89            0 :     check_permissions(&req, Scope::GenerationsApi)?;
      90              : 
      91            0 :     let mut req = match maybe_forward(req).await {
      92            0 :         ForwardOutcome::Forwarded(res) => {
      93            0 :             return res;
      94              :         }
      95            0 :         ForwardOutcome::NotForwarded(req) => req,
      96              :     };
      97              : 
      98            0 :     let reattach_req = json_request::<ReAttachRequest>(&mut req).await?;
      99            0 :     let state = get_state(&req);
     100            0 :     json_response(StatusCode::OK, state.service.re_attach(reattach_req).await?)
     101            0 : }
     102              : 
     103              : /// Pageserver calls into this before doing deletions, to confirm that it still
     104              : /// holds the latest generation for the tenants with deletions enqueued
     105            0 : async fn handle_validate(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     106            0 :     check_permissions(&req, Scope::GenerationsApi)?;
     107              : 
     108            0 :     let mut req = match maybe_forward(req).await {
     109            0 :         ForwardOutcome::Forwarded(res) => {
     110            0 :             return res;
     111              :         }
     112            0 :         ForwardOutcome::NotForwarded(req) => req,
     113              :     };
     114              : 
     115            0 :     let validate_req = json_request::<ValidateRequest>(&mut req).await?;
     116            0 :     let state = get_state(&req);
     117            0 :     json_response(StatusCode::OK, state.service.validate(validate_req).await?)
     118            0 : }
     119              : 
     120              : /// Call into this before attaching a tenant to a pageserver, to acquire a generation number
     121              : /// (in the real control plane this is unnecessary, because the same program is managing
     122              : ///  generation numbers and doing attachments).
     123            0 : async fn handle_attach_hook(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     124            0 :     check_permissions(&req, Scope::Admin)?;
     125              : 
     126            0 :     let mut req = match maybe_forward(req).await {
     127            0 :         ForwardOutcome::Forwarded(res) => {
     128            0 :             return res;
     129              :         }
     130            0 :         ForwardOutcome::NotForwarded(req) => req,
     131              :     };
     132              : 
     133            0 :     let attach_req = json_request::<AttachHookRequest>(&mut req).await?;
     134            0 :     let state = get_state(&req);
     135            0 : 
     136            0 :     json_response(
     137            0 :         StatusCode::OK,
     138            0 :         state
     139            0 :             .service
     140            0 :             .attach_hook(attach_req)
     141            0 :             .await
     142            0 :             .map_err(ApiError::InternalServerError)?,
     143              :     )
     144            0 : }
     145              : 
     146            0 : async fn handle_inspect(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     147            0 :     check_permissions(&req, Scope::Admin)?;
     148              : 
     149            0 :     let mut req = match maybe_forward(req).await {
     150            0 :         ForwardOutcome::Forwarded(res) => {
     151            0 :             return res;
     152              :         }
     153            0 :         ForwardOutcome::NotForwarded(req) => req,
     154              :     };
     155              : 
     156            0 :     let inspect_req = json_request::<InspectRequest>(&mut req).await?;
     157              : 
     158            0 :     let state = get_state(&req);
     159            0 : 
     160            0 :     json_response(StatusCode::OK, state.service.inspect(inspect_req))
     161            0 : }
     162              : 
     163            0 : async fn handle_tenant_create(
     164            0 :     service: Arc<Service>,
     165            0 :     req: Request<Body>,
     166            0 : ) -> Result<Response<Body>, ApiError> {
     167            0 :     check_permissions(&req, Scope::PageServerApi)?;
     168              : 
     169            0 :     let mut req = match maybe_forward(req).await {
     170            0 :         ForwardOutcome::Forwarded(res) => {
     171            0 :             return res;
     172              :         }
     173            0 :         ForwardOutcome::NotForwarded(req) => req,
     174              :     };
     175              : 
     176            0 :     let create_req = json_request::<TenantCreateRequest>(&mut req).await?;
     177              : 
     178              :     json_response(
     179              :         StatusCode::CREATED,
     180            0 :         service.tenant_create(create_req).await?,
     181              :     )
     182            0 : }
     183              : 
     184            0 : async fn handle_tenant_location_config(
     185            0 :     service: Arc<Service>,
     186            0 :     req: Request<Body>,
     187            0 : ) -> Result<Response<Body>, ApiError> {
     188            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
     189            0 :     check_permissions(&req, Scope::PageServerApi)?;
     190              : 
     191            0 :     let mut req = match maybe_forward(req).await {
     192            0 :         ForwardOutcome::Forwarded(res) => {
     193            0 :             return res;
     194              :         }
     195            0 :         ForwardOutcome::NotForwarded(req) => req,
     196              :     };
     197              : 
     198            0 :     let config_req = json_request::<TenantLocationConfigRequest>(&mut req).await?;
     199              :     json_response(
     200              :         StatusCode::OK,
     201            0 :         service
     202            0 :             .tenant_location_config(tenant_shard_id, config_req)
     203            0 :             .await?,
     204              :     )
     205            0 : }
     206              : 
     207            0 : async fn handle_tenant_config_patch(
     208            0 :     service: Arc<Service>,
     209            0 :     req: Request<Body>,
     210            0 : ) -> Result<Response<Body>, ApiError> {
     211            0 :     check_permissions(&req, Scope::PageServerApi)?;
     212              : 
     213            0 :     let mut req = match maybe_forward(req).await {
     214            0 :         ForwardOutcome::Forwarded(res) => {
     215            0 :             return res;
     216              :         }
     217            0 :         ForwardOutcome::NotForwarded(req) => req,
     218              :     };
     219              : 
     220            0 :     let config_req = json_request::<TenantConfigPatchRequest>(&mut req).await?;
     221              : 
     222              :     json_response(
     223              :         StatusCode::OK,
     224            0 :         service.tenant_config_patch(config_req).await?,
     225              :     )
     226            0 : }
     227              : 
     228            0 : async fn handle_tenant_config_set(
     229            0 :     service: Arc<Service>,
     230            0 :     req: Request<Body>,
     231            0 : ) -> Result<Response<Body>, ApiError> {
     232            0 :     check_permissions(&req, Scope::PageServerApi)?;
     233              : 
     234            0 :     let mut req = match maybe_forward(req).await {
     235            0 :         ForwardOutcome::Forwarded(res) => {
     236            0 :             return res;
     237              :         }
     238            0 :         ForwardOutcome::NotForwarded(req) => req,
     239              :     };
     240              : 
     241            0 :     let config_req = json_request::<TenantConfigRequest>(&mut req).await?;
     242              : 
     243            0 :     json_response(StatusCode::OK, service.tenant_config_set(config_req).await?)
     244            0 : }
     245              : 
     246            0 : async fn handle_tenant_config_get(
     247            0 :     service: Arc<Service>,
     248            0 :     req: Request<Body>,
     249            0 : ) -> Result<Response<Body>, ApiError> {
     250            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     251            0 :     check_permissions(&req, Scope::PageServerApi)?;
     252              : 
     253            0 :     match maybe_forward(req).await {
     254            0 :         ForwardOutcome::Forwarded(res) => {
     255            0 :             return res;
     256              :         }
     257            0 :         ForwardOutcome::NotForwarded(_req) => {}
     258            0 :     };
     259            0 : 
     260            0 :     json_response(StatusCode::OK, service.tenant_config_get(tenant_id)?)
     261            0 : }
     262              : 
     263            0 : async fn handle_tenant_time_travel_remote_storage(
     264            0 :     service: Arc<Service>,
     265            0 :     req: Request<Body>,
     266            0 : ) -> Result<Response<Body>, ApiError> {
     267            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     268            0 :     check_permissions(&req, Scope::PageServerApi)?;
     269              : 
     270            0 :     let mut req = match maybe_forward(req).await {
     271            0 :         ForwardOutcome::Forwarded(res) => {
     272            0 :             return res;
     273              :         }
     274            0 :         ForwardOutcome::NotForwarded(req) => req,
     275              :     };
     276              : 
     277            0 :     let time_travel_req = json_request::<TenantTimeTravelRequest>(&mut req).await?;
     278              : 
     279            0 :     let timestamp_raw = must_get_query_param(&req, "travel_to")?;
     280            0 :     let _timestamp = humantime::parse_rfc3339(&timestamp_raw).map_err(|_e| {
     281            0 :         ApiError::BadRequest(anyhow::anyhow!(
     282            0 :             "Invalid time for travel_to: {timestamp_raw:?}"
     283            0 :         ))
     284            0 :     })?;
     285              : 
     286            0 :     let done_if_after_raw = must_get_query_param(&req, "done_if_after")?;
     287            0 :     let _done_if_after = humantime::parse_rfc3339(&done_if_after_raw).map_err(|_e| {
     288            0 :         ApiError::BadRequest(anyhow::anyhow!(
     289            0 :             "Invalid time for done_if_after: {done_if_after_raw:?}"
     290            0 :         ))
     291            0 :     })?;
     292              : 
     293            0 :     service
     294            0 :         .tenant_time_travel_remote_storage(
     295            0 :             &time_travel_req,
     296            0 :             tenant_id,
     297            0 :             timestamp_raw,
     298            0 :             done_if_after_raw,
     299            0 :         )
     300            0 :         .await?;
     301            0 :     json_response(StatusCode::OK, ())
     302            0 : }
     303              : 
     304            0 : fn map_reqwest_hyper_status(status: reqwest::StatusCode) -> Result<hyper::StatusCode, ApiError> {
     305            0 :     hyper::StatusCode::from_u16(status.as_u16())
     306            0 :         .context("invalid status code")
     307            0 :         .map_err(ApiError::InternalServerError)
     308            0 : }
     309              : 
     310            0 : async fn handle_tenant_secondary_download(
     311            0 :     service: Arc<Service>,
     312            0 :     req: Request<Body>,
     313            0 : ) -> Result<Response<Body>, ApiError> {
     314            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     315            0 :     let wait = parse_query_param(&req, "wait_ms")?.map(Duration::from_millis);
     316            0 : 
     317            0 :     match maybe_forward(req).await {
     318            0 :         ForwardOutcome::Forwarded(res) => {
     319            0 :             return res;
     320              :         }
     321            0 :         ForwardOutcome::NotForwarded(_req) => {}
     322              :     };
     323              : 
     324            0 :     let (status, progress) = service.tenant_secondary_download(tenant_id, wait).await?;
     325            0 :     json_response(map_reqwest_hyper_status(status)?, progress)
     326            0 : }
     327              : 
     328            0 : async fn handle_tenant_delete(
     329            0 :     service: Arc<Service>,
     330            0 :     req: Request<Body>,
     331            0 : ) -> Result<Response<Body>, ApiError> {
     332            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     333            0 :     check_permissions(&req, Scope::PageServerApi)?;
     334              : 
     335            0 :     match maybe_forward(req).await {
     336            0 :         ForwardOutcome::Forwarded(res) => {
     337            0 :             return res;
     338              :         }
     339            0 :         ForwardOutcome::NotForwarded(_req) => {}
     340              :     };
     341              : 
     342            0 :     let status_code = service
     343            0 :         .tenant_delete(tenant_id)
     344            0 :         .await
     345            0 :         .and_then(map_reqwest_hyper_status)?;
     346              : 
     347            0 :     if status_code == StatusCode::NOT_FOUND {
     348              :         // The pageserver uses 404 for successful deletion, but we use 200
     349            0 :         json_response(StatusCode::OK, ())
     350              :     } else {
     351            0 :         json_response(status_code, ())
     352              :     }
     353            0 : }
     354              : 
     355            0 : async fn handle_tenant_timeline_create(
     356            0 :     service: Arc<Service>,
     357            0 :     req: Request<Body>,
     358            0 : ) -> Result<Response<Body>, ApiError> {
     359            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     360            0 :     check_permissions(&req, Scope::PageServerApi)?;
     361              : 
     362            0 :     let mut req = match maybe_forward(req).await {
     363            0 :         ForwardOutcome::Forwarded(res) => {
     364            0 :             return res;
     365              :         }
     366            0 :         ForwardOutcome::NotForwarded(req) => req,
     367              :     };
     368              : 
     369            0 :     let create_req = json_request::<TimelineCreateRequest>(&mut req).await?;
     370              :     json_response(
     371              :         StatusCode::CREATED,
     372            0 :         service
     373            0 :             .tenant_timeline_create(tenant_id, create_req)
     374            0 :             .await?,
     375              :     )
     376            0 : }
     377              : 
     378            0 : async fn handle_tenant_timeline_delete(
     379            0 :     service: Arc<Service>,
     380            0 :     req: Request<Body>,
     381            0 : ) -> Result<Response<Body>, ApiError> {
     382            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     383            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     384              : 
     385            0 :     check_permissions(&req, Scope::PageServerApi)?;
     386              : 
     387            0 :     match maybe_forward(req).await {
     388            0 :         ForwardOutcome::Forwarded(res) => {
     389            0 :             return res;
     390              :         }
     391            0 :         ForwardOutcome::NotForwarded(_req) => {}
     392              :     };
     393              : 
     394              :     // For timeline deletions, which both implement an "initially return 202, then 404 once
     395              :     // we're done" semantic, we wrap with a retry loop to expose a simpler API upstream.
     396            0 :     async fn deletion_wrapper<R, F>(service: Arc<Service>, f: F) -> Result<Response<Body>, ApiError>
     397            0 :     where
     398            0 :         R: std::future::Future<Output = Result<StatusCode, ApiError>> + Send + 'static,
     399            0 :         F: Fn(Arc<Service>) -> R + Send + Sync + 'static,
     400            0 :     {
     401              :         // On subsequent retries, wait longer.
     402              :         // Enable callers with a 25 second request timeout to reliably get a response
     403              :         const MAX_WAIT: Duration = Duration::from_secs(25);
     404              :         const MAX_RETRY_PERIOD: Duration = Duration::from_secs(5);
     405              : 
     406            0 :         let started_at = Instant::now();
     407            0 : 
     408            0 :         // To keep deletion reasonably snappy for small tenants, initially check after 1 second if deletion
     409            0 :         // completed.
     410            0 :         let mut retry_period = Duration::from_secs(1);
     411              : 
     412              :         loop {
     413            0 :             let status = f(service.clone()).await?;
     414            0 :             match status {
     415              :                 StatusCode::ACCEPTED => {
     416            0 :                     tracing::info!("Deletion accepted, waiting to try again...");
     417            0 :                     tokio::time::sleep(retry_period).await;
     418            0 :                     retry_period = MAX_RETRY_PERIOD;
     419              :                 }
     420              :                 StatusCode::CONFLICT => {
     421            0 :                     tracing::info!("Deletion already in progress, waiting to try again...");
     422            0 :                     tokio::time::sleep(retry_period).await;
     423              :                 }
     424              :                 StatusCode::NOT_FOUND => {
     425            0 :                     tracing::info!("Deletion complete");
     426            0 :                     return json_response(StatusCode::OK, ());
     427              :                 }
     428              :                 _ => {
     429            0 :                     tracing::warn!("Unexpected status {status}");
     430            0 :                     return json_response(status, ());
     431              :                 }
     432              :             }
     433              : 
     434            0 :             let now = Instant::now();
     435            0 :             if now + retry_period > started_at + MAX_WAIT {
     436            0 :                 tracing::info!("Deletion timed out waiting for 404");
     437              :                 // REQUEST_TIMEOUT would be more appropriate, but CONFLICT is already part of
     438              :                 // the pageserver's swagger definition for this endpoint, and has the same desired
     439              :                 // effect of causing the control plane to retry later.
     440            0 :                 return json_response(StatusCode::CONFLICT, ());
     441            0 :             }
     442              :         }
     443            0 :     }
     444              : 
     445            0 :     deletion_wrapper(service, move |service| async move {
     446            0 :         service
     447            0 :             .tenant_timeline_delete(tenant_id, timeline_id)
     448            0 :             .await
     449            0 :             .and_then(map_reqwest_hyper_status)
     450            0 :     })
     451            0 :     .await
     452            0 : }
     453              : 
     454            0 : async fn handle_tenant_timeline_archival_config(
     455            0 :     service: Arc<Service>,
     456            0 :     req: Request<Body>,
     457            0 : ) -> Result<Response<Body>, ApiError> {
     458            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     459            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     460              : 
     461            0 :     check_permissions(&req, Scope::PageServerApi)?;
     462              : 
     463            0 :     let mut req = match maybe_forward(req).await {
     464            0 :         ForwardOutcome::Forwarded(res) => {
     465            0 :             return res;
     466              :         }
     467            0 :         ForwardOutcome::NotForwarded(req) => req,
     468              :     };
     469              : 
     470            0 :     let create_req = json_request::<TimelineArchivalConfigRequest>(&mut req).await?;
     471              : 
     472            0 :     service
     473            0 :         .tenant_timeline_archival_config(tenant_id, timeline_id, create_req)
     474            0 :         .await?;
     475              : 
     476            0 :     json_response(StatusCode::OK, ())
     477            0 : }
     478              : 
     479            0 : async fn handle_tenant_timeline_detach_ancestor(
     480            0 :     service: Arc<Service>,
     481            0 :     req: Request<Body>,
     482            0 : ) -> Result<Response<Body>, ApiError> {
     483            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     484            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     485              : 
     486            0 :     check_permissions(&req, Scope::PageServerApi)?;
     487              : 
     488            0 :     match maybe_forward(req).await {
     489            0 :         ForwardOutcome::Forwarded(res) => {
     490            0 :             return res;
     491              :         }
     492            0 :         ForwardOutcome::NotForwarded(_req) => {}
     493              :     };
     494              : 
     495            0 :     let res = service
     496            0 :         .tenant_timeline_detach_ancestor(tenant_id, timeline_id)
     497            0 :         .await?;
     498              : 
     499            0 :     json_response(StatusCode::OK, res)
     500            0 : }
     501              : 
     502            0 : async fn handle_tenant_timeline_block_unblock_gc(
     503            0 :     service: Arc<Service>,
     504            0 :     req: Request<Body>,
     505            0 :     dir: BlockUnblock,
     506            0 : ) -> Result<Response<Body>, ApiError> {
     507            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     508            0 :     check_permissions(&req, Scope::PageServerApi)?;
     509              : 
     510            0 :     let timeline_id: TimelineId = parse_request_param(&req, "timeline_id")?;
     511              : 
     512            0 :     service
     513            0 :         .tenant_timeline_block_unblock_gc(tenant_id, timeline_id, dir)
     514            0 :         .await?;
     515              : 
     516            0 :     json_response(StatusCode::OK, ())
     517            0 : }
     518              : 
     519              : // For metric labels where we would like to include the approximate path, but exclude high-cardinality fields like query parameters
     520              : // and tenant/timeline IDs.  Since we are proxying to arbitrary paths, we don't have routing templates to
     521              : // compare to, so we can just filter out our well known ID format with regexes.
     522            3 : fn path_without_ids(path: &str) -> String {
     523              :     static ID_REGEX: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
     524            3 :     ID_REGEX
     525            3 :         .get_or_init(|| regex::Regex::new(r"([0-9a-fA-F]{32}(-[0-9]{4})?|\?.*)").unwrap())
     526            3 :         .replace_all(path, "")
     527            3 :         .to_string()
     528            3 : }
     529              : 
     530            0 : async fn handle_tenant_timeline_passthrough(
     531            0 :     service: Arc<Service>,
     532            0 :     req: Request<Body>,
     533            0 : ) -> Result<Response<Body>, ApiError> {
     534            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     535            0 :     check_permissions(&req, Scope::PageServerApi)?;
     536              : 
     537            0 :     let req = match maybe_forward(req).await {
     538            0 :         ForwardOutcome::Forwarded(res) => {
     539            0 :             return res;
     540              :         }
     541            0 :         ForwardOutcome::NotForwarded(req) => req,
     542              :     };
     543              : 
     544            0 :     let Some(path) = req.uri().path_and_query() else {
     545              :         // This should never happen, our request router only calls us if there is a path
     546            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!("Missing path")));
     547              :     };
     548              : 
     549            0 :     tracing::info!("Proxying request for tenant {} ({})", tenant_id, path);
     550              : 
     551              :     // Find the node that holds shard zero
     552            0 :     let (node, tenant_shard_id) = service.tenant_shard0_node(tenant_id).await?;
     553              : 
     554              :     // Callers will always pass an unsharded tenant ID.  Before proxying, we must
     555              :     // rewrite this to a shard-aware shard zero ID.
     556            0 :     let path = format!("{}", path);
     557            0 :     let tenant_str = tenant_id.to_string();
     558            0 :     let tenant_shard_str = format!("{}", tenant_shard_id);
     559            0 :     let path = path.replace(&tenant_str, &tenant_shard_str);
     560            0 : 
     561            0 :     let latency = &METRICS_REGISTRY
     562            0 :         .metrics_group
     563            0 :         .storage_controller_passthrough_request_latency;
     564            0 : 
     565            0 :     let path_label = path_without_ids(&path)
     566            0 :         .split('/')
     567            0 :         .filter(|token| !token.is_empty())
     568            0 :         .collect::<Vec<_>>()
     569            0 :         .join("_");
     570            0 :     let labels = PageserverRequestLabelGroup {
     571            0 :         pageserver_id: &node.get_id().to_string(),
     572            0 :         path: &path_label,
     573            0 :         method: crate::metrics::Method::Get,
     574            0 :     };
     575            0 : 
     576            0 :     let _timer = latency.start_timer(labels.clone());
     577            0 : 
     578            0 :     let client = mgmt_api::Client::new(node.base_url(), service.get_config().jwt_token.as_deref());
     579            0 :     let resp = client.get_raw(path).await.map_err(|e|
     580              :         // We return 503 here because if we can't successfully send a request to the pageserver,
     581              :         // either we aren't available or the pageserver is unavailable.
     582            0 :         ApiError::ResourceUnavailable(format!("Error sending pageserver API request to {node}: {e}").into()))?;
     583              : 
     584            0 :     if !resp.status().is_success() {
     585            0 :         let error_counter = &METRICS_REGISTRY
     586            0 :             .metrics_group
     587            0 :             .storage_controller_passthrough_request_error;
     588            0 :         error_counter.inc(labels);
     589            0 :     }
     590              : 
     591              :     // Transform 404 into 503 if we raced with a migration
     592            0 :     if resp.status() == reqwest::StatusCode::NOT_FOUND {
     593              :         // Look up node again: if we migrated it will be different
     594            0 :         let (new_node, _tenant_shard_id) = service.tenant_shard0_node(tenant_id).await?;
     595            0 :         if new_node.get_id() != node.get_id() {
     596              :             // Rather than retry here, send the client a 503 to prompt a retry: this matches
     597              :             // the pageserver's use of 503, and all clients calling this API should retry on 503.
     598            0 :             return Err(ApiError::ResourceUnavailable(
     599            0 :                 format!("Pageserver {node} returned 404, was migrated to {new_node}").into(),
     600            0 :             ));
     601            0 :         }
     602            0 :     }
     603              : 
     604              :     // We have a reqest::Response, would like a http::Response
     605            0 :     let mut builder = hyper::Response::builder().status(map_reqwest_hyper_status(resp.status())?);
     606            0 :     for (k, v) in resp.headers() {
     607            0 :         builder = builder.header(k.as_str(), v.as_bytes());
     608            0 :     }
     609              : 
     610            0 :     let response = builder
     611            0 :         .body(Body::wrap_stream(resp.bytes_stream()))
     612            0 :         .map_err(|e| ApiError::InternalServerError(e.into()))?;
     613              : 
     614            0 :     Ok(response)
     615            0 : }
     616              : 
     617            0 : async fn handle_tenant_locate(
     618            0 :     service: Arc<Service>,
     619            0 :     req: Request<Body>,
     620            0 : ) -> Result<Response<Body>, ApiError> {
     621            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     622              : 
     623            0 :     check_permissions(&req, Scope::Admin)?;
     624              : 
     625            0 :     match maybe_forward(req).await {
     626            0 :         ForwardOutcome::Forwarded(res) => {
     627            0 :             return res;
     628              :         }
     629            0 :         ForwardOutcome::NotForwarded(_req) => {}
     630            0 :     };
     631            0 : 
     632            0 :     json_response(StatusCode::OK, service.tenant_locate(tenant_id)?)
     633            0 : }
     634              : 
     635            0 : async fn handle_tenant_describe(
     636            0 :     service: Arc<Service>,
     637            0 :     req: Request<Body>,
     638            0 : ) -> Result<Response<Body>, ApiError> {
     639            0 :     check_permissions(&req, Scope::Scrubber)?;
     640              : 
     641            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     642              : 
     643            0 :     match maybe_forward(req).await {
     644            0 :         ForwardOutcome::Forwarded(res) => {
     645            0 :             return res;
     646              :         }
     647            0 :         ForwardOutcome::NotForwarded(_req) => {}
     648            0 :     };
     649            0 : 
     650            0 :     json_response(StatusCode::OK, service.tenant_describe(tenant_id)?)
     651            0 : }
     652              : 
     653            0 : async fn handle_tenant_list(
     654            0 :     service: Arc<Service>,
     655            0 :     req: Request<Body>,
     656            0 : ) -> Result<Response<Body>, ApiError> {
     657            0 :     check_permissions(&req, Scope::Admin)?;
     658              : 
     659            0 :     let limit: Option<usize> = parse_query_param(&req, "limit")?;
     660            0 :     let start_after: Option<TenantId> = parse_query_param(&req, "start_after")?;
     661            0 :     tracing::info!("start_after: {:?}", start_after);
     662              : 
     663            0 :     match maybe_forward(req).await {
     664            0 :         ForwardOutcome::Forwarded(res) => {
     665            0 :             return res;
     666              :         }
     667            0 :         ForwardOutcome::NotForwarded(_req) => {}
     668            0 :     };
     669            0 : 
     670            0 :     json_response(StatusCode::OK, service.tenant_list(limit, start_after))
     671            0 : }
     672              : 
     673            0 : async fn handle_node_register(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     674            0 :     check_permissions(&req, Scope::Infra)?;
     675              : 
     676            0 :     let mut req = match maybe_forward(req).await {
     677            0 :         ForwardOutcome::Forwarded(res) => {
     678            0 :             return res;
     679              :         }
     680            0 :         ForwardOutcome::NotForwarded(req) => req,
     681              :     };
     682              : 
     683            0 :     let register_req = json_request::<NodeRegisterRequest>(&mut req).await?;
     684            0 :     let state = get_state(&req);
     685            0 :     state.service.node_register(register_req).await?;
     686            0 :     json_response(StatusCode::OK, ())
     687            0 : }
     688              : 
     689            0 : async fn handle_node_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     690            0 :     check_permissions(&req, Scope::Infra)?;
     691              : 
     692            0 :     let req = match maybe_forward(req).await {
     693            0 :         ForwardOutcome::Forwarded(res) => {
     694            0 :             return res;
     695              :         }
     696            0 :         ForwardOutcome::NotForwarded(req) => req,
     697            0 :     };
     698            0 : 
     699            0 :     let state = get_state(&req);
     700            0 :     let mut nodes = state.service.node_list().await?;
     701            0 :     nodes.sort_by_key(|n| n.get_id());
     702            0 :     let api_nodes = nodes.into_iter().map(|n| n.describe()).collect::<Vec<_>>();
     703            0 : 
     704            0 :     json_response(StatusCode::OK, api_nodes)
     705            0 : }
     706              : 
     707            0 : async fn handle_node_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     708            0 :     check_permissions(&req, Scope::Admin)?;
     709              : 
     710            0 :     let req = match maybe_forward(req).await {
     711            0 :         ForwardOutcome::Forwarded(res) => {
     712            0 :             return res;
     713              :         }
     714            0 :         ForwardOutcome::NotForwarded(req) => req,
     715            0 :     };
     716            0 : 
     717            0 :     let state = get_state(&req);
     718            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     719            0 :     json_response(StatusCode::OK, state.service.node_drop(node_id).await?)
     720            0 : }
     721              : 
     722            0 : async fn handle_node_delete(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     723            0 :     check_permissions(&req, Scope::Admin)?;
     724              : 
     725            0 :     let req = match maybe_forward(req).await {
     726            0 :         ForwardOutcome::Forwarded(res) => {
     727            0 :             return res;
     728              :         }
     729            0 :         ForwardOutcome::NotForwarded(req) => req,
     730            0 :     };
     731            0 : 
     732            0 :     let state = get_state(&req);
     733            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     734            0 :     json_response(StatusCode::OK, state.service.node_delete(node_id).await?)
     735            0 : }
     736              : 
     737            0 : async fn handle_node_configure(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     738            0 :     check_permissions(&req, Scope::Admin)?;
     739              : 
     740            0 :     let mut req = match maybe_forward(req).await {
     741            0 :         ForwardOutcome::Forwarded(res) => {
     742            0 :             return res;
     743              :         }
     744            0 :         ForwardOutcome::NotForwarded(req) => req,
     745              :     };
     746              : 
     747            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     748            0 :     let config_req = json_request::<NodeConfigureRequest>(&mut req).await?;
     749            0 :     if node_id != config_req.node_id {
     750            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!(
     751            0 :             "Path and body node_id differ"
     752            0 :         )));
     753            0 :     }
     754            0 :     let state = get_state(&req);
     755            0 : 
     756            0 :     json_response(
     757            0 :         StatusCode::OK,
     758            0 :         state
     759            0 :             .service
     760            0 :             .external_node_configure(
     761            0 :                 config_req.node_id,
     762            0 :                 config_req.availability.map(NodeAvailability::from),
     763            0 :                 config_req.scheduling,
     764            0 :             )
     765            0 :             .await?,
     766              :     )
     767            0 : }
     768              : 
     769            0 : async fn handle_node_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     770            0 :     check_permissions(&req, Scope::Infra)?;
     771              : 
     772            0 :     let req = match maybe_forward(req).await {
     773            0 :         ForwardOutcome::Forwarded(res) => {
     774            0 :             return res;
     775              :         }
     776            0 :         ForwardOutcome::NotForwarded(req) => req,
     777            0 :     };
     778            0 : 
     779            0 :     let state = get_state(&req);
     780            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     781              : 
     782            0 :     let node_status = state.service.get_node(node_id).await?;
     783              : 
     784            0 :     json_response(StatusCode::OK, node_status)
     785            0 : }
     786              : 
     787            0 : async fn handle_node_shards(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     788            0 :     check_permissions(&req, Scope::Admin)?;
     789              : 
     790            0 :     let state = get_state(&req);
     791            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     792              : 
     793            0 :     let node_status = state.service.get_node_shards(node_id).await?;
     794              : 
     795            0 :     json_response(StatusCode::OK, node_status)
     796            0 : }
     797              : 
     798            0 : async fn handle_get_leader(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     799            0 :     check_permissions(&req, Scope::Admin)?;
     800              : 
     801            0 :     let req = match maybe_forward(req).await {
     802            0 :         ForwardOutcome::Forwarded(res) => {
     803            0 :             return res;
     804              :         }
     805            0 :         ForwardOutcome::NotForwarded(req) => req,
     806            0 :     };
     807            0 : 
     808            0 :     let state = get_state(&req);
     809            0 :     let leader = state.service.get_leader().await.map_err(|err| {
     810            0 :         ApiError::InternalServerError(anyhow::anyhow!(
     811            0 :             "Failed to read leader from database: {err}"
     812            0 :         ))
     813            0 :     })?;
     814              : 
     815            0 :     json_response(StatusCode::OK, leader)
     816            0 : }
     817              : 
     818            0 : async fn handle_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     819            0 :     check_permissions(&req, Scope::Infra)?;
     820              : 
     821            0 :     let req = match maybe_forward(req).await {
     822            0 :         ForwardOutcome::Forwarded(res) => {
     823            0 :             return res;
     824              :         }
     825            0 :         ForwardOutcome::NotForwarded(req) => req,
     826            0 :     };
     827            0 : 
     828            0 :     let state = get_state(&req);
     829            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     830              : 
     831            0 :     state.service.start_node_drain(node_id).await?;
     832              : 
     833            0 :     json_response(StatusCode::ACCEPTED, ())
     834            0 : }
     835              : 
     836            0 : async fn handle_cancel_node_drain(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     837            0 :     check_permissions(&req, Scope::Infra)?;
     838              : 
     839            0 :     let req = match maybe_forward(req).await {
     840            0 :         ForwardOutcome::Forwarded(res) => {
     841            0 :             return res;
     842              :         }
     843            0 :         ForwardOutcome::NotForwarded(req) => req,
     844            0 :     };
     845            0 : 
     846            0 :     let state = get_state(&req);
     847            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     848              : 
     849            0 :     state.service.cancel_node_drain(node_id).await?;
     850              : 
     851            0 :     json_response(StatusCode::ACCEPTED, ())
     852            0 : }
     853              : 
     854            0 : async fn handle_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     855            0 :     check_permissions(&req, Scope::Infra)?;
     856              : 
     857            0 :     let req = match maybe_forward(req).await {
     858            0 :         ForwardOutcome::Forwarded(res) => {
     859            0 :             return res;
     860              :         }
     861            0 :         ForwardOutcome::NotForwarded(req) => req,
     862            0 :     };
     863            0 : 
     864            0 :     let state = get_state(&req);
     865            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     866              : 
     867            0 :     state.service.start_node_fill(node_id).await?;
     868              : 
     869            0 :     json_response(StatusCode::ACCEPTED, ())
     870            0 : }
     871              : 
     872            0 : async fn handle_cancel_node_fill(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     873            0 :     check_permissions(&req, Scope::Infra)?;
     874              : 
     875            0 :     let req = match maybe_forward(req).await {
     876            0 :         ForwardOutcome::Forwarded(res) => {
     877            0 :             return res;
     878              :         }
     879            0 :         ForwardOutcome::NotForwarded(req) => req,
     880            0 :     };
     881            0 : 
     882            0 :     let state = get_state(&req);
     883            0 :     let node_id: NodeId = parse_request_param(&req, "node_id")?;
     884              : 
     885            0 :     state.service.cancel_node_fill(node_id).await?;
     886              : 
     887            0 :     json_response(StatusCode::ACCEPTED, ())
     888            0 : }
     889              : 
     890            0 : async fn handle_safekeeper_list(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     891            0 :     check_permissions(&req, Scope::Infra)?;
     892              : 
     893            0 :     let req = match maybe_forward(req).await {
     894            0 :         ForwardOutcome::Forwarded(res) => {
     895            0 :             return res;
     896              :         }
     897            0 :         ForwardOutcome::NotForwarded(req) => req,
     898            0 :     };
     899            0 : 
     900            0 :     let state = get_state(&req);
     901            0 :     let safekeepers = state.service.safekeepers_list().await?;
     902            0 :     json_response(StatusCode::OK, safekeepers)
     903            0 : }
     904              : 
     905            0 : async fn handle_metadata_health_update(req: Request<Body>) -> Result<Response<Body>, ApiError> {
     906            0 :     check_permissions(&req, Scope::Scrubber)?;
     907              : 
     908            0 :     let mut req = match maybe_forward(req).await {
     909            0 :         ForwardOutcome::Forwarded(res) => {
     910            0 :             return res;
     911              :         }
     912            0 :         ForwardOutcome::NotForwarded(req) => req,
     913              :     };
     914              : 
     915            0 :     let update_req = json_request::<MetadataHealthUpdateRequest>(&mut req).await?;
     916            0 :     let state = get_state(&req);
     917            0 : 
     918            0 :     state.service.metadata_health_update(update_req).await?;
     919              : 
     920            0 :     json_response(StatusCode::OK, MetadataHealthUpdateResponse {})
     921            0 : }
     922              : 
     923            0 : async fn handle_metadata_health_list_unhealthy(
     924            0 :     req: Request<Body>,
     925            0 : ) -> Result<Response<Body>, ApiError> {
     926            0 :     check_permissions(&req, Scope::Admin)?;
     927              : 
     928            0 :     let req = match maybe_forward(req).await {
     929            0 :         ForwardOutcome::Forwarded(res) => {
     930            0 :             return res;
     931              :         }
     932            0 :         ForwardOutcome::NotForwarded(req) => req,
     933            0 :     };
     934            0 : 
     935            0 :     let state = get_state(&req);
     936            0 :     let unhealthy_tenant_shards = state.service.metadata_health_list_unhealthy().await?;
     937              : 
     938            0 :     json_response(
     939            0 :         StatusCode::OK,
     940            0 :         MetadataHealthListUnhealthyResponse {
     941            0 :             unhealthy_tenant_shards,
     942            0 :         },
     943            0 :     )
     944            0 : }
     945              : 
     946            0 : async fn handle_metadata_health_list_outdated(
     947            0 :     req: Request<Body>,
     948            0 : ) -> Result<Response<Body>, ApiError> {
     949            0 :     check_permissions(&req, Scope::Admin)?;
     950              : 
     951            0 :     let mut req = match maybe_forward(req).await {
     952            0 :         ForwardOutcome::Forwarded(res) => {
     953            0 :             return res;
     954              :         }
     955            0 :         ForwardOutcome::NotForwarded(req) => req,
     956              :     };
     957              : 
     958            0 :     let list_outdated_req = json_request::<MetadataHealthListOutdatedRequest>(&mut req).await?;
     959            0 :     let state = get_state(&req);
     960            0 :     let health_records = state
     961            0 :         .service
     962            0 :         .metadata_health_list_outdated(list_outdated_req.not_scrubbed_for)
     963            0 :         .await?;
     964              : 
     965            0 :     json_response(
     966            0 :         StatusCode::OK,
     967            0 :         MetadataHealthListOutdatedResponse { health_records },
     968            0 :     )
     969            0 : }
     970              : 
     971            0 : async fn handle_tenant_shard_split(
     972            0 :     service: Arc<Service>,
     973            0 :     req: Request<Body>,
     974            0 : ) -> Result<Response<Body>, ApiError> {
     975            0 :     check_permissions(&req, Scope::Admin)?;
     976              : 
     977            0 :     let mut req = match maybe_forward(req).await {
     978            0 :         ForwardOutcome::Forwarded(res) => {
     979            0 :             return res;
     980              :         }
     981            0 :         ForwardOutcome::NotForwarded(req) => req,
     982              :     };
     983              : 
     984            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
     985            0 :     let split_req = json_request::<TenantShardSplitRequest>(&mut req).await?;
     986              : 
     987              :     json_response(
     988              :         StatusCode::OK,
     989            0 :         service.tenant_shard_split(tenant_id, split_req).await?,
     990              :     )
     991            0 : }
     992              : 
     993            0 : async fn handle_tenant_shard_migrate(
     994            0 :     service: Arc<Service>,
     995            0 :     req: Request<Body>,
     996            0 : ) -> Result<Response<Body>, ApiError> {
     997            0 :     check_permissions(&req, Scope::Admin)?;
     998              : 
     999            0 :     let mut req = match maybe_forward(req).await {
    1000            0 :         ForwardOutcome::Forwarded(res) => {
    1001            0 :             return res;
    1002              :         }
    1003            0 :         ForwardOutcome::NotForwarded(req) => req,
    1004              :     };
    1005              : 
    1006            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
    1007            0 :     let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
    1008              :     json_response(
    1009              :         StatusCode::OK,
    1010            0 :         service
    1011            0 :             .tenant_shard_migrate(tenant_shard_id, migrate_req)
    1012            0 :             .await?,
    1013              :     )
    1014            0 : }
    1015              : 
    1016            0 : async fn handle_tenant_shard_migrate_secondary(
    1017            0 :     service: Arc<Service>,
    1018            0 :     req: Request<Body>,
    1019            0 : ) -> Result<Response<Body>, ApiError> {
    1020            0 :     check_permissions(&req, Scope::Admin)?;
    1021              : 
    1022            0 :     let mut req = match maybe_forward(req).await {
    1023            0 :         ForwardOutcome::Forwarded(res) => {
    1024            0 :             return res;
    1025              :         }
    1026            0 :         ForwardOutcome::NotForwarded(req) => req,
    1027              :     };
    1028              : 
    1029            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
    1030            0 :     let migrate_req = json_request::<TenantShardMigrateRequest>(&mut req).await?;
    1031              :     json_response(
    1032              :         StatusCode::OK,
    1033            0 :         service
    1034            0 :             .tenant_shard_migrate_secondary(tenant_shard_id, migrate_req)
    1035            0 :             .await?,
    1036              :     )
    1037            0 : }
    1038              : 
    1039            0 : async fn handle_tenant_shard_cancel_reconcile(
    1040            0 :     service: Arc<Service>,
    1041            0 :     req: Request<Body>,
    1042            0 : ) -> Result<Response<Body>, ApiError> {
    1043            0 :     check_permissions(&req, Scope::Admin)?;
    1044              : 
    1045            0 :     let req = match maybe_forward(req).await {
    1046            0 :         ForwardOutcome::Forwarded(res) => {
    1047            0 :             return res;
    1048              :         }
    1049            0 :         ForwardOutcome::NotForwarded(req) => req,
    1050              :     };
    1051              : 
    1052            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&req, "tenant_shard_id")?;
    1053              :     json_response(
    1054              :         StatusCode::OK,
    1055            0 :         service
    1056            0 :             .tenant_shard_cancel_reconcile(tenant_shard_id)
    1057            0 :             .await?,
    1058              :     )
    1059            0 : }
    1060              : 
    1061            0 : async fn handle_tenant_update_policy(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1062            0 :     check_permissions(&req, Scope::Admin)?;
    1063              : 
    1064            0 :     let mut req = match maybe_forward(req).await {
    1065            0 :         ForwardOutcome::Forwarded(res) => {
    1066            0 :             return res;
    1067              :         }
    1068            0 :         ForwardOutcome::NotForwarded(req) => req,
    1069              :     };
    1070              : 
    1071            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
    1072            0 :     let update_req = json_request::<TenantPolicyRequest>(&mut req).await?;
    1073            0 :     let state = get_state(&req);
    1074            0 : 
    1075            0 :     json_response(
    1076            0 :         StatusCode::OK,
    1077            0 :         state
    1078            0 :             .service
    1079            0 :             .tenant_update_policy(tenant_id, update_req)
    1080            0 :             .await?,
    1081              :     )
    1082            0 : }
    1083              : 
    1084            0 : async fn handle_update_preferred_azs(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1085            0 :     check_permissions(&req, Scope::Admin)?;
    1086              : 
    1087            0 :     let mut req = match maybe_forward(req).await {
    1088            0 :         ForwardOutcome::Forwarded(res) => {
    1089            0 :             return res;
    1090              :         }
    1091            0 :         ForwardOutcome::NotForwarded(req) => req,
    1092              :     };
    1093              : 
    1094            0 :     let azs_req = json_request::<ShardsPreferredAzsRequest>(&mut req).await?;
    1095            0 :     let state = get_state(&req);
    1096            0 : 
    1097            0 :     json_response(
    1098            0 :         StatusCode::OK,
    1099            0 :         state.service.update_shards_preferred_azs(azs_req).await?,
    1100              :     )
    1101            0 : }
    1102              : 
    1103            0 : async fn handle_step_down(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1104            0 :     check_permissions(&req, Scope::ControllerPeer)?;
    1105              : 
    1106            0 :     let req = match maybe_forward(req).await {
    1107            0 :         ForwardOutcome::Forwarded(res) => {
    1108            0 :             return res;
    1109              :         }
    1110            0 :         ForwardOutcome::NotForwarded(req) => req,
    1111            0 :     };
    1112            0 : 
    1113            0 :     let state = get_state(&req);
    1114            0 :     json_response(StatusCode::OK, state.service.step_down().await)
    1115            0 : }
    1116              : 
    1117            0 : async fn handle_tenant_drop(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1118            0 :     check_permissions(&req, Scope::PageServerApi)?;
    1119              : 
    1120            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
    1121              : 
    1122            0 :     let req = match maybe_forward(req).await {
    1123            0 :         ForwardOutcome::Forwarded(res) => {
    1124            0 :             return res;
    1125              :         }
    1126            0 :         ForwardOutcome::NotForwarded(req) => req,
    1127            0 :     };
    1128            0 : 
    1129            0 :     let state = get_state(&req);
    1130            0 : 
    1131            0 :     json_response(StatusCode::OK, state.service.tenant_drop(tenant_id).await?)
    1132            0 : }
    1133              : 
    1134            0 : async fn handle_tenant_import(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1135            0 :     check_permissions(&req, Scope::PageServerApi)?;
    1136              : 
    1137            0 :     let tenant_id: TenantId = parse_request_param(&req, "tenant_id")?;
    1138              : 
    1139            0 :     let req = match maybe_forward(req).await {
    1140            0 :         ForwardOutcome::Forwarded(res) => {
    1141            0 :             return res;
    1142              :         }
    1143            0 :         ForwardOutcome::NotForwarded(req) => req,
    1144            0 :     };
    1145            0 : 
    1146            0 :     let state = get_state(&req);
    1147            0 : 
    1148            0 :     json_response(
    1149            0 :         StatusCode::OK,
    1150            0 :         state.service.tenant_import(tenant_id).await?,
    1151              :     )
    1152            0 : }
    1153              : 
    1154            0 : async fn handle_tenants_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1155            0 :     check_permissions(&req, Scope::Admin)?;
    1156              : 
    1157            0 :     let req = match maybe_forward(req).await {
    1158            0 :         ForwardOutcome::Forwarded(res) => {
    1159            0 :             return res;
    1160              :         }
    1161            0 :         ForwardOutcome::NotForwarded(req) => req,
    1162            0 :     };
    1163            0 : 
    1164            0 :     let state = get_state(&req);
    1165            0 :     state.service.tenants_dump()
    1166            0 : }
    1167              : 
    1168            0 : async fn handle_scheduler_dump(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1169            0 :     check_permissions(&req, Scope::Admin)?;
    1170              : 
    1171            0 :     let req = match maybe_forward(req).await {
    1172            0 :         ForwardOutcome::Forwarded(res) => {
    1173            0 :             return res;
    1174              :         }
    1175            0 :         ForwardOutcome::NotForwarded(req) => req,
    1176            0 :     };
    1177            0 : 
    1178            0 :     let state = get_state(&req);
    1179            0 :     state.service.scheduler_dump()
    1180            0 : }
    1181              : 
    1182            0 : async fn handle_consistency_check(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1183            0 :     check_permissions(&req, Scope::Admin)?;
    1184              : 
    1185            0 :     let req = match maybe_forward(req).await {
    1186            0 :         ForwardOutcome::Forwarded(res) => {
    1187            0 :             return res;
    1188              :         }
    1189            0 :         ForwardOutcome::NotForwarded(req) => req,
    1190            0 :     };
    1191            0 : 
    1192            0 :     let state = get_state(&req);
    1193            0 : 
    1194            0 :     json_response(StatusCode::OK, state.service.consistency_check().await?)
    1195            0 : }
    1196              : 
    1197            0 : async fn handle_reconcile_all(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1198            0 :     check_permissions(&req, Scope::Admin)?;
    1199              : 
    1200            0 :     let req = match maybe_forward(req).await {
    1201            0 :         ForwardOutcome::Forwarded(res) => {
    1202            0 :             return res;
    1203              :         }
    1204            0 :         ForwardOutcome::NotForwarded(req) => req,
    1205            0 :     };
    1206            0 : 
    1207            0 :     let state = get_state(&req);
    1208            0 : 
    1209            0 :     json_response(StatusCode::OK, state.service.reconcile_all_now().await?)
    1210            0 : }
    1211              : 
    1212              : /// Status endpoint is just used for checking that our HTTP listener is up
    1213            0 : async fn handle_status(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1214            0 :     match maybe_forward(req).await {
    1215            0 :         ForwardOutcome::Forwarded(res) => {
    1216            0 :             return res;
    1217              :         }
    1218            0 :         ForwardOutcome::NotForwarded(_req) => {}
    1219            0 :     };
    1220            0 : 
    1221            0 :     json_response(StatusCode::OK, ())
    1222            0 : }
    1223              : 
    1224              : /// Readiness endpoint indicates when we're done doing startup I/O (e.g. reconciling
    1225              : /// with remote pageserver nodes).  This is intended for use as a kubernetes readiness probe.
    1226            0 : async fn handle_ready(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1227            0 :     let req = match maybe_forward(req).await {
    1228            0 :         ForwardOutcome::Forwarded(res) => {
    1229            0 :             return res;
    1230              :         }
    1231            0 :         ForwardOutcome::NotForwarded(req) => req,
    1232            0 :     };
    1233            0 : 
    1234            0 :     let state = get_state(&req);
    1235            0 :     if state.service.startup_complete.is_ready() {
    1236            0 :         json_response(StatusCode::OK, ())
    1237              :     } else {
    1238            0 :         json_response(StatusCode::SERVICE_UNAVAILABLE, ())
    1239              :     }
    1240            0 : }
    1241              : 
    1242              : impl From<ReconcileError> for ApiError {
    1243            0 :     fn from(value: ReconcileError) -> Self {
    1244            0 :         ApiError::Conflict(format!("Reconciliation error: {}", value))
    1245            0 :     }
    1246              : }
    1247              : 
    1248              : /// Return the safekeeper record by instance id, or 404.
    1249              : ///
    1250              : /// Not used by anything except manual testing.
    1251            0 : async fn handle_get_safekeeper(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1252            0 :     check_permissions(&req, Scope::Infra)?;
    1253              : 
    1254            0 :     let id = parse_request_param::<i64>(&req, "id")?;
    1255              : 
    1256            0 :     let req = match maybe_forward(req).await {
    1257            0 :         ForwardOutcome::Forwarded(res) => {
    1258            0 :             return res;
    1259              :         }
    1260            0 :         ForwardOutcome::NotForwarded(req) => req,
    1261            0 :     };
    1262            0 : 
    1263            0 :     let state = get_state(&req);
    1264              : 
    1265            0 :     let res = state.service.get_safekeeper(id).await;
    1266              : 
    1267            0 :     match res {
    1268            0 :         Ok(b) => json_response(StatusCode::OK, b),
    1269              :         Err(crate::persistence::DatabaseError::Query(diesel::result::Error::NotFound)) => {
    1270            0 :             Err(ApiError::NotFound("unknown instance id".into()))
    1271              :         }
    1272            0 :         Err(other) => Err(other.into()),
    1273              :     }
    1274            0 : }
    1275              : 
    1276              : /// Used as part of deployment scripts.
    1277              : ///
    1278              : /// Assumes information is only relayed to storage controller after first selecting an unique id on
    1279              : /// control plane database, which means we have an id field in the request and payload.
    1280            0 : async fn handle_upsert_safekeeper(mut req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1281            0 :     check_permissions(&req, Scope::Infra)?;
    1282              : 
    1283            0 :     let body = json_request::<SafekeeperUpsert>(&mut req).await?;
    1284            0 :     let id = parse_request_param::<i64>(&req, "id")?;
    1285              : 
    1286            0 :     if id != body.id {
    1287              :         // it should be repeated
    1288            0 :         return Err(ApiError::BadRequest(anyhow::anyhow!(
    1289            0 :             "id mismatch: url={id:?}, body={:?}",
    1290            0 :             body.id
    1291            0 :         )));
    1292            0 :     }
    1293              : 
    1294            0 :     let req = match maybe_forward(req).await {
    1295            0 :         ForwardOutcome::Forwarded(res) => {
    1296            0 :             return res;
    1297              :         }
    1298            0 :         ForwardOutcome::NotForwarded(req) => req,
    1299            0 :     };
    1300            0 : 
    1301            0 :     let state = get_state(&req);
    1302            0 : 
    1303            0 :     state.service.upsert_safekeeper(body).await?;
    1304              : 
    1305            0 :     Ok(Response::builder()
    1306            0 :         .status(StatusCode::NO_CONTENT)
    1307            0 :         .body(Body::empty())
    1308            0 :         .unwrap())
    1309            0 : }
    1310              : 
    1311              : /// Sets the scheduling policy of the specified safekeeper
    1312            0 : async fn handle_safekeeper_scheduling_policy(
    1313            0 :     mut req: Request<Body>,
    1314            0 : ) -> Result<Response<Body>, ApiError> {
    1315            0 :     check_permissions(&req, Scope::Admin)?;
    1316              : 
    1317            0 :     let body = json_request::<SafekeeperSchedulingPolicyRequest>(&mut req).await?;
    1318            0 :     let id = parse_request_param::<i64>(&req, "id")?;
    1319              : 
    1320            0 :     let req = match maybe_forward(req).await {
    1321            0 :         ForwardOutcome::Forwarded(res) => {
    1322            0 :             return res;
    1323              :         }
    1324            0 :         ForwardOutcome::NotForwarded(req) => req,
    1325            0 :     };
    1326            0 : 
    1327            0 :     let state = get_state(&req);
    1328            0 : 
    1329            0 :     state
    1330            0 :         .service
    1331            0 :         .set_safekeeper_scheduling_policy(id, body.scheduling_policy)
    1332            0 :         .await?;
    1333              : 
    1334            0 :     Ok(Response::builder()
    1335            0 :         .status(StatusCode::NO_CONTENT)
    1336            0 :         .body(Body::empty())
    1337            0 :         .unwrap())
    1338            0 : }
    1339              : 
    1340              : /// Common wrapper for request handlers that call into Service and will operate on tenants: they must only
    1341              : /// be allowed to run if Service has finished its initial reconciliation.
    1342            0 : async fn tenant_service_handler<R, H>(
    1343            0 :     request: Request<Body>,
    1344            0 :     handler: H,
    1345            0 :     request_name: RequestName,
    1346            0 : ) -> R::Output
    1347            0 : where
    1348            0 :     R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
    1349            0 :     H: FnOnce(Arc<Service>, Request<Body>) -> R + Send + Sync + 'static,
    1350            0 : {
    1351            0 :     let state = get_state(&request);
    1352            0 :     let service = state.service.clone();
    1353            0 : 
    1354            0 :     let startup_complete = service.startup_complete.clone();
    1355            0 :     if tokio::time::timeout(STARTUP_RECONCILE_TIMEOUT, startup_complete.wait())
    1356            0 :         .await
    1357            0 :         .is_err()
    1358              :     {
    1359              :         // This shouldn't happen: it is the responsibilty of [`Service::startup_reconcile`] to use appropriate
    1360              :         // timeouts around its remote calls, to bound its runtime.
    1361            0 :         return Err(ApiError::Timeout(
    1362            0 :             "Timed out waiting for service readiness".into(),
    1363            0 :         ));
    1364            0 :     }
    1365            0 : 
    1366            0 :     named_request_span(
    1367            0 :         request,
    1368            0 :         |request| async move { handler(service, request).await },
    1369            0 :         request_name,
    1370            0 :     )
    1371            0 :     .await
    1372            0 : }
    1373              : 
    1374              : /// Check if the required scope is held in the request's token, or if the request has
    1375              : /// a token with 'admin' scope then always permit it.
    1376            0 : fn check_permissions(request: &Request<Body>, required_scope: Scope) -> Result<(), ApiError> {
    1377            0 :     check_permission_with(request, |claims| {
    1378            0 :         match crate::auth::check_permission(claims, required_scope) {
    1379            0 :             Err(e) => match crate::auth::check_permission(claims, Scope::Admin) {
    1380            0 :                 Ok(()) => Ok(()),
    1381            0 :                 Err(_) => Err(e),
    1382              :             },
    1383            0 :             Ok(()) => Ok(()),
    1384              :         }
    1385            0 :     })
    1386            0 : }
    1387              : 
    1388              : #[derive(Clone, Debug)]
    1389              : struct RequestMeta {
    1390              :     method: hyper::http::Method,
    1391              :     at: Instant,
    1392              : }
    1393              : 
    1394            0 : pub fn prologue_leadership_status_check_middleware<
    1395            0 :     B: hyper::body::HttpBody + Send + Sync + 'static,
    1396            0 : >() -> Middleware<B, ApiError> {
    1397            0 :     Middleware::pre(move |req| async move {
    1398            0 :         let state = get_state(&req);
    1399            0 :         let leadership_status = state.service.get_leadership_status();
    1400              : 
    1401              :         enum AllowedRoutes<'a> {
    1402              :             All,
    1403              :             Some(Vec<&'a str>),
    1404              :         }
    1405              : 
    1406            0 :         let allowed_routes = match leadership_status {
    1407            0 :             LeadershipStatus::Leader => AllowedRoutes::All,
    1408            0 :             LeadershipStatus::SteppedDown => AllowedRoutes::All,
    1409              :             LeadershipStatus::Candidate => {
    1410            0 :                 AllowedRoutes::Some(["/ready", "/status", "/metrics"].to_vec())
    1411              :             }
    1412              :         };
    1413              : 
    1414            0 :         let uri = req.uri().to_string();
    1415            0 :         match allowed_routes {
    1416            0 :             AllowedRoutes::All => Ok(req),
    1417            0 :             AllowedRoutes::Some(allowed) if allowed.contains(&uri.as_str()) => Ok(req),
    1418              :             _ => {
    1419            0 :                 tracing::info!(
    1420            0 :                     "Request {} not allowed due to current leadership state",
    1421            0 :                     req.uri()
    1422              :                 );
    1423              : 
    1424            0 :                 Err(ApiError::ResourceUnavailable(
    1425            0 :                     format!("Current leadership status is {leadership_status}").into(),
    1426            0 :                 ))
    1427              :             }
    1428              :         }
    1429            0 :     })
    1430            0 : }
    1431              : 
    1432            0 : fn prologue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
    1433            0 : ) -> Middleware<B, ApiError> {
    1434            0 :     Middleware::pre(move |req| async move {
    1435            0 :         let meta = RequestMeta {
    1436            0 :             method: req.method().clone(),
    1437            0 :             at: Instant::now(),
    1438            0 :         };
    1439            0 : 
    1440            0 :         req.set_context(meta);
    1441            0 : 
    1442            0 :         Ok(req)
    1443            0 :     })
    1444            0 : }
    1445              : 
    1446            0 : fn epilogue_metrics_middleware<B: hyper::body::HttpBody + Send + Sync + 'static>(
    1447            0 : ) -> Middleware<B, ApiError> {
    1448            0 :     Middleware::post_with_info(move |resp, req_info| async move {
    1449            0 :         let request_name = match req_info.context::<RequestName>() {
    1450            0 :             Some(name) => name,
    1451              :             None => {
    1452            0 :                 return Ok(resp);
    1453              :             }
    1454              :         };
    1455              : 
    1456            0 :         if let Some(meta) = req_info.context::<RequestMeta>() {
    1457            0 :             let status = &crate::metrics::METRICS_REGISTRY
    1458            0 :                 .metrics_group
    1459            0 :                 .storage_controller_http_request_status;
    1460            0 :             let latency = &crate::metrics::METRICS_REGISTRY
    1461            0 :                 .metrics_group
    1462            0 :                 .storage_controller_http_request_latency;
    1463            0 : 
    1464            0 :             status.inc(HttpRequestStatusLabelGroup {
    1465            0 :                 path: request_name.0,
    1466            0 :                 method: meta.method.clone().into(),
    1467            0 :                 status: crate::metrics::StatusCode(resp.status()),
    1468            0 :             });
    1469            0 : 
    1470            0 :             latency.observe(
    1471            0 :                 HttpRequestLatencyLabelGroup {
    1472            0 :                     path: request_name.0,
    1473            0 :                     method: meta.method.into(),
    1474            0 :                 },
    1475            0 :                 meta.at.elapsed().as_secs_f64(),
    1476            0 :             );
    1477            0 :         }
    1478            0 :         Ok(resp)
    1479            0 :     })
    1480            0 : }
    1481              : 
    1482            0 : pub async fn measured_metrics_handler(req: Request<Body>) -> Result<Response<Body>, ApiError> {
    1483              :     pub const TEXT_FORMAT: &str = "text/plain; version=0.0.4";
    1484              : 
    1485            0 :     let req = match maybe_forward(req).await {
    1486            0 :         ForwardOutcome::Forwarded(res) => {
    1487            0 :             return res;
    1488              :         }
    1489            0 :         ForwardOutcome::NotForwarded(req) => req,
    1490            0 :     };
    1491            0 : 
    1492            0 :     let state = get_state(&req);
    1493            0 :     let payload = crate::metrics::METRICS_REGISTRY.encode(&state.neon_metrics);
    1494            0 :     let response = Response::builder()
    1495            0 :         .status(200)
    1496            0 :         .header(CONTENT_TYPE, TEXT_FORMAT)
    1497            0 :         .body(payload.into())
    1498            0 :         .unwrap();
    1499            0 : 
    1500            0 :     Ok(response)
    1501            0 : }
    1502              : 
    1503              : #[derive(Clone)]
    1504              : struct RequestName(&'static str);
    1505              : 
    1506            0 : async fn named_request_span<R, H>(
    1507            0 :     request: Request<Body>,
    1508            0 :     handler: H,
    1509            0 :     name: RequestName,
    1510            0 : ) -> R::Output
    1511            0 : where
    1512            0 :     R: Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
    1513            0 :     H: FnOnce(Request<Body>) -> R + Send + Sync + 'static,
    1514            0 : {
    1515            0 :     request.set_context(name);
    1516            0 :     request_span(request, handler).await
    1517            0 : }
    1518              : 
    1519              : enum ForwardOutcome {
    1520              :     Forwarded(Result<Response<Body>, ApiError>),
    1521              :     NotForwarded(Request<Body>),
    1522              : }
    1523              : 
    1524              : /// Potentially forward the request to the current storage controler leader.
    1525              : /// More specifically we forward when:
    1526              : /// 1. Request is not one of ["/control/v1/step_down", "/status", "/ready", "/metrics"]
    1527              : /// 2. Current instance is in [`LeadershipStatus::SteppedDown`] state
    1528              : /// 3. There is a leader in the database to forward to
    1529              : /// 4. Leader from step (3) is not the current instance
    1530              : ///
    1531              : /// Why forward?
    1532              : /// It turns out that we can't rely on external orchestration to promptly route trafic to the
    1533              : /// new leader. This is downtime inducing. Forwarding provides a safe way out.
    1534              : ///
    1535              : /// Why is it safe?
    1536              : /// If a storcon instance is persisted in the database, then we know that it is the current leader.
    1537              : /// There's one exception: time between handling step-down request and the new leader updating the
    1538              : /// database.
    1539              : ///
    1540              : /// Let's treat the happy case first. The stepped down node does not produce any side effects,
    1541              : /// since all request handling happens on the leader.
    1542              : ///
    1543              : /// As for the edge case, we are guaranteed to always have a maximum of two running instances.
    1544              : /// Hence, if we are in the edge case scenario the leader persisted in the database is the
    1545              : /// stepped down instance that received the request. Condition (4) above covers this scenario.
    1546            0 : async fn maybe_forward(req: Request<Body>) -> ForwardOutcome {
    1547              :     const NOT_FOR_FORWARD: [&str; 4] = ["/control/v1/step_down", "/status", "/ready", "/metrics"];
    1548              : 
    1549            0 :     let uri = req.uri().to_string();
    1550            0 :     let uri_for_forward = !NOT_FOR_FORWARD.contains(&uri.as_str());
    1551            0 : 
    1552            0 :     // Fast return before trying to take any Service locks, if we will never forward anyway
    1553            0 :     if !uri_for_forward {
    1554            0 :         return ForwardOutcome::NotForwarded(req);
    1555            0 :     }
    1556            0 : 
    1557            0 :     let state = get_state(&req);
    1558            0 :     let leadership_status = state.service.get_leadership_status();
    1559            0 : 
    1560            0 :     if leadership_status != LeadershipStatus::SteppedDown {
    1561            0 :         return ForwardOutcome::NotForwarded(req);
    1562            0 :     }
    1563              : 
    1564            0 :     let leader = state.service.get_leader().await;
    1565            0 :     let leader = {
    1566            0 :         match leader {
    1567            0 :             Ok(Some(leader)) => leader,
    1568              :             Ok(None) => {
    1569            0 :                 return ForwardOutcome::Forwarded(Err(ApiError::ResourceUnavailable(
    1570            0 :                     "No leader to forward to while in stepped down state".into(),
    1571            0 :                 )));
    1572              :             }
    1573            0 :             Err(err) => {
    1574            0 :                 return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(
    1575            0 :                     anyhow::anyhow!(
    1576            0 :                         "Failed to get leader for forwarding while in stepped down state: {err}"
    1577            0 :                     ),
    1578            0 :                 )));
    1579              :             }
    1580              :         }
    1581              :     };
    1582              : 
    1583            0 :     let cfg = state.service.get_config();
    1584            0 :     if let Some(ref self_addr) = cfg.address_for_peers {
    1585            0 :         let leader_addr = match Uri::from_str(leader.address.as_str()) {
    1586            0 :             Ok(uri) => uri,
    1587            0 :             Err(err) => {
    1588            0 :                 return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(
    1589            0 :                     anyhow::anyhow!(
    1590            0 :                     "Failed to parse leader uri for forwarding while in stepped down state: {err}"
    1591            0 :                 ),
    1592            0 :                 )));
    1593              :             }
    1594              :         };
    1595              : 
    1596            0 :         if *self_addr == leader_addr {
    1597            0 :             return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
    1598            0 :                 "Leader is stepped down instance"
    1599            0 :             ))));
    1600            0 :         }
    1601            0 :     }
    1602              : 
    1603            0 :     tracing::info!("Forwarding {} to leader at {}", uri, leader.address);
    1604              : 
    1605              :     // Use [`RECONCILE_TIMEOUT`] as the max amount of time a request should block for and
    1606              :     // include some leeway to get the timeout for proxied requests.
    1607              :     const PROXIED_REQUEST_TIMEOUT: Duration = Duration::from_secs(RECONCILE_TIMEOUT.as_secs() + 10);
    1608            0 :     let client = reqwest::ClientBuilder::new()
    1609            0 :         .timeout(PROXIED_REQUEST_TIMEOUT)
    1610            0 :         .build();
    1611            0 :     let client = match client {
    1612            0 :         Ok(client) => client,
    1613            0 :         Err(err) => {
    1614            0 :             return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
    1615            0 :                 "Failed to build leader client for forwarding while in stepped down state: {err}"
    1616            0 :             ))));
    1617              :         }
    1618              :     };
    1619              : 
    1620            0 :     let request: reqwest::Request = match convert_request(req, &client, leader.address).await {
    1621            0 :         Ok(r) => r,
    1622            0 :         Err(err) => {
    1623            0 :             return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
    1624            0 :                 "Failed to convert request for forwarding while in stepped down state: {err}"
    1625            0 :             ))));
    1626              :         }
    1627              :     };
    1628              : 
    1629            0 :     let response = match client.execute(request).await {
    1630            0 :         Ok(r) => r,
    1631            0 :         Err(err) => {
    1632            0 :             return ForwardOutcome::Forwarded(Err(ApiError::InternalServerError(anyhow::anyhow!(
    1633            0 :                 "Failed to forward while in stepped down state: {err}"
    1634            0 :             ))));
    1635              :         }
    1636              :     };
    1637              : 
    1638            0 :     ForwardOutcome::Forwarded(convert_response(response).await)
    1639            0 : }
    1640              : 
    1641              : /// Convert a [`reqwest::Response`] to a [hyper::Response`] by passing through
    1642              : /// a stable representation (string, bytes or integer)
    1643              : ///
    1644              : /// Ideally, we would not have to do this since both types use the http crate
    1645              : /// under the hood. However, they use different versions of the crate and keeping
    1646              : /// second order dependencies in sync is difficult.
    1647            0 : async fn convert_response(resp: reqwest::Response) -> Result<hyper::Response<Body>, ApiError> {
    1648              :     use std::str::FromStr;
    1649              : 
    1650            0 :     let mut builder = hyper::Response::builder().status(resp.status().as_u16());
    1651            0 :     for (key, value) in resp.headers().into_iter() {
    1652            0 :         let key = hyper::header::HeaderName::from_str(key.as_str()).map_err(|err| {
    1653            0 :             ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
    1654            0 :         })?;
    1655              : 
    1656            0 :         let value = hyper::header::HeaderValue::from_bytes(value.as_bytes()).map_err(|err| {
    1657            0 :             ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
    1658            0 :         })?;
    1659              : 
    1660            0 :         builder = builder.header(key, value);
    1661              :     }
    1662              : 
    1663            0 :     let body = http::Body::wrap_stream(resp.bytes_stream());
    1664            0 : 
    1665            0 :     builder.body(body).map_err(|err| {
    1666            0 :         ApiError::InternalServerError(anyhow::anyhow!("Response conversion failed: {err}"))
    1667            0 :     })
    1668            0 : }
    1669              : 
    1670              : /// Convert a [`reqwest::Request`] to a [hyper::Request`] by passing through
    1671              : /// a stable representation (string, bytes or integer)
    1672              : ///
    1673              : /// See [`convert_response`] for why we are doing it this way.
    1674            0 : async fn convert_request(
    1675            0 :     req: hyper::Request<Body>,
    1676            0 :     client: &reqwest::Client,
    1677            0 :     to_address: String,
    1678            0 : ) -> Result<reqwest::Request, ApiError> {
    1679              :     use std::str::FromStr;
    1680              : 
    1681            0 :     let (parts, body) = req.into_parts();
    1682            0 :     let method = reqwest::Method::from_str(parts.method.as_str()).map_err(|err| {
    1683            0 :         ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1684            0 :     })?;
    1685              : 
    1686            0 :     let path_and_query = parts.uri.path_and_query().ok_or_else(|| {
    1687            0 :         ApiError::InternalServerError(anyhow::anyhow!(
    1688            0 :             "Request conversion failed: no path and query"
    1689            0 :         ))
    1690            0 :     })?;
    1691              : 
    1692            0 :     let uri = reqwest::Url::from_str(
    1693            0 :         format!(
    1694            0 :             "{}{}",
    1695            0 :             to_address.trim_end_matches("/"),
    1696            0 :             path_and_query.as_str()
    1697            0 :         )
    1698            0 :         .as_str(),
    1699            0 :     )
    1700            0 :     .map_err(|err| {
    1701            0 :         ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1702            0 :     })?;
    1703              : 
    1704            0 :     let mut headers = reqwest::header::HeaderMap::new();
    1705            0 :     for (key, value) in parts.headers.into_iter() {
    1706            0 :         let key = match key {
    1707            0 :             Some(k) => k,
    1708              :             None => {
    1709            0 :                 continue;
    1710              :             }
    1711              :         };
    1712              : 
    1713            0 :         let key = reqwest::header::HeaderName::from_str(key.as_str()).map_err(|err| {
    1714            0 :             ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1715            0 :         })?;
    1716              : 
    1717            0 :         let value = reqwest::header::HeaderValue::from_bytes(value.as_bytes()).map_err(|err| {
    1718            0 :             ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1719            0 :         })?;
    1720              : 
    1721            0 :         headers.insert(key, value);
    1722              :     }
    1723              : 
    1724            0 :     let body = hyper::body::to_bytes(body).await.map_err(|err| {
    1725            0 :         ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1726            0 :     })?;
    1727              : 
    1728            0 :     client
    1729            0 :         .request(method, uri)
    1730            0 :         .headers(headers)
    1731            0 :         .body(body)
    1732            0 :         .build()
    1733            0 :         .map_err(|err| {
    1734            0 :             ApiError::InternalServerError(anyhow::anyhow!("Request conversion failed: {err}"))
    1735            0 :         })
    1736            0 : }
    1737              : 
    1738            0 : pub fn make_router(
    1739            0 :     service: Arc<Service>,
    1740            0 :     auth: Option<Arc<SwappableJwtAuth>>,
    1741            0 :     build_info: BuildInfo,
    1742            0 : ) -> RouterBuilder<hyper::Body, ApiError> {
    1743            0 :     let mut router = endpoint::make_router()
    1744            0 :         .middleware(prologue_leadership_status_check_middleware())
    1745            0 :         .middleware(prologue_metrics_middleware())
    1746            0 :         .middleware(epilogue_metrics_middleware());
    1747            0 :     if auth.is_some() {
    1748            0 :         router = router.middleware(auth_middleware(|request| {
    1749            0 :             let state = get_state(request);
    1750            0 :             if state.allowlist_routes.contains(request.uri()) {
    1751            0 :                 None
    1752              :             } else {
    1753            0 :                 state.auth.as_deref()
    1754              :             }
    1755            0 :         }));
    1756            0 :     }
    1757              : 
    1758            0 :     router
    1759            0 :         .data(Arc::new(HttpState::new(service, auth, build_info)))
    1760            0 :         .get("/metrics", |r| {
    1761            0 :             named_request_span(r, measured_metrics_handler, RequestName("metrics"))
    1762            0 :         })
    1763            0 :         // Non-prefixed generic endpoints (status, metrics)
    1764            0 :         .get("/status", |r| {
    1765            0 :             named_request_span(r, handle_status, RequestName("status"))
    1766            0 :         })
    1767            0 :         .get("/ready", |r| {
    1768            0 :             named_request_span(r, handle_ready, RequestName("ready"))
    1769            0 :         })
    1770            0 :         // Upcalls for the pageserver: point the pageserver's `control_plane_api` config to this prefix
    1771            0 :         .post("/upcall/v1/re-attach", |r| {
    1772            0 :             named_request_span(r, handle_re_attach, RequestName("upcall_v1_reattach"))
    1773            0 :         })
    1774            0 :         .post("/upcall/v1/validate", |r| {
    1775            0 :             named_request_span(r, handle_validate, RequestName("upcall_v1_validate"))
    1776            0 :         })
    1777            0 :         // Test/dev/debug endpoints
    1778            0 :         .post("/debug/v1/attach-hook", |r| {
    1779            0 :             named_request_span(r, handle_attach_hook, RequestName("debug_v1_attach_hook"))
    1780            0 :         })
    1781            0 :         .post("/debug/v1/inspect", |r| {
    1782            0 :             named_request_span(r, handle_inspect, RequestName("debug_v1_inspect"))
    1783            0 :         })
    1784            0 :         .post("/debug/v1/tenant/:tenant_id/drop", |r| {
    1785            0 :             named_request_span(r, handle_tenant_drop, RequestName("debug_v1_tenant_drop"))
    1786            0 :         })
    1787            0 :         .post("/debug/v1/node/:node_id/drop", |r| {
    1788            0 :             named_request_span(r, handle_node_drop, RequestName("debug_v1_node_drop"))
    1789            0 :         })
    1790            0 :         .post("/debug/v1/tenant/:tenant_id/import", |r| {
    1791            0 :             named_request_span(
    1792            0 :                 r,
    1793            0 :                 handle_tenant_import,
    1794            0 :                 RequestName("debug_v1_tenant_import"),
    1795            0 :             )
    1796            0 :         })
    1797            0 :         .get("/debug/v1/tenant", |r| {
    1798            0 :             named_request_span(r, handle_tenants_dump, RequestName("debug_v1_tenant"))
    1799            0 :         })
    1800            0 :         .get("/debug/v1/tenant/:tenant_id/locate", |r| {
    1801            0 :             tenant_service_handler(
    1802            0 :                 r,
    1803            0 :                 handle_tenant_locate,
    1804            0 :                 RequestName("debug_v1_tenant_locate"),
    1805            0 :             )
    1806            0 :         })
    1807            0 :         .get("/debug/v1/scheduler", |r| {
    1808            0 :             named_request_span(r, handle_scheduler_dump, RequestName("debug_v1_scheduler"))
    1809            0 :         })
    1810            0 :         .post("/debug/v1/consistency_check", |r| {
    1811            0 :             named_request_span(
    1812            0 :                 r,
    1813            0 :                 handle_consistency_check,
    1814            0 :                 RequestName("debug_v1_consistency_check"),
    1815            0 :             )
    1816            0 :         })
    1817            0 :         .post("/debug/v1/reconcile_all", |r| {
    1818            0 :             request_span(r, handle_reconcile_all)
    1819            0 :         })
    1820            0 :         .put("/debug/v1/failpoints", |r| {
    1821            0 :             request_span(r, |r| failpoints_handler(r, CancellationToken::new()))
    1822            0 :         })
    1823            0 :         // Node operations
    1824            0 :         .post("/control/v1/node", |r| {
    1825            0 :             named_request_span(r, handle_node_register, RequestName("control_v1_node"))
    1826            0 :         })
    1827            0 :         .delete("/control/v1/node/:node_id", |r| {
    1828            0 :             named_request_span(r, handle_node_delete, RequestName("control_v1_node_delete"))
    1829            0 :         })
    1830            0 :         .get("/control/v1/node", |r| {
    1831            0 :             named_request_span(r, handle_node_list, RequestName("control_v1_node"))
    1832            0 :         })
    1833            0 :         .put("/control/v1/node/:node_id/config", |r| {
    1834            0 :             named_request_span(
    1835            0 :                 r,
    1836            0 :                 handle_node_configure,
    1837            0 :                 RequestName("control_v1_node_config"),
    1838            0 :             )
    1839            0 :         })
    1840            0 :         .get("/control/v1/node/:node_id", |r| {
    1841            0 :             named_request_span(r, handle_node_status, RequestName("control_v1_node_status"))
    1842            0 :         })
    1843            0 :         .get("/control/v1/node/:node_id/shards", |r| {
    1844            0 :             named_request_span(
    1845            0 :                 r,
    1846            0 :                 handle_node_shards,
    1847            0 :                 RequestName("control_v1_node_describe"),
    1848            0 :             )
    1849            0 :         })
    1850            0 :         .get("/control/v1/leader", |r| {
    1851            0 :             named_request_span(r, handle_get_leader, RequestName("control_v1_get_leader"))
    1852            0 :         })
    1853            0 :         .put("/control/v1/node/:node_id/drain", |r| {
    1854            0 :             named_request_span(r, handle_node_drain, RequestName("control_v1_node_drain"))
    1855            0 :         })
    1856            0 :         .delete("/control/v1/node/:node_id/drain", |r| {
    1857            0 :             named_request_span(
    1858            0 :                 r,
    1859            0 :                 handle_cancel_node_drain,
    1860            0 :                 RequestName("control_v1_cancel_node_drain"),
    1861            0 :             )
    1862            0 :         })
    1863            0 :         .put("/control/v1/node/:node_id/fill", |r| {
    1864            0 :             named_request_span(r, handle_node_fill, RequestName("control_v1_node_fill"))
    1865            0 :         })
    1866            0 :         .delete("/control/v1/node/:node_id/fill", |r| {
    1867            0 :             named_request_span(
    1868            0 :                 r,
    1869            0 :                 handle_cancel_node_fill,
    1870            0 :                 RequestName("control_v1_cancel_node_fill"),
    1871            0 :             )
    1872            0 :         })
    1873            0 :         // Metadata health operations
    1874            0 :         .post("/control/v1/metadata_health/update", |r| {
    1875            0 :             named_request_span(
    1876            0 :                 r,
    1877            0 :                 handle_metadata_health_update,
    1878            0 :                 RequestName("control_v1_metadata_health_update"),
    1879            0 :             )
    1880            0 :         })
    1881            0 :         .get("/control/v1/metadata_health/unhealthy", |r| {
    1882            0 :             named_request_span(
    1883            0 :                 r,
    1884            0 :                 handle_metadata_health_list_unhealthy,
    1885            0 :                 RequestName("control_v1_metadata_health_list_unhealthy"),
    1886            0 :             )
    1887            0 :         })
    1888            0 :         .post("/control/v1/metadata_health/outdated", |r| {
    1889            0 :             named_request_span(
    1890            0 :                 r,
    1891            0 :                 handle_metadata_health_list_outdated,
    1892            0 :                 RequestName("control_v1_metadata_health_list_outdated"),
    1893            0 :             )
    1894            0 :         })
    1895            0 :         // Safekeepers
    1896            0 :         .get("/control/v1/safekeeper", |r| {
    1897            0 :             named_request_span(
    1898            0 :                 r,
    1899            0 :                 handle_safekeeper_list,
    1900            0 :                 RequestName("control_v1_safekeeper_list"),
    1901            0 :             )
    1902            0 :         })
    1903            0 :         .get("/control/v1/safekeeper/:id", |r| {
    1904            0 :             named_request_span(r, handle_get_safekeeper, RequestName("v1_safekeeper"))
    1905            0 :         })
    1906            0 :         .post("/control/v1/safekeeper/:id", |r| {
    1907            0 :             // id is in the body
    1908            0 :             named_request_span(
    1909            0 :                 r,
    1910            0 :                 handle_upsert_safekeeper,
    1911            0 :                 RequestName("v1_safekeeper_post"),
    1912            0 :             )
    1913            0 :         })
    1914            0 :         .post("/control/v1/safekeeper/:id/scheduling_policy", |r| {
    1915            0 :             named_request_span(
    1916            0 :                 r,
    1917            0 :                 handle_safekeeper_scheduling_policy,
    1918            0 :                 RequestName("v1_safekeeper_status"),
    1919            0 :             )
    1920            0 :         })
    1921            0 :         // Tenant Shard operations
    1922            0 :         .put("/control/v1/tenant/:tenant_shard_id/migrate", |r| {
    1923            0 :             tenant_service_handler(
    1924            0 :                 r,
    1925            0 :                 handle_tenant_shard_migrate,
    1926            0 :                 RequestName("control_v1_tenant_migrate"),
    1927            0 :             )
    1928            0 :         })
    1929            0 :         .put(
    1930            0 :             "/control/v1/tenant/:tenant_shard_id/migrate_secondary",
    1931            0 :             |r| {
    1932            0 :                 tenant_service_handler(
    1933            0 :                     r,
    1934            0 :                     handle_tenant_shard_migrate_secondary,
    1935            0 :                     RequestName("control_v1_tenant_migrate_secondary"),
    1936            0 :                 )
    1937            0 :             },
    1938            0 :         )
    1939            0 :         .put(
    1940            0 :             "/control/v1/tenant/:tenant_shard_id/cancel_reconcile",
    1941            0 :             |r| {
    1942            0 :                 tenant_service_handler(
    1943            0 :                     r,
    1944            0 :                     handle_tenant_shard_cancel_reconcile,
    1945            0 :                     RequestName("control_v1_tenant_cancel_reconcile"),
    1946            0 :                 )
    1947            0 :             },
    1948            0 :         )
    1949            0 :         .put("/control/v1/tenant/:tenant_id/shard_split", |r| {
    1950            0 :             tenant_service_handler(
    1951            0 :                 r,
    1952            0 :                 handle_tenant_shard_split,
    1953            0 :                 RequestName("control_v1_tenant_shard_split"),
    1954            0 :             )
    1955            0 :         })
    1956            0 :         .get("/control/v1/tenant/:tenant_id", |r| {
    1957            0 :             tenant_service_handler(
    1958            0 :                 r,
    1959            0 :                 handle_tenant_describe,
    1960            0 :                 RequestName("control_v1_tenant_describe"),
    1961            0 :             )
    1962            0 :         })
    1963            0 :         .get("/control/v1/tenant", |r| {
    1964            0 :             tenant_service_handler(r, handle_tenant_list, RequestName("control_v1_tenant_list"))
    1965            0 :         })
    1966            0 :         .put("/control/v1/tenant/:tenant_id/policy", |r| {
    1967            0 :             named_request_span(
    1968            0 :                 r,
    1969            0 :                 handle_tenant_update_policy,
    1970            0 :                 RequestName("control_v1_tenant_policy"),
    1971            0 :             )
    1972            0 :         })
    1973            0 :         .put("/control/v1/preferred_azs", |r| {
    1974            0 :             named_request_span(
    1975            0 :                 r,
    1976            0 :                 handle_update_preferred_azs,
    1977            0 :                 RequestName("control_v1_preferred_azs"),
    1978            0 :             )
    1979            0 :         })
    1980            0 :         .put("/control/v1/step_down", |r| {
    1981            0 :             named_request_span(r, handle_step_down, RequestName("control_v1_step_down"))
    1982            0 :         })
    1983            0 :         // Tenant operations
    1984            0 :         // The ^/v1/ endpoints act as a "Virtual Pageserver", enabling shard-naive clients to call into
    1985            0 :         // this service to manage tenants that actually consist of many tenant shards, as if they are a single entity.
    1986            0 :         .post("/v1/tenant", |r| {
    1987            0 :             tenant_service_handler(r, handle_tenant_create, RequestName("v1_tenant"))
    1988            0 :         })
    1989            0 :         .delete("/v1/tenant/:tenant_id", |r| {
    1990            0 :             tenant_service_handler(r, handle_tenant_delete, RequestName("v1_tenant"))
    1991            0 :         })
    1992            0 :         .patch("/v1/tenant/config", |r| {
    1993            0 :             tenant_service_handler(
    1994            0 :                 r,
    1995            0 :                 handle_tenant_config_patch,
    1996            0 :                 RequestName("v1_tenant_config"),
    1997            0 :             )
    1998            0 :         })
    1999            0 :         .put("/v1/tenant/config", |r| {
    2000            0 :             tenant_service_handler(r, handle_tenant_config_set, RequestName("v1_tenant_config"))
    2001            0 :         })
    2002            0 :         .get("/v1/tenant/:tenant_id/config", |r| {
    2003            0 :             tenant_service_handler(r, handle_tenant_config_get, RequestName("v1_tenant_config"))
    2004            0 :         })
    2005            0 :         .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
    2006            0 :             tenant_service_handler(
    2007            0 :                 r,
    2008            0 :                 handle_tenant_location_config,
    2009            0 :                 RequestName("v1_tenant_location_config"),
    2010            0 :             )
    2011            0 :         })
    2012            0 :         .put("/v1/tenant/:tenant_id/time_travel_remote_storage", |r| {
    2013            0 :             tenant_service_handler(
    2014            0 :                 r,
    2015            0 :                 handle_tenant_time_travel_remote_storage,
    2016            0 :                 RequestName("v1_tenant_time_travel_remote_storage"),
    2017            0 :             )
    2018            0 :         })
    2019            0 :         .post("/v1/tenant/:tenant_id/secondary/download", |r| {
    2020            0 :             tenant_service_handler(
    2021            0 :                 r,
    2022            0 :                 handle_tenant_secondary_download,
    2023            0 :                 RequestName("v1_tenant_secondary_download"),
    2024            0 :             )
    2025            0 :         })
    2026            0 :         // Timeline operations
    2027            0 :         .delete("/v1/tenant/:tenant_id/timeline/:timeline_id", |r| {
    2028            0 :             tenant_service_handler(
    2029            0 :                 r,
    2030            0 :                 handle_tenant_timeline_delete,
    2031            0 :                 RequestName("v1_tenant_timeline"),
    2032            0 :             )
    2033            0 :         })
    2034            0 :         .post("/v1/tenant/:tenant_id/timeline", |r| {
    2035            0 :             tenant_service_handler(
    2036            0 :                 r,
    2037            0 :                 handle_tenant_timeline_create,
    2038            0 :                 RequestName("v1_tenant_timeline"),
    2039            0 :             )
    2040            0 :         })
    2041            0 :         .put(
    2042            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/archival_config",
    2043            0 :             |r| {
    2044            0 :                 tenant_service_handler(
    2045            0 :                     r,
    2046            0 :                     handle_tenant_timeline_archival_config,
    2047            0 :                     RequestName("v1_tenant_timeline_archival_config"),
    2048            0 :                 )
    2049            0 :             },
    2050            0 :         )
    2051            0 :         .put(
    2052            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/detach_ancestor",
    2053            0 :             |r| {
    2054            0 :                 tenant_service_handler(
    2055            0 :                     r,
    2056            0 :                     handle_tenant_timeline_detach_ancestor,
    2057            0 :                     RequestName("v1_tenant_timeline_detach_ancestor"),
    2058            0 :                 )
    2059            0 :             },
    2060            0 :         )
    2061            0 :         .post(
    2062            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/block_gc",
    2063            0 :             |r| {
    2064            0 :                 tenant_service_handler(
    2065            0 :                     r,
    2066            0 :                     |s, r| handle_tenant_timeline_block_unblock_gc(s, r, BlockUnblock::Block),
    2067            0 :                     RequestName("v1_tenant_timeline_block_unblock_gc"),
    2068            0 :                 )
    2069            0 :             },
    2070            0 :         )
    2071            0 :         .post(
    2072            0 :             "/v1/tenant/:tenant_id/timeline/:timeline_id/unblock_gc",
    2073            0 :             |r| {
    2074            0 :                 tenant_service_handler(
    2075            0 :                     r,
    2076            0 :                     |s, r| handle_tenant_timeline_block_unblock_gc(s, r, BlockUnblock::Unblock),
    2077            0 :                     RequestName("v1_tenant_timeline_block_unblock_gc"),
    2078            0 :                 )
    2079            0 :             },
    2080            0 :         )
    2081            0 :         // Tenant detail GET passthrough to shard zero:
    2082            0 :         .get("/v1/tenant/:tenant_id", |r| {
    2083            0 :             tenant_service_handler(
    2084            0 :                 r,
    2085            0 :                 handle_tenant_timeline_passthrough,
    2086            0 :                 RequestName("v1_tenant_passthrough"),
    2087            0 :             )
    2088            0 :         })
    2089            0 :         // The `*` in the  URL is a wildcard: any tenant/timeline GET APIs on the pageserver
    2090            0 :         // are implicitly exposed here.  This must be last in the list to avoid
    2091            0 :         // taking precedence over other GET methods we might implement by hand.
    2092            0 :         .get("/v1/tenant/:tenant_id/*", |r| {
    2093            0 :             tenant_service_handler(
    2094            0 :                 r,
    2095            0 :                 handle_tenant_timeline_passthrough,
    2096            0 :                 RequestName("v1_tenant_passthrough"),
    2097            0 :             )
    2098            0 :         })
    2099            0 : }
    2100              : 
    2101              : #[cfg(test)]
    2102              : mod test {
    2103              : 
    2104              :     use super::path_without_ids;
    2105              : 
    2106              :     #[test]
    2107            1 :     fn test_path_without_ids() {
    2108            1 :         assert_eq!(path_without_ids("/v1/tenant/1a2b3344556677881122334455667788/timeline/AA223344556677881122334455667788"), "/v1/tenant//timeline/");
    2109            1 :         assert_eq!(path_without_ids("/v1/tenant/1a2b3344556677881122334455667788-0108/timeline/AA223344556677881122334455667788"), "/v1/tenant//timeline/");
    2110            1 :         assert_eq!(path_without_ids("/v1/tenant/1a2b3344556677881122334455667788-0108/timeline/AA223344556677881122334455667788?parameter=foo"), "/v1/tenant//timeline/");
    2111            1 :     }
    2112              : }
        

Generated by: LCOV version 2.1-beta