LCOV - code coverage report
Current view: top level - storage_controller/src - http.rs (source / functions) Coverage Total Hit
Test: 1d18b743246dcf78c27c0bad0234a4c0da6fde89.info Lines: 0.0 % 1539 0
Test Date: 2025-02-14 00:11:37 Functions: 0.0 % 421 0

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

Generated by: LCOV version 2.1-beta