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

Generated by: LCOV version 2.1-beta