LCOV - code coverage report
Current view: top level - storage_controller/src - http.rs (source / functions) Coverage Total Hit
Test: feead26e04cdef6e988ff1765b1cb7075eb48d3d.info Lines: 1.6 % 1597 26
Test Date: 2025-02-28 12:11:00 Functions: 0.7 % 437 3

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

Generated by: LCOV version 2.1-beta