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

Generated by: LCOV version 2.1-beta