LCOV - code coverage report
Current view: top level - storage_controller/src - http.rs (source / functions) Coverage Total Hit
Test: 1d5975439f3c9882b18414799141ebf9a3922c58.info Lines: 1.0 % 1736 17
Test Date: 2025-07-31 15:59:03 Functions: 0.6 % 532 3

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

Generated by: LCOV version 2.1-beta