LCOV - code coverage report
Current view: top level - pageserver/src/http - routes.rs (source / functions) Coverage Total Hit
Test: 15f04989d2faf4ce76cecb56042184aca56ebae6.info Lines: 0.0 % 2810 0
Test Date: 2025-07-14 11:50:36 Functions: 0.0 % 932 0

            Line data    Source code
       1              : //!
       2              : //! Management HTTP API
       3              : //!
       4              : use std::cmp::Reverse;
       5              : use std::collections::BTreeMap;
       6              : use std::collections::BinaryHeap;
       7              : use std::collections::HashMap;
       8              : use std::str::FromStr;
       9              : use std::sync::Arc;
      10              : use std::time::Duration;
      11              : 
      12              : use anyhow::{Context, Result, anyhow};
      13              : use enumset::EnumSet;
      14              : use futures::future::join_all;
      15              : use futures::{StreamExt, TryFutureExt};
      16              : use http_utils::endpoint::{
      17              :     self, attach_openapi_ui, auth_middleware, check_permission_with, profile_cpu_handler,
      18              :     profile_heap_handler, prometheus_metrics_handler, request_span,
      19              : };
      20              : use http_utils::error::{ApiError, HttpErrorBody};
      21              : use http_utils::failpoints::failpoints_handler;
      22              : use http_utils::json::{json_request, json_request_maybe, json_response};
      23              : use http_utils::request::{
      24              :     get_request_param, must_get_query_param, must_parse_query_param, parse_query_param,
      25              :     parse_request_param,
      26              : };
      27              : use http_utils::{RequestExt, RouterBuilder};
      28              : use humantime::format_rfc3339;
      29              : use hyper::{Body, Request, Response, StatusCode, Uri, header};
      30              : use metrics::launch_timestamp::LaunchTimestamp;
      31              : use pageserver_api::models::virtual_file::IoMode;
      32              : use pageserver_api::models::{
      33              :     DetachBehavior, DownloadRemoteLayersTaskSpawnRequest, IngestAuxFilesRequest,
      34              :     ListAuxFilesRequest, LocationConfig, LocationConfigListResponse, LocationConfigMode, LsnLease,
      35              :     LsnLeaseRequest, OffloadedTimelineInfo, PageTraceEvent, ShardParameters, StatusResponse,
      36              :     TenantConfigPatchRequest, TenantConfigRequest, TenantDetails, TenantInfo,
      37              :     TenantLocationConfigRequest, TenantLocationConfigResponse, TenantScanRemoteStorageResponse,
      38              :     TenantScanRemoteStorageShard, TenantShardLocation, TenantShardSplitRequest,
      39              :     TenantShardSplitResponse, TenantSorting, TenantState, TenantWaitLsnRequest,
      40              :     TimelineArchivalConfigRequest, TimelineCreateRequest, TimelineCreateRequestMode,
      41              :     TimelineCreateRequestModeImportPgdata, TimelineGcRequest, TimelineInfo,
      42              :     TimelinePatchIndexPartRequest, TimelineVisibilityState, TimelinesInfoAndOffloaded,
      43              :     TopTenantShardItem, TopTenantShardsRequest, TopTenantShardsResponse,
      44              : };
      45              : use pageserver_api::shard::{ShardCount, TenantShardId};
      46              : use postgres_ffi::PgMajorVersion;
      47              : use remote_storage::{DownloadError, GenericRemoteStorage, TimeTravelError};
      48              : use scopeguard::defer;
      49              : use serde_json::json;
      50              : use tenant_size_model::svg::SvgBranchKind;
      51              : use tenant_size_model::{SizeResult, StorageModel};
      52              : use tokio::time::Instant;
      53              : use tokio_util::io::StreamReader;
      54              : use tokio_util::sync::CancellationToken;
      55              : use tracing::*;
      56              : use utils::auth::SwappableJwtAuth;
      57              : use utils::generation::Generation;
      58              : use utils::id::{TenantId, TimelineId};
      59              : use utils::lsn::Lsn;
      60              : 
      61              : use crate::config::PageServerConf;
      62              : use crate::context;
      63              : use crate::context::{DownloadBehavior, RequestContext, RequestContextBuilder};
      64              : use crate::deletion_queue::DeletionQueueClient;
      65              : use crate::feature_resolver::FeatureResolver;
      66              : use crate::metrics::LOCAL_DATA_LOSS_SUSPECTED;
      67              : use crate::pgdatadir_mapping::LsnForTimestamp;
      68              : use crate::task_mgr::TaskKind;
      69              : use crate::tenant::config::LocationConf;
      70              : use crate::tenant::mgr::{
      71              :     GetActiveTenantError, GetTenantError, TenantManager, TenantMapError, TenantMapInsertError,
      72              :     TenantSlot, TenantSlotError, TenantSlotUpsertError, TenantStateError, UpsertLocationError,
      73              : };
      74              : use crate::tenant::remote_timeline_client::index::GcCompactionState;
      75              : use crate::tenant::remote_timeline_client::{
      76              :     download_index_part, download_tenant_manifest, list_remote_tenant_shards, list_remote_timelines,
      77              : };
      78              : use crate::tenant::secondary::SecondaryController;
      79              : use crate::tenant::size::ModelInputs;
      80              : use crate::tenant::storage_layer::{IoConcurrency, LayerAccessStatsReset, LayerName};
      81              : use crate::tenant::timeline::layer_manager::LayerManagerLockHolder;
      82              : use crate::tenant::timeline::offload::{OffloadError, offload_timeline};
      83              : use crate::tenant::timeline::{
      84              :     CompactFlags, CompactOptions, CompactRequest, MarkInvisibleRequest, Timeline, WaitLsnTimeout,
      85              :     WaitLsnWaiter, import_pgdata,
      86              : };
      87              : use crate::tenant::{
      88              :     GetTimelineError, LogicalSizeCalculationCause, OffloadedTimeline, PageReconstructError,
      89              :     remote_timeline_client,
      90              : };
      91              : use crate::{DEFAULT_PG_VERSION, disk_usage_eviction_task, tenant};
      92              : 
      93              : // For APIs that require an Active tenant, how long should we block waiting for that state?
      94              : // This is not functionally necessary (clients will retry), but avoids generating a lot of
      95              : // failed API calls while tenants are activating.
      96              : #[cfg(not(feature = "testing"))]
      97              : pub(crate) const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(5000);
      98              : 
      99              : // Tests run on slow/oversubscribed nodes, and may need to wait much longer for tenants to
     100              : // finish attaching, if calls to remote storage are slow.
     101              : #[cfg(feature = "testing")]
     102              : pub(crate) const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(30000);
     103              : 
     104              : pub struct State {
     105              :     conf: &'static PageServerConf,
     106              :     tenant_manager: Arc<TenantManager>,
     107              :     auth: Option<Arc<SwappableJwtAuth>>,
     108              :     allowlist_routes: &'static [&'static str],
     109              :     remote_storage: GenericRemoteStorage,
     110              :     broker_client: storage_broker::BrokerClientChannel,
     111              :     disk_usage_eviction_state: Arc<disk_usage_eviction_task::State>,
     112              :     deletion_queue_client: DeletionQueueClient,
     113              :     secondary_controller: SecondaryController,
     114              :     latest_utilization: tokio::sync::Mutex<Option<(std::time::Instant, bytes::Bytes)>>,
     115              :     feature_resolver: FeatureResolver,
     116              : }
     117              : 
     118              : impl State {
     119              :     #[allow(clippy::too_many_arguments)]
     120            0 :     pub fn new(
     121            0 :         conf: &'static PageServerConf,
     122            0 :         tenant_manager: Arc<TenantManager>,
     123            0 :         auth: Option<Arc<SwappableJwtAuth>>,
     124            0 :         remote_storage: GenericRemoteStorage,
     125            0 :         broker_client: storage_broker::BrokerClientChannel,
     126            0 :         disk_usage_eviction_state: Arc<disk_usage_eviction_task::State>,
     127            0 :         deletion_queue_client: DeletionQueueClient,
     128            0 :         secondary_controller: SecondaryController,
     129            0 :         feature_resolver: FeatureResolver,
     130            0 :     ) -> anyhow::Result<Self> {
     131            0 :         let allowlist_routes = &[
     132            0 :             "/v1/status",
     133            0 :             "/v1/doc",
     134            0 :             "/swagger.yml",
     135            0 :             "/metrics",
     136            0 :             "/profile/cpu",
     137            0 :             "/profile/heap",
     138            0 :         ];
     139            0 :         Ok(Self {
     140            0 :             conf,
     141            0 :             tenant_manager,
     142            0 :             auth,
     143            0 :             allowlist_routes,
     144            0 :             remote_storage,
     145            0 :             broker_client,
     146            0 :             disk_usage_eviction_state,
     147            0 :             deletion_queue_client,
     148            0 :             secondary_controller,
     149            0 :             latest_utilization: Default::default(),
     150            0 :             feature_resolver,
     151            0 :         })
     152            0 :     }
     153              : }
     154              : 
     155              : #[inline(always)]
     156            0 : fn get_state(request: &Request<Body>) -> &State {
     157            0 :     request
     158            0 :         .data::<Arc<State>>()
     159            0 :         .expect("unknown state type")
     160            0 :         .as_ref()
     161            0 : }
     162              : 
     163              : #[inline(always)]
     164            0 : fn get_config(request: &Request<Body>) -> &'static PageServerConf {
     165            0 :     get_state(request).conf
     166            0 : }
     167              : 
     168              : /// Check that the requester is authorized to operate on given tenant
     169            0 : fn check_permission(request: &Request<Body>, tenant_id: Option<TenantId>) -> Result<(), ApiError> {
     170            0 :     check_permission_with(request, |claims| {
     171            0 :         crate::auth::check_permission(claims, tenant_id)
     172            0 :     })
     173            0 : }
     174              : 
     175              : impl From<PageReconstructError> for ApiError {
     176            0 :     fn from(pre: PageReconstructError) -> ApiError {
     177            0 :         match pre {
     178            0 :             PageReconstructError::Other(other) => ApiError::InternalServerError(other),
     179            0 :             PageReconstructError::MissingKey(e) => ApiError::InternalServerError(e.into()),
     180            0 :             PageReconstructError::Cancelled => ApiError::Cancelled,
     181            0 :             PageReconstructError::AncestorLsnTimeout(e) => ApiError::Timeout(format!("{e}").into()),
     182            0 :             PageReconstructError::WalRedo(pre) => ApiError::InternalServerError(pre),
     183              :         }
     184            0 :     }
     185              : }
     186              : 
     187              : impl From<TenantMapInsertError> for ApiError {
     188            0 :     fn from(tmie: TenantMapInsertError) -> ApiError {
     189            0 :         match tmie {
     190            0 :             TenantMapInsertError::SlotError(e) => e.into(),
     191            0 :             TenantMapInsertError::SlotUpsertError(e) => e.into(),
     192            0 :             TenantMapInsertError::Other(e) => ApiError::InternalServerError(e),
     193              :         }
     194            0 :     }
     195              : }
     196              : 
     197              : impl From<TenantSlotError> for ApiError {
     198            0 :     fn from(e: TenantSlotError) -> ApiError {
     199              :         use TenantSlotError::*;
     200            0 :         match e {
     201            0 :             NotFound(tenant_id) => {
     202            0 :                 ApiError::NotFound(anyhow::anyhow!("NotFound: tenant {tenant_id}").into())
     203              :             }
     204              :             InProgress => {
     205            0 :                 ApiError::ResourceUnavailable("Tenant is being modified concurrently".into())
     206              :             }
     207            0 :             MapState(e) => e.into(),
     208              :         }
     209            0 :     }
     210              : }
     211              : 
     212              : impl From<TenantSlotUpsertError> for ApiError {
     213            0 :     fn from(e: TenantSlotUpsertError) -> ApiError {
     214              :         use TenantSlotUpsertError::*;
     215            0 :         match e {
     216            0 :             InternalError(e) => ApiError::InternalServerError(anyhow::anyhow!("{e}")),
     217            0 :             MapState(e) => e.into(),
     218            0 :             ShuttingDown(_) => ApiError::ShuttingDown,
     219              :         }
     220            0 :     }
     221              : }
     222              : 
     223              : impl From<UpsertLocationError> for ApiError {
     224            0 :     fn from(e: UpsertLocationError) -> ApiError {
     225              :         use UpsertLocationError::*;
     226            0 :         match e {
     227            0 :             BadRequest(e) => ApiError::BadRequest(e),
     228            0 :             Unavailable(_) => ApiError::ShuttingDown,
     229            0 :             e @ InProgress => ApiError::Conflict(format!("{e}")),
     230            0 :             Flush(e) | InternalError(e) => ApiError::InternalServerError(e),
     231              :         }
     232            0 :     }
     233              : }
     234              : 
     235              : impl From<TenantMapError> for ApiError {
     236            0 :     fn from(e: TenantMapError) -> ApiError {
     237              :         use TenantMapError::*;
     238            0 :         match e {
     239              :             StillInitializing | ShuttingDown => {
     240            0 :                 ApiError::ResourceUnavailable(format!("{e}").into())
     241              :             }
     242              :         }
     243            0 :     }
     244              : }
     245              : 
     246              : impl From<TenantStateError> for ApiError {
     247            0 :     fn from(tse: TenantStateError) -> ApiError {
     248            0 :         match tse {
     249              :             TenantStateError::IsStopping(_) => {
     250            0 :                 ApiError::ResourceUnavailable("Tenant is stopping".into())
     251              :             }
     252            0 :             TenantStateError::SlotError(e) => e.into(),
     253            0 :             TenantStateError::SlotUpsertError(e) => e.into(),
     254            0 :             TenantStateError::Other(e) => ApiError::InternalServerError(anyhow!(e)),
     255              :         }
     256            0 :     }
     257              : }
     258              : 
     259              : impl From<GetTenantError> for ApiError {
     260            0 :     fn from(tse: GetTenantError) -> ApiError {
     261            0 :         match tse {
     262            0 :             GetTenantError::NotFound(tid) => ApiError::NotFound(anyhow!("tenant {tid}").into()),
     263            0 :             GetTenantError::ShardNotFound(tid) => {
     264            0 :                 ApiError::NotFound(anyhow!("tenant {tid}").into())
     265              :             }
     266              :             GetTenantError::NotActive(_) => {
     267              :                 // Why is this not `ApiError::NotFound`?
     268              :                 // Because we must be careful to never return 404 for a tenant if it does
     269              :                 // in fact exist locally. If we did, the caller could draw the conclusion
     270              :                 // that it can attach the tenant to another PS and we'd be in split-brain.
     271            0 :                 ApiError::ResourceUnavailable("Tenant not yet active".into())
     272              :             }
     273            0 :             GetTenantError::MapState(e) => ApiError::ResourceUnavailable(format!("{e}").into()),
     274              :         }
     275            0 :     }
     276              : }
     277              : 
     278              : impl From<GetTimelineError> for ApiError {
     279            0 :     fn from(gte: GetTimelineError) -> Self {
     280              :         // Rationale: tenant is activated only after eligble timelines activate
     281            0 :         ApiError::NotFound(gte.into())
     282            0 :     }
     283              : }
     284              : 
     285              : impl From<GetActiveTenantError> for ApiError {
     286            0 :     fn from(e: GetActiveTenantError) -> ApiError {
     287            0 :         match e {
     288            0 :             GetActiveTenantError::Broken(reason) => {
     289            0 :                 ApiError::InternalServerError(anyhow!("tenant is broken: {}", reason))
     290              :             }
     291              :             GetActiveTenantError::WillNotBecomeActive(TenantState::Stopping { .. }) => {
     292            0 :                 ApiError::ShuttingDown
     293              :             }
     294            0 :             GetActiveTenantError::WillNotBecomeActive(_) => ApiError::Conflict(format!("{e}")),
     295            0 :             GetActiveTenantError::Cancelled => ApiError::ShuttingDown,
     296            0 :             GetActiveTenantError::NotFound(gte) => gte.into(),
     297              :             GetActiveTenantError::WaitForActiveTimeout { .. } => {
     298            0 :                 ApiError::ResourceUnavailable(format!("{e}").into())
     299              :             }
     300              :             GetActiveTenantError::SwitchedTenant => {
     301              :                 // in our HTTP handlers, this error doesn't happen
     302              :                 // TODO: separate error types
     303            0 :                 ApiError::ResourceUnavailable("switched tenant".into())
     304              :             }
     305              :         }
     306            0 :     }
     307              : }
     308              : 
     309              : impl From<crate::tenant::DeleteTimelineError> for ApiError {
     310            0 :     fn from(value: crate::tenant::DeleteTimelineError) -> Self {
     311              :         use crate::tenant::DeleteTimelineError::*;
     312            0 :         match value {
     313            0 :             NotFound => ApiError::NotFound(anyhow::anyhow!("timeline not found").into()),
     314            0 :             HasChildren(children) => ApiError::PreconditionFailed(
     315            0 :                 format!("Cannot delete timeline which has child timelines: {children:?}")
     316            0 :                     .into_boxed_str(),
     317            0 :             ),
     318            0 :             a @ AlreadyInProgress(_) => ApiError::Conflict(a.to_string()),
     319            0 :             Cancelled => ApiError::ResourceUnavailable("shutting down".into()),
     320            0 :             Other(e) => ApiError::InternalServerError(e),
     321              :         }
     322            0 :     }
     323              : }
     324              : 
     325              : impl From<crate::tenant::TimelineArchivalError> for ApiError {
     326            0 :     fn from(value: crate::tenant::TimelineArchivalError) -> Self {
     327              :         use crate::tenant::TimelineArchivalError::*;
     328            0 :         match value {
     329            0 :             NotFound => ApiError::NotFound(anyhow::anyhow!("timeline not found").into()),
     330            0 :             Timeout => ApiError::Timeout("hit pageserver internal timeout".into()),
     331            0 :             Cancelled => ApiError::ShuttingDown,
     332            0 :             e @ HasArchivedParent(_) => {
     333            0 :                 ApiError::PreconditionFailed(e.to_string().into_boxed_str())
     334              :             }
     335            0 :             HasUnarchivedChildren(children) => ApiError::PreconditionFailed(
     336            0 :                 format!(
     337            0 :                     "Cannot archive timeline which has non-archived child timelines: {children:?}"
     338            0 :                 )
     339            0 :                 .into_boxed_str(),
     340            0 :             ),
     341            0 :             a @ AlreadyInProgress => ApiError::Conflict(a.to_string()),
     342            0 :             Other(e) => ApiError::InternalServerError(e),
     343              :         }
     344            0 :     }
     345              : }
     346              : 
     347              : impl From<crate::tenant::mgr::DeleteTimelineError> for ApiError {
     348            0 :     fn from(value: crate::tenant::mgr::DeleteTimelineError) -> Self {
     349              :         use crate::tenant::mgr::DeleteTimelineError::*;
     350            0 :         match value {
     351              :             // Report Precondition failed so client can distinguish between
     352              :             // "tenant is missing" case from "timeline is missing"
     353            0 :             Tenant(GetTenantError::NotFound(..)) => ApiError::PreconditionFailed(
     354            0 :                 "Requested tenant is missing".to_owned().into_boxed_str(),
     355            0 :             ),
     356            0 :             Tenant(t) => ApiError::from(t),
     357            0 :             Timeline(t) => ApiError::from(t),
     358              :         }
     359            0 :     }
     360              : }
     361              : 
     362              : impl From<crate::tenant::mgr::DeleteTenantError> for ApiError {
     363            0 :     fn from(value: crate::tenant::mgr::DeleteTenantError) -> Self {
     364              :         use crate::tenant::mgr::DeleteTenantError::*;
     365            0 :         match value {
     366            0 :             SlotError(e) => e.into(),
     367            0 :             Other(o) => ApiError::InternalServerError(o),
     368            0 :             Cancelled => ApiError::ShuttingDown,
     369              :         }
     370            0 :     }
     371              : }
     372              : 
     373              : impl From<crate::tenant::secondary::SecondaryTenantError> for ApiError {
     374            0 :     fn from(ste: crate::tenant::secondary::SecondaryTenantError) -> ApiError {
     375              :         use crate::tenant::secondary::SecondaryTenantError;
     376            0 :         match ste {
     377            0 :             SecondaryTenantError::GetTenant(gte) => gte.into(),
     378            0 :             SecondaryTenantError::ShuttingDown => ApiError::ShuttingDown,
     379              :         }
     380            0 :     }
     381              : }
     382              : 
     383              : impl From<crate::tenant::FinalizeTimelineImportError> for ApiError {
     384            0 :     fn from(err: crate::tenant::FinalizeTimelineImportError) -> ApiError {
     385              :         use crate::tenant::FinalizeTimelineImportError::*;
     386            0 :         match err {
     387              :             ImportTaskStillRunning => {
     388            0 :                 ApiError::ResourceUnavailable("Import task still running".into())
     389              :             }
     390            0 :             ShuttingDown => ApiError::ShuttingDown,
     391              :         }
     392            0 :     }
     393              : }
     394              : 
     395              : // Helper function to construct a TimelineInfo struct for a timeline
     396            0 : async fn build_timeline_info(
     397            0 :     timeline: &Arc<Timeline>,
     398            0 :     include_non_incremental_logical_size: bool,
     399            0 :     force_await_initial_logical_size: bool,
     400            0 :     include_image_consistent_lsn: bool,
     401            0 :     ctx: &RequestContext,
     402            0 : ) -> anyhow::Result<TimelineInfo> {
     403            0 :     crate::tenant::debug_assert_current_span_has_tenant_and_timeline_id();
     404              : 
     405            0 :     if force_await_initial_logical_size {
     406            0 :         timeline.clone().await_initial_logical_size().await
     407            0 :     }
     408              : 
     409            0 :     let mut info = build_timeline_info_common(
     410            0 :         timeline,
     411            0 :         ctx,
     412            0 :         tenant::timeline::GetLogicalSizePriority::Background,
     413            0 :     )
     414            0 :     .await?;
     415            0 :     if include_non_incremental_logical_size {
     416              :         // XXX we should be using spawn_ondemand_logical_size_calculation here.
     417              :         // Otherwise, if someone deletes the timeline / detaches the tenant while
     418              :         // we're executing this function, we will outlive the timeline on-disk state.
     419              :         info.current_logical_size_non_incremental = Some(
     420            0 :             timeline
     421            0 :                 .get_current_logical_size_non_incremental(info.last_record_lsn, ctx)
     422            0 :                 .await?,
     423              :         );
     424            0 :     }
     425              :     // HADRON
     426            0 :     if include_image_consistent_lsn {
     427            0 :         info.image_consistent_lsn = Some(timeline.compute_image_consistent_lsn().await?);
     428            0 :     }
     429            0 :     Ok(info)
     430            0 : }
     431              : 
     432            0 : async fn build_timeline_info_common(
     433            0 :     timeline: &Arc<Timeline>,
     434            0 :     ctx: &RequestContext,
     435            0 :     logical_size_task_priority: tenant::timeline::GetLogicalSizePriority,
     436            0 : ) -> anyhow::Result<TimelineInfo> {
     437            0 :     crate::tenant::debug_assert_current_span_has_tenant_and_timeline_id();
     438            0 :     let initdb_lsn = timeline.initdb_lsn;
     439            0 :     let last_record_lsn = timeline.get_last_record_lsn();
     440            0 :     let (wal_source_connstr, last_received_msg_lsn, last_received_msg_ts) = {
     441            0 :         let guard = timeline.last_received_wal.lock().unwrap();
     442            0 :         if let Some(info) = guard.as_ref() {
     443            0 :             (
     444            0 :                 Some(format!("{}", info.wal_source_connconf)), // Password is hidden, but it's for statistics only.
     445            0 :                 Some(info.last_received_msg_lsn),
     446            0 :                 Some(info.last_received_msg_ts),
     447            0 :             )
     448              :         } else {
     449            0 :             (None, None, None)
     450              :         }
     451              :     };
     452              : 
     453            0 :     let ancestor_timeline_id = timeline.get_ancestor_timeline_id();
     454            0 :     let ancestor_lsn = match timeline.get_ancestor_lsn() {
     455            0 :         Lsn(0) => None,
     456            0 :         lsn @ Lsn(_) => Some(lsn),
     457              :     };
     458            0 :     let current_logical_size = timeline.get_current_logical_size(logical_size_task_priority, ctx);
     459            0 :     let current_physical_size = Some(timeline.layer_size_sum().await);
     460            0 :     let state = timeline.current_state();
     461              :     // Report is_archived = false if the timeline is still loading
     462            0 :     let is_archived = timeline.is_archived().unwrap_or(false);
     463            0 :     let remote_consistent_lsn_projected = timeline
     464            0 :         .get_remote_consistent_lsn_projected()
     465            0 :         .unwrap_or(Lsn(0));
     466            0 :     let remote_consistent_lsn_visible = timeline
     467            0 :         .get_remote_consistent_lsn_visible()
     468            0 :         .unwrap_or(Lsn(0));
     469            0 :     let is_invisible = timeline.remote_client.is_invisible().unwrap_or(false);
     470              : 
     471            0 :     let walreceiver_status = timeline.walreceiver_status();
     472              : 
     473            0 :     let (pitr_history_size, within_ancestor_pitr) = timeline.get_pitr_history_stats();
     474              : 
     475              :     // Externally, expose the lowest LSN that can be used to create a branch.
     476              :     // Internally we distinguish between the planned GC cutoff (PITR point) and the "applied" GC cutoff (where we
     477              :     // actually trimmed data to), which can pass each other when PITR is changed.
     478            0 :     let min_readable_lsn = std::cmp::max(
     479            0 :         timeline.get_gc_cutoff_lsn().unwrap_or_default(),
     480            0 :         *timeline.get_applied_gc_cutoff_lsn(),
     481              :     );
     482              : 
     483            0 :     let info = TimelineInfo {
     484            0 :         tenant_id: timeline.tenant_shard_id,
     485            0 :         timeline_id: timeline.timeline_id,
     486            0 :         ancestor_timeline_id,
     487            0 :         ancestor_lsn,
     488            0 :         disk_consistent_lsn: timeline.get_disk_consistent_lsn(),
     489            0 :         remote_consistent_lsn: remote_consistent_lsn_projected,
     490            0 :         remote_consistent_lsn_visible,
     491            0 :         initdb_lsn,
     492            0 :         last_record_lsn,
     493            0 :         prev_record_lsn: Some(timeline.get_prev_record_lsn()),
     494            0 :         min_readable_lsn,
     495            0 :         applied_gc_cutoff_lsn: *timeline.get_applied_gc_cutoff_lsn(),
     496            0 :         current_logical_size: current_logical_size.size_dont_care_about_accuracy(),
     497            0 :         current_logical_size_is_accurate: match current_logical_size.accuracy() {
     498            0 :             tenant::timeline::logical_size::Accuracy::Approximate => false,
     499            0 :             tenant::timeline::logical_size::Accuracy::Exact => true,
     500              :         },
     501            0 :         directory_entries_counts: timeline.get_directory_metrics().to_vec(),
     502            0 :         current_physical_size,
     503            0 :         current_logical_size_non_incremental: None,
     504            0 :         pitr_history_size,
     505            0 :         within_ancestor_pitr,
     506            0 :         timeline_dir_layer_file_size_sum: None,
     507            0 :         wal_source_connstr,
     508            0 :         last_received_msg_lsn,
     509            0 :         last_received_msg_ts,
     510            0 :         pg_version: timeline.pg_version,
     511              : 
     512            0 :         state,
     513            0 :         is_archived: Some(is_archived),
     514            0 :         rel_size_migration: Some(timeline.get_rel_size_v2_status()),
     515            0 :         is_invisible: Some(is_invisible),
     516              : 
     517            0 :         walreceiver_status,
     518              :         // HADRON
     519            0 :         image_consistent_lsn: None,
     520              :     };
     521            0 :     Ok(info)
     522            0 : }
     523              : 
     524            0 : fn build_timeline_offloaded_info(offloaded: &Arc<OffloadedTimeline>) -> OffloadedTimelineInfo {
     525              :     let &OffloadedTimeline {
     526            0 :         tenant_shard_id,
     527            0 :         timeline_id,
     528            0 :         ancestor_retain_lsn,
     529            0 :         ancestor_timeline_id,
     530            0 :         archived_at,
     531              :         ..
     532            0 :     } = offloaded.as_ref();
     533            0 :     OffloadedTimelineInfo {
     534            0 :         tenant_id: tenant_shard_id,
     535            0 :         timeline_id,
     536            0 :         ancestor_retain_lsn,
     537            0 :         ancestor_timeline_id,
     538            0 :         archived_at: archived_at.and_utc(),
     539            0 :     }
     540            0 : }
     541              : 
     542              : // healthcheck handler
     543            0 : async fn status_handler(
     544            0 :     request: Request<Body>,
     545            0 :     _cancel: CancellationToken,
     546            0 : ) -> Result<Response<Body>, ApiError> {
     547            0 :     check_permission(&request, None)?;
     548            0 :     let config = get_config(&request);
     549            0 :     json_response(StatusCode::OK, StatusResponse { id: config.id })
     550            0 : }
     551              : 
     552            0 : async fn reload_auth_validation_keys_handler(
     553            0 :     request: Request<Body>,
     554            0 :     _cancel: CancellationToken,
     555            0 : ) -> Result<Response<Body>, ApiError> {
     556            0 :     check_permission(&request, None)?;
     557            0 :     let config = get_config(&request);
     558            0 :     let state = get_state(&request);
     559            0 :     let Some(shared_auth) = &state.auth else {
     560            0 :         return json_response(StatusCode::BAD_REQUEST, ());
     561              :     };
     562              :     // unwrap is ok because check is performed when creating config, so path is set and exists
     563            0 :     let key_path = config.auth_validation_public_key_path.as_ref().unwrap();
     564            0 :     info!("Reloading public key(s) for verifying JWT tokens from {key_path:?}");
     565              : 
     566            0 :     match utils::auth::JwtAuth::from_key_path(key_path) {
     567            0 :         Ok(new_auth) => {
     568            0 :             shared_auth.swap(new_auth);
     569            0 :             json_response(StatusCode::OK, ())
     570              :         }
     571            0 :         Err(e) => {
     572            0 :             let err_msg = "Error reloading public keys";
     573            0 :             warn!("Error reloading public keys from {key_path:?}: {e:}");
     574            0 :             json_response(
     575              :                 StatusCode::INTERNAL_SERVER_ERROR,
     576            0 :                 HttpErrorBody::from_msg(err_msg.to_string()),
     577              :             )
     578              :         }
     579              :     }
     580            0 : }
     581              : 
     582            0 : async fn timeline_create_handler(
     583            0 :     mut request: Request<Body>,
     584            0 :     _cancel: CancellationToken,
     585            0 : ) -> Result<Response<Body>, ApiError> {
     586            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     587            0 :     let request_data: TimelineCreateRequest = json_request(&mut request).await?;
     588            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     589              : 
     590            0 :     let new_timeline_id = request_data.new_timeline_id;
     591              :     // fill in the default pg_version if not provided & convert request into domain model
     592            0 :     let params: tenant::CreateTimelineParams = match request_data.mode {
     593              :         TimelineCreateRequestMode::Bootstrap {
     594            0 :             existing_initdb_timeline_id,
     595            0 :             pg_version,
     596            0 :         } => tenant::CreateTimelineParams::Bootstrap(tenant::CreateTimelineParamsBootstrap {
     597            0 :             new_timeline_id,
     598            0 :             existing_initdb_timeline_id,
     599            0 :             pg_version: pg_version.unwrap_or(DEFAULT_PG_VERSION),
     600            0 :         }),
     601              :         TimelineCreateRequestMode::Branch {
     602            0 :             ancestor_timeline_id,
     603            0 :             ancestor_start_lsn,
     604              :             read_only: _,
     605              :             pg_version: _,
     606            0 :         } => tenant::CreateTimelineParams::Branch(tenant::CreateTimelineParamsBranch {
     607            0 :             new_timeline_id,
     608            0 :             ancestor_timeline_id,
     609            0 :             ancestor_start_lsn,
     610            0 :         }),
     611              :         TimelineCreateRequestMode::ImportPgdata {
     612              :             import_pgdata:
     613              :                 TimelineCreateRequestModeImportPgdata {
     614            0 :                     location,
     615            0 :                     idempotency_key,
     616              :                 },
     617              :         } => tenant::CreateTimelineParams::ImportPgdata(tenant::CreateTimelineParamsImportPgdata {
     618            0 :             idempotency_key: import_pgdata::index_part_format::IdempotencyKey::new(
     619            0 :                 idempotency_key.0,
     620              :             ),
     621            0 :             new_timeline_id,
     622              :             location: {
     623              :                 use import_pgdata::index_part_format::Location;
     624              :                 use pageserver_api::models::ImportPgdataLocation;
     625            0 :                 match location {
     626              :                     #[cfg(feature = "testing")]
     627            0 :                     ImportPgdataLocation::LocalFs { path } => Location::LocalFs { path },
     628              :                     ImportPgdataLocation::AwsS3 {
     629            0 :                         region,
     630            0 :                         bucket,
     631            0 :                         key,
     632            0 :                     } => Location::AwsS3 {
     633            0 :                         region,
     634            0 :                         bucket,
     635            0 :                         key,
     636            0 :                     },
     637              :                 }
     638              :             },
     639              :         }),
     640              :     };
     641              : 
     642            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Error);
     643              : 
     644            0 :     let state = get_state(&request);
     645              : 
     646            0 :     async {
     647            0 :         let tenant = state
     648            0 :             .tenant_manager
     649            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     650              : 
     651            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     652              : 
     653              :         // earlier versions of the code had pg_version and ancestor_lsn in the span
     654              :         // => continue to provide that information, but, through a log message that doesn't require us to destructure
     655            0 :         tracing::info!(?params, "creating timeline");
     656              : 
     657            0 :         match tenant
     658            0 :             .create_timeline(params, state.broker_client.clone(), &ctx)
     659            0 :             .await
     660              :         {
     661            0 :             Ok(new_timeline) => {
     662              :                 // Created. Construct a TimelineInfo for it.
     663            0 :                 let timeline_info = build_timeline_info_common(
     664            0 :                     &new_timeline,
     665            0 :                     &ctx,
     666            0 :                     tenant::timeline::GetLogicalSizePriority::User,
     667            0 :                 )
     668            0 :                 .await
     669            0 :                 .map_err(ApiError::InternalServerError)?;
     670            0 :                 json_response(StatusCode::CREATED, timeline_info)
     671              :             }
     672            0 :             Err(_) if tenant.cancel.is_cancelled() => {
     673              :                 // In case we get some ugly error type during shutdown, cast it into a clean 503.
     674            0 :                 json_response(
     675              :                     StatusCode::SERVICE_UNAVAILABLE,
     676            0 :                     HttpErrorBody::from_msg("Tenant shutting down".to_string()),
     677              :                 )
     678              :             }
     679            0 :             Err(e @ tenant::CreateTimelineError::Conflict) => {
     680            0 :                 json_response(StatusCode::CONFLICT, HttpErrorBody::from_msg(e.to_string()))
     681              :             }
     682            0 :             Err(e @ tenant::CreateTimelineError::AlreadyCreating) => json_response(
     683              :                 StatusCode::TOO_MANY_REQUESTS,
     684            0 :                 HttpErrorBody::from_msg(e.to_string()),
     685              :             ),
     686            0 :             Err(tenant::CreateTimelineError::AncestorLsn(err)) => json_response(
     687              :                 StatusCode::NOT_ACCEPTABLE,
     688            0 :                 HttpErrorBody::from_msg(format!("{err:#}")),
     689              :             ),
     690            0 :             Err(e @ tenant::CreateTimelineError::AncestorNotActive) => json_response(
     691              :                 StatusCode::SERVICE_UNAVAILABLE,
     692            0 :                 HttpErrorBody::from_msg(e.to_string()),
     693              :             ),
     694            0 :             Err(e @ tenant::CreateTimelineError::AncestorArchived) => json_response(
     695              :                 StatusCode::NOT_ACCEPTABLE,
     696            0 :                 HttpErrorBody::from_msg(e.to_string()),
     697              :             ),
     698            0 :             Err(tenant::CreateTimelineError::ShuttingDown) => json_response(
     699              :                 StatusCode::SERVICE_UNAVAILABLE,
     700            0 :                 HttpErrorBody::from_msg("tenant shutting down".to_string()),
     701              :             ),
     702            0 :             Err(tenant::CreateTimelineError::Other(err)) => Err(ApiError::InternalServerError(err)),
     703              :         }
     704            0 :     }
     705            0 :     .instrument(info_span!("timeline_create",
     706              :         tenant_id = %tenant_shard_id.tenant_id,
     707            0 :         shard_id = %tenant_shard_id.shard_slug(),
     708              :         timeline_id = %new_timeline_id,
     709              :     ))
     710            0 :     .await
     711            0 : }
     712              : 
     713            0 : async fn timeline_list_handler(
     714            0 :     request: Request<Body>,
     715            0 :     _cancel: CancellationToken,
     716            0 : ) -> Result<Response<Body>, ApiError> {
     717            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     718            0 :     let include_non_incremental_logical_size: Option<bool> =
     719            0 :         parse_query_param(&request, "include-non-incremental-logical-size")?;
     720            0 :     let force_await_initial_logical_size: Option<bool> =
     721            0 :         parse_query_param(&request, "force-await-initial-logical-size")?;
     722            0 :     let include_image_consistent_lsn: Option<bool> =
     723            0 :         parse_query_param(&request, "include-image-consistent-lsn")?;
     724            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     725              : 
     726            0 :     let state = get_state(&request);
     727            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
     728              : 
     729            0 :     let response_data = async {
     730            0 :         let tenant = state
     731            0 :             .tenant_manager
     732            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     733              : 
     734            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     735              : 
     736            0 :         let timelines = tenant.list_timelines();
     737              : 
     738            0 :         let mut response_data = Vec::with_capacity(timelines.len());
     739            0 :         for timeline in timelines {
     740            0 :             let timeline_info = build_timeline_info(
     741            0 :                 &timeline,
     742            0 :                 include_non_incremental_logical_size.unwrap_or(false),
     743            0 :                 force_await_initial_logical_size.unwrap_or(false),
     744            0 :                 include_image_consistent_lsn.unwrap_or(false),
     745            0 :                 &ctx,
     746              :             )
     747            0 :             .instrument(info_span!("build_timeline_info", timeline_id = %timeline.timeline_id))
     748            0 :             .await
     749            0 :             .context("Failed to build timeline info")
     750            0 :             .map_err(ApiError::InternalServerError)?;
     751              : 
     752            0 :             response_data.push(timeline_info);
     753              :         }
     754            0 :         Ok::<Vec<TimelineInfo>, ApiError>(response_data)
     755            0 :     }
     756            0 :     .instrument(info_span!("timeline_list",
     757              :                 tenant_id = %tenant_shard_id.tenant_id,
     758            0 :                 shard_id = %tenant_shard_id.shard_slug()))
     759            0 :     .await?;
     760              : 
     761            0 :     json_response(StatusCode::OK, response_data)
     762            0 : }
     763              : 
     764            0 : async fn timeline_and_offloaded_list_handler(
     765            0 :     request: Request<Body>,
     766            0 :     _cancel: CancellationToken,
     767            0 : ) -> Result<Response<Body>, ApiError> {
     768            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     769            0 :     let include_non_incremental_logical_size: Option<bool> =
     770            0 :         parse_query_param(&request, "include-non-incremental-logical-size")?;
     771            0 :     let force_await_initial_logical_size: Option<bool> =
     772            0 :         parse_query_param(&request, "force-await-initial-logical-size")?;
     773            0 :     let include_image_consistent_lsn: Option<bool> =
     774            0 :         parse_query_param(&request, "include-image-consistent-lsn")?;
     775              : 
     776            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     777              : 
     778            0 :     let state = get_state(&request);
     779            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
     780              : 
     781            0 :     let response_data = async {
     782            0 :         let tenant = state
     783            0 :             .tenant_manager
     784            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     785              : 
     786            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     787              : 
     788            0 :         let (timelines, offloadeds) = tenant.list_timelines_and_offloaded();
     789              : 
     790            0 :         let mut timeline_infos = Vec::with_capacity(timelines.len());
     791            0 :         for timeline in timelines {
     792            0 :             let timeline_info = build_timeline_info(
     793            0 :                 &timeline,
     794            0 :                 include_non_incremental_logical_size.unwrap_or(false),
     795            0 :                 force_await_initial_logical_size.unwrap_or(false),
     796            0 :                 include_image_consistent_lsn.unwrap_or(false),
     797            0 :                 &ctx,
     798              :             )
     799            0 :             .instrument(info_span!("build_timeline_info", timeline_id = %timeline.timeline_id))
     800            0 :             .await
     801            0 :             .context("Failed to build timeline info")
     802            0 :             .map_err(ApiError::InternalServerError)?;
     803              : 
     804            0 :             timeline_infos.push(timeline_info);
     805              :         }
     806            0 :         let offloaded_infos = offloadeds
     807            0 :             .into_iter()
     808            0 :             .map(|offloaded| build_timeline_offloaded_info(&offloaded))
     809            0 :             .collect::<Vec<_>>();
     810            0 :         let res = TimelinesInfoAndOffloaded {
     811            0 :             timelines: timeline_infos,
     812            0 :             offloaded: offloaded_infos,
     813            0 :         };
     814            0 :         Ok::<TimelinesInfoAndOffloaded, ApiError>(res)
     815            0 :     }
     816            0 :     .instrument(info_span!("timeline_and_offloaded_list",
     817              :                 tenant_id = %tenant_shard_id.tenant_id,
     818            0 :                 shard_id = %tenant_shard_id.shard_slug()))
     819            0 :     .await?;
     820              : 
     821            0 :     json_response(StatusCode::OK, response_data)
     822            0 : }
     823              : 
     824            0 : async fn timeline_preserve_initdb_handler(
     825            0 :     request: Request<Body>,
     826            0 :     _cancel: CancellationToken,
     827            0 : ) -> Result<Response<Body>, ApiError> {
     828            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     829            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     830            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     831            0 :     let state = get_state(&request);
     832              : 
     833              :     // Part of the process for disaster recovery from safekeeper-stored WAL:
     834              :     // If we don't recover into a new timeline but want to keep the timeline ID,
     835              :     // then the initdb archive is deleted. This endpoint copies it to a different
     836              :     // location where timeline recreation cand find it.
     837              : 
     838            0 :     async {
     839            0 :         let tenant = state
     840            0 :             .tenant_manager
     841            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     842              : 
     843            0 :         let timeline = tenant.get_timeline(timeline_id, false)?;
     844              : 
     845            0 :         timeline
     846            0 :             .preserve_initdb_archive()
     847            0 :             .await
     848            0 :             .context("preserving initdb archive")
     849            0 :             .map_err(ApiError::InternalServerError)?;
     850              : 
     851            0 :         Ok::<_, ApiError>(())
     852            0 :     }
     853            0 :     .instrument(info_span!("timeline_preserve_initdb_archive",
     854              :                 tenant_id = %tenant_shard_id.tenant_id,
     855            0 :                 shard_id = %tenant_shard_id.shard_slug(),
     856              :                 %timeline_id))
     857            0 :     .await?;
     858              : 
     859            0 :     json_response(StatusCode::OK, ())
     860            0 : }
     861              : 
     862            0 : async fn timeline_archival_config_handler(
     863            0 :     mut request: Request<Body>,
     864            0 :     _cancel: CancellationToken,
     865            0 : ) -> Result<Response<Body>, ApiError> {
     866            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     867            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     868              : 
     869            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
     870              : 
     871            0 :     let request_data: TimelineArchivalConfigRequest = json_request(&mut request).await?;
     872            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     873            0 :     let state = get_state(&request);
     874              : 
     875            0 :     async {
     876            0 :         let tenant = state
     877            0 :             .tenant_manager
     878            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     879              : 
     880            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     881              : 
     882            0 :         tenant
     883            0 :             .apply_timeline_archival_config(
     884            0 :                 timeline_id,
     885            0 :                 request_data.state,
     886            0 :                 state.broker_client.clone(),
     887            0 :                 ctx,
     888            0 :             )
     889            0 :             .await?;
     890            0 :         Ok::<_, ApiError>(())
     891            0 :     }
     892            0 :     .instrument(info_span!("timeline_archival_config",
     893              :                 tenant_id = %tenant_shard_id.tenant_id,
     894            0 :                 shard_id = %tenant_shard_id.shard_slug(),
     895              :                 state = ?request_data.state,
     896              :                 %timeline_id))
     897            0 :     .await?;
     898              : 
     899            0 :     json_response(StatusCode::OK, ())
     900            0 : }
     901              : 
     902              : /// This API is used to patch the index part of a timeline. You must ensure such patches are safe to apply. Use this API as an emergency
     903              : /// measure only.
     904              : ///
     905              : /// Some examples of safe patches:
     906              : /// - Increase the gc_cutoff and gc_compaction_cutoff to a larger value in case of a bug that didn't bump the cutoff and cause read errors.
     907              : /// - Force set the index part to use reldir v2 (migrating/migrated).
     908              : ///
     909              : /// Some examples of unsafe patches:
     910              : /// - Force set the index part from v2 to v1 (legacy). This will cause the code path to ignore anything written to the new keyspace and cause
     911              : ///   errors.
     912              : /// - Decrease the gc_cutoff without validating the data really exists. It will cause read errors in the background.
     913            0 : async fn timeline_patch_index_part_handler(
     914            0 :     mut request: Request<Body>,
     915            0 :     _cancel: CancellationToken,
     916            0 : ) -> Result<Response<Body>, ApiError> {
     917            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     918            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     919              : 
     920            0 :     let request_data: TimelinePatchIndexPartRequest = json_request(&mut request).await?;
     921            0 :     check_permission(&request, None)?; // require global permission for this request
     922            0 :     let state = get_state(&request);
     923              : 
     924            0 :     async {
     925            0 :         let timeline =
     926            0 :             active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
     927            0 :                 .await?;
     928              : 
     929            0 :         if let Some(rel_size_migration) = request_data.rel_size_migration {
     930            0 :             timeline
     931            0 :                 .update_rel_size_v2_status(rel_size_migration)
     932            0 :                 .map_err(ApiError::InternalServerError)?;
     933            0 :         }
     934              : 
     935            0 :         if let Some(gc_compaction_last_completed_lsn) =
     936            0 :             request_data.gc_compaction_last_completed_lsn
     937              :         {
     938            0 :             timeline
     939            0 :                 .update_gc_compaction_state(GcCompactionState {
     940            0 :                     last_completed_lsn: gc_compaction_last_completed_lsn,
     941            0 :                 })
     942            0 :                 .map_err(ApiError::InternalServerError)?;
     943            0 :         }
     944              : 
     945            0 :         if let Some(applied_gc_cutoff_lsn) = request_data.applied_gc_cutoff_lsn {
     946            0 :             {
     947            0 :                 let guard = timeline.applied_gc_cutoff_lsn.lock_for_write();
     948            0 :                 guard.store_and_unlock(applied_gc_cutoff_lsn);
     949            0 :             }
     950            0 :         }
     951              : 
     952            0 :         if request_data.force_index_update {
     953            0 :             timeline
     954            0 :                 .remote_client
     955            0 :                 .force_schedule_index_upload()
     956            0 :                 .context("force schedule index upload")
     957            0 :                 .map_err(ApiError::InternalServerError)?;
     958            0 :         }
     959              : 
     960            0 :         Ok::<_, ApiError>(())
     961            0 :     }
     962            0 :     .instrument(info_span!("timeline_patch_index_part",
     963              :                 tenant_id = %tenant_shard_id.tenant_id,
     964            0 :                 shard_id = %tenant_shard_id.shard_slug(),
     965              :                 %timeline_id))
     966            0 :     .await?;
     967              : 
     968            0 :     json_response(StatusCode::OK, ())
     969            0 : }
     970              : 
     971            0 : async fn timeline_detail_handler(
     972            0 :     request: Request<Body>,
     973            0 :     _cancel: CancellationToken,
     974            0 : ) -> Result<Response<Body>, ApiError> {
     975            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
     976            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
     977            0 :     let include_non_incremental_logical_size: Option<bool> =
     978            0 :         parse_query_param(&request, "include-non-incremental-logical-size")?;
     979            0 :     let force_await_initial_logical_size: Option<bool> =
     980            0 :         parse_query_param(&request, "force-await-initial-logical-size")?;
     981              :     // HADRON
     982            0 :     let include_image_consistent_lsn: Option<bool> =
     983            0 :         parse_query_param(&request, "include-image-consistent-lsn")?;
     984            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
     985              : 
     986              :     // Logical size calculation needs downloading.
     987            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
     988            0 :     let state = get_state(&request);
     989              : 
     990            0 :     let timeline_info = async {
     991            0 :         let tenant = state
     992            0 :             .tenant_manager
     993            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
     994              : 
     995            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
     996              : 
     997            0 :         let timeline = tenant.get_timeline(timeline_id, false)?;
     998            0 :         let ctx = &ctx.with_scope_timeline(&timeline);
     999              : 
    1000            0 :         let timeline_info = build_timeline_info(
    1001            0 :             &timeline,
    1002            0 :             include_non_incremental_logical_size.unwrap_or(false),
    1003            0 :             force_await_initial_logical_size.unwrap_or(false),
    1004            0 :             include_image_consistent_lsn.unwrap_or(false),
    1005            0 :             ctx,
    1006            0 :         )
    1007            0 :         .await
    1008            0 :         .context("get local timeline info")
    1009            0 :         .map_err(ApiError::InternalServerError)?;
    1010              : 
    1011            0 :         Ok::<_, ApiError>(timeline_info)
    1012            0 :     }
    1013            0 :     .instrument(info_span!("timeline_detail",
    1014              :                 tenant_id = %tenant_shard_id.tenant_id,
    1015            0 :                 shard_id = %tenant_shard_id.shard_slug(),
    1016              :                 %timeline_id))
    1017            0 :     .await?;
    1018              : 
    1019            0 :     json_response(StatusCode::OK, timeline_info)
    1020            0 : }
    1021              : 
    1022            0 : async fn get_lsn_by_timestamp_handler(
    1023            0 :     request: Request<Body>,
    1024            0 :     cancel: CancellationToken,
    1025            0 : ) -> Result<Response<Body>, ApiError> {
    1026            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1027            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1028            0 :     let state = get_state(&request);
    1029              : 
    1030            0 :     if !tenant_shard_id.is_shard_zero() {
    1031              :         // Requires SLRU contents, which are only stored on shard zero
    1032            0 :         return Err(ApiError::BadRequest(anyhow!(
    1033            0 :             "Lsn calculations by timestamp are only available on shard zero"
    1034            0 :         )));
    1035            0 :     }
    1036              : 
    1037            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1038            0 :     let timestamp_raw = must_get_query_param(&request, "timestamp")?;
    1039            0 :     let timestamp = humantime::parse_rfc3339(&timestamp_raw)
    1040            0 :         .with_context(|| format!("Invalid time: {timestamp_raw:?}"))
    1041            0 :         .map_err(ApiError::BadRequest)?;
    1042            0 :     let timestamp_pg = postgres_ffi::to_pg_timestamp(timestamp);
    1043              : 
    1044            0 :     let with_lease = parse_query_param(&request, "with_lease")?.unwrap_or(false);
    1045              : 
    1046            0 :     let timeline =
    1047            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1048            0 :             .await?;
    1049            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download)
    1050            0 :         .with_scope_timeline(&timeline);
    1051            0 :     let result = timeline
    1052            0 :         .find_lsn_for_timestamp(timestamp_pg, &cancel, &ctx)
    1053            0 :         .await?;
    1054              : 
    1055              :     #[derive(serde::Serialize, Debug)]
    1056              :     struct Result {
    1057              :         lsn: Lsn,
    1058              :         kind: &'static str,
    1059              :         #[serde(default)]
    1060              :         #[serde(skip_serializing_if = "Option::is_none")]
    1061              :         #[serde(flatten)]
    1062              :         lease: Option<LsnLease>,
    1063              :     }
    1064            0 :     let (lsn, kind) = match result {
    1065            0 :         LsnForTimestamp::Present(lsn) => (lsn, "present"),
    1066            0 :         LsnForTimestamp::Future(lsn) => (lsn, "future"),
    1067            0 :         LsnForTimestamp::Past(lsn) => (lsn, "past"),
    1068            0 :         LsnForTimestamp::NoData(lsn) => (lsn, "nodata"),
    1069              :     };
    1070              : 
    1071            0 :     let lease = if with_lease {
    1072            0 :         timeline
    1073            0 :             .init_lsn_lease(lsn, timeline.get_lsn_lease_length_for_ts(), &ctx)
    1074            0 :             .inspect_err(|_| {
    1075            0 :                 warn!("fail to grant a lease to {}", lsn);
    1076            0 :             })
    1077            0 :             .ok()
    1078              :     } else {
    1079            0 :         None
    1080              :     };
    1081              : 
    1082            0 :     let result = Result { lsn, kind, lease };
    1083            0 :     let valid_until = result
    1084            0 :         .lease
    1085            0 :         .as_ref()
    1086            0 :         .map(|l| humantime::format_rfc3339_millis(l.valid_until).to_string());
    1087            0 :     tracing::info!(
    1088              :         lsn=?result.lsn,
    1089              :         kind=%result.kind,
    1090              :         timestamp=%timestamp_raw,
    1091              :         valid_until=?valid_until,
    1092            0 :         "lsn_by_timestamp finished"
    1093              :     );
    1094            0 :     json_response(StatusCode::OK, result)
    1095            0 : }
    1096              : 
    1097            0 : async fn get_timestamp_of_lsn_handler(
    1098            0 :     request: Request<Body>,
    1099            0 :     _cancel: CancellationToken,
    1100            0 : ) -> Result<Response<Body>, ApiError> {
    1101            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1102            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1103            0 :     let state = get_state(&request);
    1104              : 
    1105            0 :     if !tenant_shard_id.is_shard_zero() {
    1106              :         // Requires SLRU contents, which are only stored on shard zero
    1107            0 :         return Err(ApiError::BadRequest(anyhow!(
    1108            0 :             "Timestamp calculations by lsn are only available on shard zero"
    1109            0 :         )));
    1110            0 :     }
    1111              : 
    1112            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1113              : 
    1114            0 :     let lsn_str = must_get_query_param(&request, "lsn")?;
    1115            0 :     let lsn = Lsn::from_str(&lsn_str)
    1116            0 :         .with_context(|| format!("Invalid LSN: {lsn_str:?}"))
    1117            0 :         .map_err(ApiError::BadRequest)?;
    1118              : 
    1119            0 :     let timeline =
    1120            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1121            0 :             .await?;
    1122            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download)
    1123            0 :         .with_scope_timeline(&timeline);
    1124            0 :     let result = timeline.get_timestamp_for_lsn(lsn, &ctx).await?;
    1125              : 
    1126            0 :     match result {
    1127            0 :         Some(time) => {
    1128            0 :             let time = format_rfc3339(
    1129            0 :                 postgres_ffi::try_from_pg_timestamp(time).map_err(ApiError::InternalServerError)?,
    1130              :             )
    1131            0 :             .to_string();
    1132            0 :             json_response(StatusCode::OK, time)
    1133              :         }
    1134            0 :         None => Err(ApiError::PreconditionFailed(
    1135            0 :             format!("Timestamp for lsn {lsn} not found").into(),
    1136            0 :         )),
    1137              :     }
    1138            0 : }
    1139              : 
    1140            0 : async fn timeline_delete_handler(
    1141            0 :     request: Request<Body>,
    1142            0 :     _cancel: CancellationToken,
    1143            0 : ) -> Result<Response<Body>, ApiError> {
    1144            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1145            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1146            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1147              : 
    1148            0 :     let state = get_state(&request);
    1149              : 
    1150            0 :     let tenant = state
    1151            0 :         .tenant_manager
    1152            0 :         .get_attached_tenant_shard(tenant_shard_id)
    1153            0 :         .map_err(|e| {
    1154            0 :             match e {
    1155              :                 // GetTenantError has a built-in conversion to ApiError, but in this context we don't
    1156              :                 // want to treat missing tenants as 404, to avoid ambiguity with successful deletions.
    1157              :                 GetTenantError::NotFound(_) | GetTenantError::ShardNotFound(_) => {
    1158            0 :                     ApiError::PreconditionFailed(
    1159            0 :                         "Requested tenant is missing".to_string().into_boxed_str(),
    1160            0 :                     )
    1161              :                 }
    1162            0 :                 e => e.into(),
    1163              :             }
    1164            0 :         })?;
    1165            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1166            0 :     tenant.delete_timeline(timeline_id).instrument(info_span!("timeline_delete", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), %timeline_id))
    1167            0 :         .await?;
    1168              : 
    1169            0 :     json_response(StatusCode::ACCEPTED, ())
    1170            0 : }
    1171              : 
    1172            0 : async fn tenant_reset_handler(
    1173            0 :     request: Request<Body>,
    1174            0 :     _cancel: CancellationToken,
    1175            0 : ) -> Result<Response<Body>, ApiError> {
    1176            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1177            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1178              : 
    1179            0 :     let drop_cache: Option<bool> = parse_query_param(&request, "drop_cache")?;
    1180              : 
    1181            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
    1182            0 :     let state = get_state(&request);
    1183            0 :     state
    1184            0 :         .tenant_manager
    1185            0 :         .reset_tenant(tenant_shard_id, drop_cache.unwrap_or(false), &ctx)
    1186            0 :         .await
    1187            0 :         .map_err(ApiError::InternalServerError)?;
    1188              : 
    1189            0 :     json_response(StatusCode::OK, ())
    1190            0 : }
    1191              : 
    1192            0 : async fn tenant_list_handler(
    1193            0 :     request: Request<Body>,
    1194            0 :     _cancel: CancellationToken,
    1195            0 : ) -> Result<Response<Body>, ApiError> {
    1196            0 :     check_permission(&request, None)?;
    1197            0 :     let state = get_state(&request);
    1198              : 
    1199            0 :     let response_data = state
    1200            0 :         .tenant_manager
    1201            0 :         .list_tenants()
    1202            0 :         .map_err(|_| {
    1203            0 :             ApiError::ResourceUnavailable("Tenant map is initializing or shutting down".into())
    1204            0 :         })?
    1205            0 :         .iter()
    1206            0 :         .map(|(id, state, gen_)| TenantInfo {
    1207            0 :             id: *id,
    1208            0 :             state: state.clone(),
    1209            0 :             current_physical_size: None,
    1210            0 :             attachment_status: state.attachment_status(),
    1211            0 :             generation: (*gen_)
    1212            0 :                 .into()
    1213            0 :                 .expect("Tenants are always attached with a generation"),
    1214            0 :             gc_blocking: None,
    1215            0 :         })
    1216            0 :         .collect::<Vec<TenantInfo>>();
    1217              : 
    1218            0 :     json_response(StatusCode::OK, response_data)
    1219            0 : }
    1220              : 
    1221            0 : async fn tenant_status(
    1222            0 :     request: Request<Body>,
    1223            0 :     _cancel: CancellationToken,
    1224            0 : ) -> Result<Response<Body>, ApiError> {
    1225            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1226            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1227            0 :     let state = get_state(&request);
    1228              : 
    1229              :     // In tests, sometimes we want to query the state of a tenant without auto-activating it if it's currently waiting.
    1230            0 :     let activate = true;
    1231              :     #[cfg(feature = "testing")]
    1232            0 :     let activate = parse_query_param(&request, "activate")?.unwrap_or(activate);
    1233              : 
    1234            0 :     let tenant_info = async {
    1235            0 :         let tenant = state
    1236            0 :             .tenant_manager
    1237            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    1238              : 
    1239            0 :         if activate {
    1240              :             // This is advisory: we prefer to let the tenant activate on-demand when this function is
    1241              :             // called, but it is still valid to return 200 and describe the current state of the tenant
    1242              :             // if it doesn't make it into an active state.
    1243            0 :             tenant
    1244            0 :                 .wait_to_become_active(ACTIVE_TENANT_TIMEOUT)
    1245            0 :                 .await
    1246            0 :                 .ok();
    1247            0 :         }
    1248              : 
    1249              :         // Calculate total physical size of all timelines
    1250            0 :         let mut current_physical_size = 0;
    1251            0 :         for timeline in tenant.list_timelines().iter() {
    1252            0 :             current_physical_size += timeline.layer_size_sum().await;
    1253              :         }
    1254              : 
    1255            0 :         let state = tenant.current_state();
    1256              :         Result::<_, ApiError>::Ok(TenantDetails {
    1257              :             tenant_info: TenantInfo {
    1258            0 :                 id: tenant_shard_id,
    1259            0 :                 state: state.clone(),
    1260            0 :                 current_physical_size: Some(current_physical_size),
    1261            0 :                 attachment_status: state.attachment_status(),
    1262            0 :                 generation: tenant
    1263            0 :                     .generation()
    1264            0 :                     .into()
    1265            0 :                     .expect("Tenants are always attached with a generation"),
    1266            0 :                 gc_blocking: tenant.gc_block.summary().map(|x| format!("{x:?}")),
    1267              :             },
    1268            0 :             walredo: tenant.wal_redo_manager_status(),
    1269            0 :             timelines: tenant.list_timeline_ids(),
    1270              :         })
    1271            0 :     }
    1272            0 :     .instrument(info_span!("tenant_status_handler",
    1273              :                 tenant_id = %tenant_shard_id.tenant_id,
    1274            0 :                 shard_id = %tenant_shard_id.shard_slug()))
    1275            0 :     .await?;
    1276              : 
    1277            0 :     json_response(StatusCode::OK, tenant_info)
    1278            0 : }
    1279              : 
    1280            0 : async fn tenant_delete_handler(
    1281            0 :     request: Request<Body>,
    1282            0 :     _cancel: CancellationToken,
    1283            0 : ) -> Result<Response<Body>, ApiError> {
    1284              :     // TODO openapi spec
    1285            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1286            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1287              : 
    1288            0 :     let state = get_state(&request);
    1289              : 
    1290            0 :     state
    1291            0 :         .tenant_manager
    1292            0 :         .delete_tenant(tenant_shard_id)
    1293            0 :         .instrument(info_span!("tenant_delete_handler",
    1294              :             tenant_id = %tenant_shard_id.tenant_id,
    1295            0 :             shard_id = %tenant_shard_id.shard_slug()
    1296              :         ))
    1297            0 :         .await?;
    1298              : 
    1299            0 :     json_response(StatusCode::OK, ())
    1300            0 : }
    1301              : 
    1302              : /// HTTP endpoint to query the current tenant_size of a tenant.
    1303              : ///
    1304              : /// This is not used by consumption metrics under [`crate::consumption_metrics`], but can be used
    1305              : /// to debug any of the calculations. Requires `tenant_id` request parameter, supports
    1306              : /// `inputs_only=true|false` (default false) which supports debugging failure to calculate model
    1307              : /// values.
    1308              : ///
    1309              : /// 'retention_period' query parameter overrides the cutoff that is used to calculate the size
    1310              : /// (only if it is shorter than the real cutoff).
    1311              : ///
    1312              : /// Note: we don't update the cached size and prometheus metric here.
    1313              : /// The retention period might be different, and it's nice to have a method to just calculate it
    1314              : /// without modifying anything anyway.
    1315            0 : async fn tenant_size_handler(
    1316            0 :     request: Request<Body>,
    1317            0 :     cancel: CancellationToken,
    1318            0 : ) -> Result<Response<Body>, ApiError> {
    1319            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1320            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1321            0 :     let inputs_only: Option<bool> = parse_query_param(&request, "inputs_only")?;
    1322            0 :     let retention_period: Option<u64> = parse_query_param(&request, "retention_period")?;
    1323            0 :     let headers = request.headers();
    1324            0 :     let state = get_state(&request);
    1325              : 
    1326            0 :     if !tenant_shard_id.is_shard_zero() {
    1327            0 :         return Err(ApiError::BadRequest(anyhow!(
    1328            0 :             "Size calculations are only available on shard zero"
    1329            0 :         )));
    1330            0 :     }
    1331              : 
    1332            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    1333            0 :     let tenant = state
    1334            0 :         .tenant_manager
    1335            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1336            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1337              : 
    1338              :     // this can be long operation
    1339            0 :     let inputs = tenant
    1340            0 :         .gather_size_inputs(
    1341            0 :             retention_period,
    1342            0 :             LogicalSizeCalculationCause::TenantSizeHandler,
    1343            0 :             &cancel,
    1344            0 :             &ctx,
    1345            0 :         )
    1346            0 :         .await
    1347            0 :         .map_err(|e| match e {
    1348            0 :             crate::tenant::size::CalculateSyntheticSizeError::Cancelled => ApiError::ShuttingDown,
    1349            0 :             other => ApiError::InternalServerError(anyhow::anyhow!(other)),
    1350            0 :         })?;
    1351              : 
    1352            0 :     let mut sizes = None;
    1353            0 :     let accepts_html = headers
    1354            0 :         .get(header::ACCEPT)
    1355            0 :         .map(|v| v == "text/html")
    1356            0 :         .unwrap_or_default();
    1357            0 :     if !inputs_only.unwrap_or(false) {
    1358            0 :         let storage_model = inputs.calculate_model();
    1359            0 :         let size = storage_model.calculate();
    1360              : 
    1361              :         // If request header expects html, return html
    1362            0 :         if accepts_html {
    1363            0 :             return synthetic_size_html_response(inputs, storage_model, size);
    1364            0 :         }
    1365            0 :         sizes = Some(size);
    1366            0 :     } else if accepts_html {
    1367            0 :         return Err(ApiError::BadRequest(anyhow!(
    1368            0 :             "inputs_only parameter is incompatible with html output request"
    1369            0 :         )));
    1370            0 :     }
    1371              : 
    1372              :     /// The type resides in the pageserver not to expose `ModelInputs`.
    1373              :     #[derive(serde::Serialize)]
    1374              :     struct TenantHistorySize {
    1375              :         id: TenantId,
    1376              :         /// Size is a mixture of WAL and logical size, so the unit is bytes.
    1377              :         ///
    1378              :         /// Will be none if `?inputs_only=true` was given.
    1379              :         size: Option<u64>,
    1380              :         /// Size of each segment used in the model.
    1381              :         /// Will be null if `?inputs_only=true` was given.
    1382              :         segment_sizes: Option<Vec<tenant_size_model::SegmentSizeResult>>,
    1383              :         inputs: crate::tenant::size::ModelInputs,
    1384              :     }
    1385              : 
    1386            0 :     json_response(
    1387              :         StatusCode::OK,
    1388              :         TenantHistorySize {
    1389            0 :             id: tenant_shard_id.tenant_id,
    1390            0 :             size: sizes.as_ref().map(|x| x.total_size),
    1391            0 :             segment_sizes: sizes.map(|x| x.segments),
    1392            0 :             inputs,
    1393              :         },
    1394              :     )
    1395            0 : }
    1396              : 
    1397            0 : async fn tenant_shard_split_handler(
    1398            0 :     mut request: Request<Body>,
    1399            0 :     _cancel: CancellationToken,
    1400            0 : ) -> Result<Response<Body>, ApiError> {
    1401            0 :     let req: TenantShardSplitRequest = json_request(&mut request).await?;
    1402              : 
    1403            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1404            0 :     let state = get_state(&request);
    1405            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
    1406              : 
    1407            0 :     let tenant = state
    1408            0 :         .tenant_manager
    1409            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1410            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1411              : 
    1412            0 :     let new_shards = state
    1413            0 :         .tenant_manager
    1414            0 :         .shard_split(
    1415            0 :             tenant,
    1416            0 :             ShardCount::new(req.new_shard_count),
    1417            0 :             req.new_stripe_size,
    1418            0 :             &ctx,
    1419            0 :         )
    1420            0 :         .await
    1421            0 :         .map_err(ApiError::InternalServerError)?;
    1422              : 
    1423            0 :     json_response(StatusCode::OK, TenantShardSplitResponse { new_shards })
    1424            0 : }
    1425              : 
    1426            0 : async fn layer_map_info_handler(
    1427            0 :     request: Request<Body>,
    1428            0 :     _cancel: CancellationToken,
    1429            0 : ) -> Result<Response<Body>, ApiError> {
    1430            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1431            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1432            0 :     let reset: LayerAccessStatsReset =
    1433            0 :         parse_query_param(&request, "reset")?.unwrap_or(LayerAccessStatsReset::NoReset);
    1434            0 :     let state = get_state(&request);
    1435              : 
    1436            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1437              : 
    1438            0 :     let timeline =
    1439            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1440            0 :             .await?;
    1441            0 :     let layer_map_info = timeline
    1442            0 :         .layer_map_info(reset)
    1443            0 :         .await
    1444            0 :         .map_err(|_shutdown| ApiError::ShuttingDown)?;
    1445              : 
    1446            0 :     json_response(StatusCode::OK, layer_map_info)
    1447            0 : }
    1448              : 
    1449              : #[instrument(skip_all, fields(tenant_id, shard_id, timeline_id, layer_name))]
    1450              : async fn timeline_layer_scan_disposable_keys(
    1451              :     request: Request<Body>,
    1452              :     cancel: CancellationToken,
    1453              : ) -> Result<Response<Body>, ApiError> {
    1454              :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1455              :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1456              :     let layer_name: LayerName = parse_request_param(&request, "layer_name")?;
    1457              : 
    1458              :     tracing::Span::current().record(
    1459              :         "tenant_id",
    1460              :         tracing::field::display(&tenant_shard_id.tenant_id),
    1461              :     );
    1462              :     tracing::Span::current().record(
    1463              :         "shard_id",
    1464              :         tracing::field::display(tenant_shard_id.shard_slug()),
    1465              :     );
    1466              :     tracing::Span::current().record("timeline_id", tracing::field::display(&timeline_id));
    1467              :     tracing::Span::current().record("layer_name", tracing::field::display(&layer_name));
    1468              : 
    1469              :     let state = get_state(&request);
    1470              : 
    1471              :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1472              : 
    1473              :     // technically the timeline need not be active for this scan to complete
    1474              :     let timeline =
    1475              :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1476              :             .await?;
    1477              : 
    1478              :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download)
    1479              :         .with_scope_timeline(&timeline);
    1480              : 
    1481              :     let guard = timeline
    1482              :         .layers
    1483              :         .read(LayerManagerLockHolder::GetLayerMapInfo)
    1484              :         .await;
    1485              :     let Some(layer) = guard.try_get_from_key(&layer_name.clone().into()) else {
    1486              :         return Err(ApiError::NotFound(
    1487              :             anyhow::anyhow!("Layer {tenant_shard_id}/{timeline_id}/{layer_name} not found").into(),
    1488              :         ));
    1489              :     };
    1490              : 
    1491              :     let resident_layer = layer
    1492              :         .download_and_keep_resident(&ctx)
    1493              :         .await
    1494            0 :         .map_err(|err| match err {
    1495              :             tenant::storage_layer::layer::DownloadError::TimelineShutdown
    1496              :             | tenant::storage_layer::layer::DownloadError::DownloadCancelled => {
    1497            0 :                 ApiError::ShuttingDown
    1498              :             }
    1499              :             tenant::storage_layer::layer::DownloadError::ContextAndConfigReallyDeniesDownloads
    1500              :             | tenant::storage_layer::layer::DownloadError::DownloadRequired
    1501              :             | tenant::storage_layer::layer::DownloadError::NotFile(_)
    1502              :             | tenant::storage_layer::layer::DownloadError::DownloadFailed
    1503              :             | tenant::storage_layer::layer::DownloadError::PreStatFailed(_) => {
    1504            0 :                 ApiError::InternalServerError(err.into())
    1505              :             }
    1506              :             #[cfg(test)]
    1507              :             tenant::storage_layer::layer::DownloadError::Failpoint(_) => {
    1508            0 :                 ApiError::InternalServerError(err.into())
    1509              :             }
    1510            0 :         })?;
    1511              : 
    1512              :     let keys = resident_layer
    1513              :         .load_keys(&ctx)
    1514              :         .await
    1515              :         .map_err(ApiError::InternalServerError)?;
    1516              : 
    1517              :     let shard_identity = timeline.get_shard_identity();
    1518              : 
    1519              :     let mut disposable_count = 0;
    1520              :     let mut not_disposable_count = 0;
    1521              :     let cancel = cancel.clone();
    1522              :     for (i, key) in keys.into_iter().enumerate() {
    1523              :         if shard_identity.is_key_disposable(&key) {
    1524              :             disposable_count += 1;
    1525              :             tracing::debug!(key = %key, key.dbg=?key, "disposable key");
    1526              :         } else {
    1527              :             not_disposable_count += 1;
    1528              :         }
    1529              :         #[allow(clippy::collapsible_if)]
    1530              :         if i % 10000 == 0 {
    1531              :             if cancel.is_cancelled() || timeline.cancel.is_cancelled() || timeline.is_stopping() {
    1532              :                 return Err(ApiError::ShuttingDown);
    1533              :             }
    1534              :         }
    1535              :     }
    1536              : 
    1537              :     json_response(
    1538              :         StatusCode::OK,
    1539              :         pageserver_api::models::ScanDisposableKeysResponse {
    1540              :             disposable_count,
    1541              :             not_disposable_count,
    1542              :         },
    1543              :     )
    1544              : }
    1545              : 
    1546            0 : async fn timeline_download_heatmap_layers_handler(
    1547            0 :     request: Request<Body>,
    1548            0 :     _cancel: CancellationToken,
    1549            0 : ) -> Result<Response<Body>, ApiError> {
    1550              :     // Only used in the case where remote storage is not configured.
    1551              :     const DEFAULT_MAX_CONCURRENCY: usize = 100;
    1552              :     // A conservative default.
    1553              :     const DEFAULT_CONCURRENCY: usize = 16;
    1554              : 
    1555            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1556            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1557              : 
    1558            0 :     let desired_concurrency =
    1559            0 :         parse_query_param(&request, "concurrency")?.unwrap_or(DEFAULT_CONCURRENCY);
    1560            0 :     let recurse = parse_query_param(&request, "recurse")?.unwrap_or(false);
    1561              : 
    1562            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1563              : 
    1564            0 :     let state = get_state(&request);
    1565            0 :     let timeline =
    1566            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1567            0 :             .await?;
    1568            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download)
    1569            0 :         .with_scope_timeline(&timeline);
    1570              : 
    1571            0 :     let max_concurrency = get_config(&request)
    1572            0 :         .remote_storage_config
    1573            0 :         .as_ref()
    1574            0 :         .map(|c| c.concurrency_limit())
    1575            0 :         .unwrap_or(DEFAULT_MAX_CONCURRENCY);
    1576            0 :     let concurrency = std::cmp::min(max_concurrency, desired_concurrency);
    1577              : 
    1578            0 :     timeline.start_heatmap_layers_download(concurrency, recurse, &ctx)?;
    1579              : 
    1580            0 :     json_response(StatusCode::ACCEPTED, ())
    1581            0 : }
    1582              : 
    1583            0 : async fn timeline_shutdown_download_heatmap_layers_handler(
    1584            0 :     request: Request<Body>,
    1585            0 :     _cancel: CancellationToken,
    1586            0 : ) -> Result<Response<Body>, ApiError> {
    1587            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1588            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1589              : 
    1590            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1591              : 
    1592            0 :     let state = get_state(&request);
    1593            0 :     let timeline =
    1594            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1595            0 :             .await?;
    1596              : 
    1597            0 :     timeline.stop_and_drain_heatmap_layers_download().await;
    1598              : 
    1599            0 :     json_response(StatusCode::OK, ())
    1600            0 : }
    1601              : 
    1602            0 : async fn layer_download_handler(
    1603            0 :     request: Request<Body>,
    1604            0 :     _cancel: CancellationToken,
    1605            0 : ) -> Result<Response<Body>, ApiError> {
    1606            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1607            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1608            0 :     let layer_file_name = get_request_param(&request, "layer_file_name")?;
    1609            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1610            0 :     let layer_name = LayerName::from_str(layer_file_name)
    1611            0 :         .map_err(|s| ApiError::BadRequest(anyhow::anyhow!(s)))?;
    1612            0 :     let state = get_state(&request);
    1613              : 
    1614            0 :     let timeline =
    1615            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1616            0 :             .await?;
    1617            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download)
    1618            0 :         .with_scope_timeline(&timeline);
    1619            0 :     let downloaded = timeline
    1620            0 :         .download_layer(&layer_name, &ctx)
    1621            0 :         .await
    1622            0 :         .map_err(|e| match e {
    1623              :             tenant::storage_layer::layer::DownloadError::TimelineShutdown
    1624              :             | tenant::storage_layer::layer::DownloadError::DownloadCancelled => {
    1625            0 :                 ApiError::ShuttingDown
    1626              :             }
    1627            0 :             other => ApiError::InternalServerError(other.into()),
    1628            0 :         })?;
    1629              : 
    1630            0 :     match downloaded {
    1631            0 :         Some(true) => json_response(StatusCode::OK, ()),
    1632            0 :         Some(false) => json_response(StatusCode::NOT_MODIFIED, ()),
    1633            0 :         None => json_response(
    1634              :             StatusCode::BAD_REQUEST,
    1635            0 :             format!("Layer {tenant_shard_id}/{timeline_id}/{layer_file_name} not found"),
    1636              :         ),
    1637              :     }
    1638            0 : }
    1639              : 
    1640            0 : async fn evict_timeline_layer_handler(
    1641            0 :     request: Request<Body>,
    1642            0 :     _cancel: CancellationToken,
    1643            0 : ) -> Result<Response<Body>, ApiError> {
    1644            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1645            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1646            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1647            0 :     let layer_file_name = get_request_param(&request, "layer_file_name")?;
    1648            0 :     let state = get_state(&request);
    1649              : 
    1650            0 :     let layer_name = LayerName::from_str(layer_file_name)
    1651            0 :         .map_err(|s| ApiError::BadRequest(anyhow::anyhow!(s)))?;
    1652              : 
    1653            0 :     let timeline =
    1654            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1655            0 :             .await?;
    1656            0 :     let evicted = timeline
    1657            0 :         .evict_layer(&layer_name)
    1658            0 :         .await
    1659            0 :         .map_err(ApiError::InternalServerError)?;
    1660              : 
    1661            0 :     match evicted {
    1662            0 :         Some(true) => json_response(StatusCode::OK, ()),
    1663            0 :         Some(false) => json_response(StatusCode::NOT_MODIFIED, ()),
    1664            0 :         None => json_response(
    1665              :             StatusCode::BAD_REQUEST,
    1666            0 :             format!("Layer {tenant_shard_id}/{timeline_id}/{layer_file_name} not found"),
    1667              :         ),
    1668              :     }
    1669            0 : }
    1670              : 
    1671            0 : async fn timeline_gc_blocking_handler(
    1672            0 :     request: Request<Body>,
    1673            0 :     _cancel: CancellationToken,
    1674            0 : ) -> Result<Response<Body>, ApiError> {
    1675            0 :     block_or_unblock_gc(request, true).await
    1676            0 : }
    1677              : 
    1678            0 : async fn timeline_gc_unblocking_handler(
    1679            0 :     request: Request<Body>,
    1680            0 :     _cancel: CancellationToken,
    1681            0 : ) -> Result<Response<Body>, ApiError> {
    1682            0 :     block_or_unblock_gc(request, false).await
    1683            0 : }
    1684              : 
    1685              : /// Traces GetPage@LSN requests for a timeline, and emits metadata in an efficient binary encoding.
    1686              : /// Use the `pagectl page-trace` command to decode and analyze the output.
    1687            0 : async fn timeline_page_trace_handler(
    1688            0 :     request: Request<Body>,
    1689            0 :     cancel: CancellationToken,
    1690            0 : ) -> Result<Response<Body>, ApiError> {
    1691            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1692            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1693            0 :     let state = get_state(&request);
    1694            0 :     check_permission(&request, None)?;
    1695              : 
    1696            0 :     let size_limit: usize = parse_query_param(&request, "size_limit_bytes")?.unwrap_or(1024 * 1024);
    1697            0 :     let time_limit_secs: u64 = parse_query_param(&request, "time_limit_secs")?.unwrap_or(5);
    1698              : 
    1699              :     // Convert size limit to event limit based on the serialized size of an event. The event size is
    1700              :     // fixed, as the default bincode serializer uses fixed-width integer encoding.
    1701            0 :     let event_size = bincode::serialize(&PageTraceEvent::default())
    1702            0 :         .map_err(|err| ApiError::InternalServerError(err.into()))?
    1703            0 :         .len();
    1704            0 :     let event_limit = size_limit / event_size;
    1705              : 
    1706            0 :     let timeline =
    1707            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    1708            0 :             .await?;
    1709              : 
    1710              :     // Install a page trace, unless one is already in progress. We just use a buffered channel,
    1711              :     // which may 2x the memory usage in the worst case, but it's still bounded.
    1712            0 :     let (trace_tx, mut trace_rx) = tokio::sync::mpsc::channel(event_limit);
    1713            0 :     let cur = timeline.page_trace.load();
    1714            0 :     let installed = cur.is_none()
    1715            0 :         && timeline
    1716            0 :             .page_trace
    1717            0 :             .compare_and_swap(cur, Some(Arc::new(trace_tx)))
    1718            0 :             .is_none();
    1719            0 :     if !installed {
    1720            0 :         return Err(ApiError::Conflict("page trace already active".to_string()));
    1721            0 :     }
    1722            0 :     defer!(timeline.page_trace.store(None)); // uninstall on return
    1723              : 
    1724              :     // Collect the trace and return it to the client. We could stream the response, but this is
    1725              :     // simple and fine.
    1726            0 :     let mut body = Vec::with_capacity(size_limit);
    1727            0 :     let deadline = Instant::now() + Duration::from_secs(time_limit_secs);
    1728              : 
    1729            0 :     while body.len() < size_limit {
    1730            0 :         tokio::select! {
    1731            0 :             event = trace_rx.recv() => {
    1732            0 :                 let Some(event) = event else {
    1733            0 :                     break; // shouldn't happen (sender doesn't close, unless timeline dropped)
    1734              :                 };
    1735            0 :                 bincode::serialize_into(&mut body, &event)
    1736            0 :                     .map_err(|err| ApiError::InternalServerError(err.into()))?;
    1737              :             }
    1738            0 :             _ = tokio::time::sleep_until(deadline) => break, // time limit reached
    1739            0 :             _ = cancel.cancelled() => return Err(ApiError::Cancelled),
    1740              :         }
    1741              :     }
    1742              : 
    1743            0 :     Ok(Response::builder()
    1744            0 :         .status(StatusCode::OK)
    1745            0 :         .header(header::CONTENT_TYPE, "application/octet-stream")
    1746            0 :         .body(hyper::Body::from(body))
    1747            0 :         .unwrap())
    1748            0 : }
    1749              : 
    1750              : /// Adding a block is `POST ../block_gc`, removing a block is `POST ../unblock_gc`.
    1751              : ///
    1752              : /// Both are technically unsafe because they might fire off index uploads, thus they are POST.
    1753            0 : async fn block_or_unblock_gc(
    1754            0 :     request: Request<Body>,
    1755            0 :     block: bool,
    1756            0 : ) -> Result<Response<Body>, ApiError> {
    1757              :     use crate::tenant::remote_timeline_client::WaitCompletionError;
    1758              :     use crate::tenant::upload_queue::NotInitialized;
    1759            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1760            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1761            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    1762            0 :     let state = get_state(&request);
    1763              : 
    1764            0 :     let tenant = state
    1765            0 :         .tenant_manager
    1766            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1767              : 
    1768            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1769              : 
    1770            0 :     let timeline = tenant.get_timeline(timeline_id, true)?;
    1771              : 
    1772            0 :     let fut = async {
    1773            0 :         if block {
    1774            0 :             timeline.block_gc(&tenant).await.map(|_| ())
    1775              :         } else {
    1776            0 :             timeline.unblock_gc(&tenant).await
    1777              :         }
    1778            0 :     };
    1779              : 
    1780            0 :     let span = tracing::info_span!(
    1781              :         "block_or_unblock_gc",
    1782              :         tenant_id = %tenant_shard_id.tenant_id,
    1783            0 :         shard_id = %tenant_shard_id.shard_slug(),
    1784              :         timeline_id = %timeline_id,
    1785              :         block = block,
    1786              :     );
    1787              : 
    1788            0 :     let res = fut.instrument(span).await;
    1789              : 
    1790            0 :     res.map_err(|e| {
    1791            0 :         if e.is::<NotInitialized>() || e.is::<WaitCompletionError>() {
    1792            0 :             ApiError::ShuttingDown
    1793              :         } else {
    1794            0 :             ApiError::InternalServerError(e)
    1795              :         }
    1796            0 :     })?;
    1797              : 
    1798            0 :     json_response(StatusCode::OK, ())
    1799            0 : }
    1800              : 
    1801              : /// Get tenant_size SVG graph along with the JSON data.
    1802            0 : fn synthetic_size_html_response(
    1803            0 :     inputs: ModelInputs,
    1804            0 :     storage_model: StorageModel,
    1805            0 :     sizes: SizeResult,
    1806            0 : ) -> Result<Response<Body>, ApiError> {
    1807            0 :     let mut timeline_ids: Vec<String> = Vec::new();
    1808            0 :     let mut timeline_map: HashMap<TimelineId, usize> = HashMap::new();
    1809            0 :     for (index, ti) in inputs.timeline_inputs.iter().enumerate() {
    1810            0 :         timeline_map.insert(ti.timeline_id, index);
    1811            0 :         timeline_ids.push(ti.timeline_id.to_string());
    1812            0 :     }
    1813            0 :     let seg_to_branch: Vec<(usize, SvgBranchKind)> = inputs
    1814            0 :         .segments
    1815            0 :         .iter()
    1816            0 :         .map(|seg| {
    1817            0 :             (
    1818            0 :                 *timeline_map.get(&seg.timeline_id).unwrap(),
    1819            0 :                 seg.kind.into(),
    1820            0 :             )
    1821            0 :         })
    1822            0 :         .collect();
    1823              : 
    1824            0 :     let svg =
    1825            0 :         tenant_size_model::svg::draw_svg(&storage_model, &timeline_ids, &seg_to_branch, &sizes)
    1826            0 :             .map_err(ApiError::InternalServerError)?;
    1827              : 
    1828            0 :     let mut response = String::new();
    1829              : 
    1830              :     use std::fmt::Write;
    1831            0 :     write!(response, "<html>\n<body>\n").unwrap();
    1832            0 :     write!(response, "<div>\n{svg}\n</div>").unwrap();
    1833            0 :     writeln!(response, "Project size: {}", sizes.total_size).unwrap();
    1834            0 :     writeln!(response, "<pre>").unwrap();
    1835            0 :     writeln!(
    1836            0 :         response,
    1837            0 :         "{}",
    1838            0 :         serde_json::to_string_pretty(&inputs).unwrap()
    1839              :     )
    1840            0 :     .unwrap();
    1841            0 :     writeln!(
    1842            0 :         response,
    1843            0 :         "{}",
    1844            0 :         serde_json::to_string_pretty(&sizes.segments).unwrap()
    1845              :     )
    1846            0 :     .unwrap();
    1847            0 :     writeln!(response, "</pre>").unwrap();
    1848            0 :     write!(response, "</body>\n</html>\n").unwrap();
    1849              : 
    1850            0 :     html_response(StatusCode::OK, response)
    1851            0 : }
    1852              : 
    1853            0 : pub fn html_response(status: StatusCode, data: String) -> Result<Response<Body>, ApiError> {
    1854            0 :     let response = Response::builder()
    1855            0 :         .status(status)
    1856            0 :         .header(header::CONTENT_TYPE, "text/html")
    1857            0 :         .body(Body::from(data.as_bytes().to_vec()))
    1858            0 :         .map_err(|e| ApiError::InternalServerError(e.into()))?;
    1859            0 :     Ok(response)
    1860            0 : }
    1861              : 
    1862            0 : async fn get_tenant_config_handler(
    1863            0 :     request: Request<Body>,
    1864            0 :     _cancel: CancellationToken,
    1865            0 : ) -> Result<Response<Body>, ApiError> {
    1866            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1867            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1868            0 :     let state = get_state(&request);
    1869              : 
    1870            0 :     let tenant = state
    1871            0 :         .tenant_manager
    1872            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1873              : 
    1874            0 :     let response = HashMap::from([
    1875              :         (
    1876              :             "tenant_specific_overrides",
    1877            0 :             serde_json::to_value(tenant.tenant_specific_overrides())
    1878            0 :                 .context("serializing tenant specific overrides")
    1879            0 :                 .map_err(ApiError::InternalServerError)?,
    1880              :         ),
    1881              :         (
    1882            0 :             "effective_config",
    1883            0 :             serde_json::to_value(tenant.effective_config())
    1884            0 :                 .context("serializing effective config")
    1885            0 :                 .map_err(ApiError::InternalServerError)?,
    1886              :         ),
    1887              :     ]);
    1888              : 
    1889            0 :     json_response(StatusCode::OK, response)
    1890            0 : }
    1891              : 
    1892            0 : async fn update_tenant_config_handler(
    1893            0 :     mut request: Request<Body>,
    1894            0 :     _cancel: CancellationToken,
    1895            0 : ) -> Result<Response<Body>, ApiError> {
    1896            0 :     let request_data: TenantConfigRequest = json_request(&mut request).await?;
    1897            0 :     let tenant_id = request_data.tenant_id;
    1898            0 :     check_permission(&request, Some(tenant_id))?;
    1899              : 
    1900            0 :     let new_tenant_conf = request_data.config;
    1901              : 
    1902            0 :     let state = get_state(&request);
    1903              : 
    1904            0 :     let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    1905              : 
    1906            0 :     let tenant = state
    1907            0 :         .tenant_manager
    1908            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1909            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1910              : 
    1911              :     // This is a legacy API that only operates on attached tenants: the preferred
    1912              :     // API to use is the location_config/ endpoint, which lets the caller provide
    1913              :     // the full LocationConf.
    1914            0 :     let location_conf = LocationConf::attached_single(
    1915            0 :         new_tenant_conf.clone(),
    1916            0 :         tenant.get_generation(),
    1917            0 :         ShardParameters::from(tenant.get_shard_identity()),
    1918              :     );
    1919              : 
    1920            0 :     tenant
    1921            0 :         .get_shard_identity()
    1922            0 :         .assert_equal(location_conf.shard); // not strictly necessary since we construct it above
    1923              : 
    1924            0 :     crate::tenant::TenantShard::persist_tenant_config(state.conf, &tenant_shard_id, &location_conf)
    1925            0 :         .await
    1926            0 :         .map_err(|e| ApiError::InternalServerError(anyhow::anyhow!(e)))?;
    1927              : 
    1928            0 :     let _ = tenant
    1929            0 :         .update_tenant_config(|_crnt| Ok(new_tenant_conf.clone()))
    1930            0 :         .expect("Closure returns Ok()");
    1931              : 
    1932            0 :     json_response(StatusCode::OK, ())
    1933            0 : }
    1934              : 
    1935            0 : async fn patch_tenant_config_handler(
    1936            0 :     mut request: Request<Body>,
    1937            0 :     _cancel: CancellationToken,
    1938            0 : ) -> Result<Response<Body>, ApiError> {
    1939            0 :     let request_data: TenantConfigPatchRequest = json_request(&mut request).await?;
    1940            0 :     let tenant_id = request_data.tenant_id;
    1941            0 :     check_permission(&request, Some(tenant_id))?;
    1942              : 
    1943            0 :     let state = get_state(&request);
    1944              : 
    1945            0 :     let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    1946              : 
    1947            0 :     let tenant = state
    1948            0 :         .tenant_manager
    1949            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    1950            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    1951              : 
    1952            0 :     let updated = tenant
    1953            0 :         .update_tenant_config(|crnt| {
    1954            0 :             crnt.apply_patch(request_data.config.clone())
    1955            0 :                 .map_err(anyhow::Error::new)
    1956            0 :         })
    1957            0 :         .map_err(ApiError::BadRequest)?;
    1958              : 
    1959              :     // This is a legacy API that only operates on attached tenants: the preferred
    1960              :     // API to use is the location_config/ endpoint, which lets the caller provide
    1961              :     // the full LocationConf.
    1962            0 :     let location_conf = LocationConf::attached_single(
    1963            0 :         updated,
    1964            0 :         tenant.get_generation(),
    1965            0 :         ShardParameters::from(tenant.get_shard_identity()),
    1966              :     );
    1967              : 
    1968            0 :     tenant
    1969            0 :         .get_shard_identity()
    1970            0 :         .assert_equal(location_conf.shard); // not strictly necessary since we construct it above
    1971              : 
    1972            0 :     crate::tenant::TenantShard::persist_tenant_config(state.conf, &tenant_shard_id, &location_conf)
    1973            0 :         .await
    1974            0 :         .map_err(|e| ApiError::InternalServerError(anyhow::anyhow!(e)))?;
    1975              : 
    1976            0 :     json_response(StatusCode::OK, ())
    1977            0 : }
    1978              : 
    1979            0 : async fn put_tenant_location_config_handler(
    1980            0 :     mut request: Request<Body>,
    1981            0 :     _cancel: CancellationToken,
    1982            0 : ) -> Result<Response<Body>, ApiError> {
    1983            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    1984              : 
    1985            0 :     let request_data: TenantLocationConfigRequest = json_request(&mut request).await?;
    1986            0 :     let flush = parse_query_param(&request, "flush_ms")?.map(Duration::from_millis);
    1987            0 :     let lazy = parse_query_param(&request, "lazy")?.unwrap_or(false);
    1988            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    1989              : 
    1990            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
    1991            0 :     let state = get_state(&request);
    1992            0 :     let conf = state.conf;
    1993              : 
    1994              :     // The `Detached` state is special, it doesn't upsert a tenant, it removes
    1995              :     // its local disk content and drops it from memory.
    1996            0 :     if let LocationConfigMode::Detached = request_data.config.mode {
    1997            0 :         if let Err(e) = state
    1998            0 :             .tenant_manager
    1999            0 :             .detach_tenant(conf, tenant_shard_id, &state.deletion_queue_client)
    2000            0 :             .instrument(info_span!("tenant_detach",
    2001              :                 tenant_id = %tenant_shard_id.tenant_id,
    2002            0 :                 shard_id = %tenant_shard_id.shard_slug()
    2003              :             ))
    2004            0 :             .await
    2005              :         {
    2006            0 :             match e {
    2007            0 :                 TenantStateError::SlotError(TenantSlotError::NotFound(_)) => {
    2008            0 :                     // This API is idempotent: a NotFound on a detach is fine.
    2009            0 :                 }
    2010            0 :                 _ => return Err(e.into()),
    2011              :             }
    2012            0 :         }
    2013            0 :         return json_response(StatusCode::OK, ());
    2014            0 :     }
    2015              : 
    2016            0 :     let location_conf =
    2017            0 :         LocationConf::try_from(&request_data.config).map_err(ApiError::BadRequest)?;
    2018              : 
    2019              :     // lazy==true queues up for activation or jumps the queue like normal when a compute connects,
    2020              :     // similar to at startup ordering.
    2021            0 :     let spawn_mode = if lazy {
    2022            0 :         tenant::SpawnMode::Lazy
    2023              :     } else {
    2024            0 :         tenant::SpawnMode::Eager
    2025              :     };
    2026              : 
    2027            0 :     let tenant = state
    2028            0 :         .tenant_manager
    2029            0 :         .upsert_location(tenant_shard_id, location_conf, flush, spawn_mode, &ctx)
    2030            0 :         .await?;
    2031            0 :     let stripe_size = tenant.as_ref().map(|t| t.get_shard_stripe_size());
    2032            0 :     let attached = tenant.is_some();
    2033              : 
    2034            0 :     if let Some(_flush_ms) = flush {
    2035            0 :         match state
    2036            0 :             .secondary_controller
    2037            0 :             .upload_tenant(tenant_shard_id)
    2038            0 :             .await
    2039              :         {
    2040              :             Ok(()) => {
    2041            0 :                 tracing::info!("Uploaded heatmap during flush");
    2042              :             }
    2043            0 :             Err(e) => {
    2044            0 :                 tracing::warn!("Failed to flush heatmap: {e}");
    2045              :             }
    2046              :         }
    2047              :     } else {
    2048            0 :         tracing::info!("No flush requested when configuring");
    2049              :     }
    2050              : 
    2051              :     // This API returns a vector of pageservers where the tenant is attached: this is
    2052              :     // primarily for use in the sharding service.  For compatibilty, we also return this
    2053              :     // when called directly on a pageserver, but the payload is always zero or one shards.
    2054            0 :     let mut response = TenantLocationConfigResponse {
    2055            0 :         shards: Vec::new(),
    2056            0 :         stripe_size: None,
    2057            0 :     };
    2058            0 :     if attached {
    2059            0 :         response.shards.push(TenantShardLocation {
    2060            0 :             shard_id: tenant_shard_id,
    2061            0 :             node_id: state.conf.id,
    2062            0 :         });
    2063            0 :         if tenant_shard_id.shard_count.count() > 1 {
    2064              :             // Stripe size should be set if we are attached
    2065            0 :             debug_assert!(stripe_size.is_some());
    2066            0 :             response.stripe_size = stripe_size;
    2067            0 :         }
    2068            0 :     }
    2069              : 
    2070            0 :     json_response(StatusCode::OK, response)
    2071            0 : }
    2072              : 
    2073            0 : async fn list_location_config_handler(
    2074            0 :     request: Request<Body>,
    2075            0 :     _cancel: CancellationToken,
    2076            0 : ) -> Result<Response<Body>, ApiError> {
    2077            0 :     let state = get_state(&request);
    2078            0 :     let slots = state.tenant_manager.list();
    2079            0 :     let result = LocationConfigListResponse {
    2080            0 :         tenant_shards: slots
    2081            0 :             .into_iter()
    2082            0 :             .map(|(tenant_shard_id, slot)| {
    2083            0 :                 let v = match slot {
    2084            0 :                     TenantSlot::Attached(t) => Some(t.get_location_conf()),
    2085            0 :                     TenantSlot::Secondary(s) => Some(s.get_location_conf()),
    2086            0 :                     TenantSlot::InProgress(_) => None,
    2087              :                 };
    2088            0 :                 (tenant_shard_id, v)
    2089            0 :             })
    2090            0 :             .collect(),
    2091              :     };
    2092            0 :     json_response(StatusCode::OK, result)
    2093            0 : }
    2094              : 
    2095            0 : async fn get_location_config_handler(
    2096            0 :     request: Request<Body>,
    2097            0 :     _cancel: CancellationToken,
    2098            0 : ) -> Result<Response<Body>, ApiError> {
    2099            0 :     let state = get_state(&request);
    2100            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2101            0 :     let slot = state.tenant_manager.get(tenant_shard_id);
    2102              : 
    2103            0 :     let Some(slot) = slot else {
    2104            0 :         return Err(ApiError::NotFound(
    2105            0 :             anyhow::anyhow!("Tenant shard not found").into(),
    2106            0 :         ));
    2107              :     };
    2108              : 
    2109            0 :     let result: Option<LocationConfig> = match slot {
    2110            0 :         TenantSlot::Attached(t) => Some(t.get_location_conf()),
    2111            0 :         TenantSlot::Secondary(s) => Some(s.get_location_conf()),
    2112            0 :         TenantSlot::InProgress(_) => None,
    2113              :     };
    2114              : 
    2115            0 :     json_response(StatusCode::OK, result)
    2116            0 : }
    2117              : 
    2118              : // Do a time travel recovery on the given tenant/tenant shard. Tenant needs to be detached
    2119              : // (from all pageservers) as it invalidates consistency assumptions.
    2120            0 : async fn tenant_time_travel_remote_storage_handler(
    2121            0 :     request: Request<Body>,
    2122            0 :     cancel: CancellationToken,
    2123            0 : ) -> Result<Response<Body>, ApiError> {
    2124            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2125              : 
    2126            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2127              : 
    2128            0 :     let timestamp_raw = must_get_query_param(&request, "travel_to")?;
    2129            0 :     let timestamp = humantime::parse_rfc3339(&timestamp_raw)
    2130            0 :         .with_context(|| format!("Invalid time for travel_to: {timestamp_raw:?}"))
    2131            0 :         .map_err(ApiError::BadRequest)?;
    2132              : 
    2133            0 :     let done_if_after_raw = must_get_query_param(&request, "done_if_after")?;
    2134            0 :     let done_if_after = humantime::parse_rfc3339(&done_if_after_raw)
    2135            0 :         .with_context(|| format!("Invalid time for done_if_after: {done_if_after_raw:?}"))
    2136            0 :         .map_err(ApiError::BadRequest)?;
    2137              : 
    2138              :     // This is just a sanity check to fend off naive wrong usages of the API:
    2139              :     // the tenant needs to be detached *everywhere*
    2140            0 :     let state = get_state(&request);
    2141            0 :     let we_manage_tenant = state.tenant_manager.manages_tenant_shard(tenant_shard_id);
    2142            0 :     if we_manage_tenant {
    2143            0 :         return Err(ApiError::BadRequest(anyhow!(
    2144            0 :             "Tenant {tenant_shard_id} is already attached at this pageserver"
    2145            0 :         )));
    2146            0 :     }
    2147              : 
    2148            0 :     if timestamp > done_if_after {
    2149            0 :         return Err(ApiError::BadRequest(anyhow!(
    2150            0 :             "The done_if_after timestamp comes before the timestamp to recover to"
    2151            0 :         )));
    2152            0 :     }
    2153              : 
    2154            0 :     tracing::info!(
    2155            0 :         "Issuing time travel request internally. timestamp={timestamp_raw}, done_if_after={done_if_after_raw}"
    2156              :     );
    2157              : 
    2158            0 :     remote_timeline_client::upload::time_travel_recover_tenant(
    2159            0 :         &state.remote_storage,
    2160            0 :         &tenant_shard_id,
    2161            0 :         timestamp,
    2162            0 :         done_if_after,
    2163            0 :         &cancel,
    2164            0 :     )
    2165            0 :     .await
    2166            0 :     .map_err(|e| match e {
    2167            0 :         TimeTravelError::BadInput(e) => {
    2168            0 :             warn!("bad input error: {e}");
    2169            0 :             ApiError::BadRequest(anyhow!("bad input error"))
    2170              :         }
    2171              :         TimeTravelError::Unimplemented => {
    2172            0 :             ApiError::BadRequest(anyhow!("unimplemented for the configured remote storage"))
    2173              :         }
    2174            0 :         TimeTravelError::Cancelled => ApiError::InternalServerError(anyhow!("cancelled")),
    2175              :         TimeTravelError::TooManyVersions => {
    2176            0 :             ApiError::InternalServerError(anyhow!("too many versions in remote storage"))
    2177              :         }
    2178            0 :         TimeTravelError::Other(e) => {
    2179            0 :             warn!("internal error: {e}");
    2180            0 :             ApiError::InternalServerError(anyhow!("internal error"))
    2181              :         }
    2182            0 :     })?;
    2183              : 
    2184            0 :     json_response(StatusCode::OK, ())
    2185            0 : }
    2186              : 
    2187              : /// Testing helper to transition a tenant to [`crate::tenant::TenantState::Broken`].
    2188            0 : async fn handle_tenant_break(
    2189            0 :     r: Request<Body>,
    2190            0 :     _cancel: CancellationToken,
    2191            0 : ) -> Result<Response<Body>, ApiError> {
    2192            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&r, "tenant_shard_id")?;
    2193              : 
    2194            0 :     let state = get_state(&r);
    2195            0 :     state
    2196            0 :         .tenant_manager
    2197            0 :         .get_attached_tenant_shard(tenant_shard_id)?
    2198            0 :         .set_broken("broken from test".to_owned())
    2199            0 :         .await;
    2200              : 
    2201            0 :     json_response(StatusCode::OK, ())
    2202            0 : }
    2203              : 
    2204              : // Obtains an lsn lease on the given timeline.
    2205            0 : async fn lsn_lease_handler(
    2206            0 :     mut request: Request<Body>,
    2207            0 :     _cancel: CancellationToken,
    2208            0 : ) -> Result<Response<Body>, ApiError> {
    2209            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2210            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2211            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2212            0 :     let lsn = json_request::<LsnLeaseRequest>(&mut request).await?.lsn;
    2213              : 
    2214            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    2215              : 
    2216            0 :     let state = get_state(&request);
    2217              : 
    2218            0 :     let timeline =
    2219            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    2220            0 :             .await?;
    2221              : 
    2222            0 :     let result = async {
    2223            0 :         timeline
    2224            0 :             .init_lsn_lease(lsn, timeline.get_lsn_lease_length(), &ctx)
    2225            0 :             .map_err(|e| {
    2226            0 :                 ApiError::InternalServerError(
    2227            0 :                     e.context(format!("invalid lsn lease request at {lsn}")),
    2228            0 :                 )
    2229            0 :             })
    2230            0 :     }
    2231            0 :     .instrument(info_span!("init_lsn_lease", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2232            0 :     .await?;
    2233              : 
    2234            0 :     json_response(StatusCode::OK, result)
    2235            0 : }
    2236              : 
    2237              : // Run GC immediately on given timeline.
    2238            0 : async fn timeline_gc_handler(
    2239            0 :     mut request: Request<Body>,
    2240            0 :     cancel: CancellationToken,
    2241            0 : ) -> Result<Response<Body>, ApiError> {
    2242            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2243            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2244            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2245              : 
    2246            0 :     let gc_req: TimelineGcRequest = json_request(&mut request).await?;
    2247              : 
    2248            0 :     let state = get_state(&request);
    2249              : 
    2250            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    2251            0 :     let gc_result = state
    2252            0 :         .tenant_manager
    2253            0 :         .immediate_gc(tenant_shard_id, timeline_id, gc_req, cancel, &ctx)
    2254            0 :         .await?;
    2255              : 
    2256            0 :     json_response(StatusCode::OK, gc_result)
    2257            0 : }
    2258              : 
    2259              : // Cancel scheduled compaction tasks
    2260            0 : async fn timeline_cancel_compact_handler(
    2261            0 :     request: Request<Body>,
    2262            0 :     _cancel: CancellationToken,
    2263            0 : ) -> Result<Response<Body>, ApiError> {
    2264            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2265            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2266            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2267            0 :     let state = get_state(&request);
    2268            0 :     async {
    2269            0 :         let tenant = state
    2270            0 :             .tenant_manager
    2271            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    2272            0 :         tenant.cancel_scheduled_compaction(timeline_id);
    2273            0 :         json_response(StatusCode::OK, ())
    2274            0 :     }
    2275            0 :     .instrument(info_span!("timeline_cancel_compact", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2276            0 :     .await
    2277            0 : }
    2278              : 
    2279              : // Get compact info of a timeline
    2280            0 : async fn timeline_compact_info_handler(
    2281            0 :     request: Request<Body>,
    2282            0 :     _cancel: CancellationToken,
    2283            0 : ) -> Result<Response<Body>, ApiError> {
    2284            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2285            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2286            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2287            0 :     let state = get_state(&request);
    2288            0 :     async {
    2289            0 :         let tenant = state
    2290            0 :             .tenant_manager
    2291            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    2292            0 :         let resp = tenant.get_scheduled_compaction_tasks(timeline_id);
    2293            0 :         json_response(StatusCode::OK, resp)
    2294            0 :     }
    2295            0 :     .instrument(info_span!("timeline_compact_info", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2296            0 :     .await
    2297            0 : }
    2298              : 
    2299              : // Run compaction immediately on given timeline.
    2300            0 : async fn timeline_compact_handler(
    2301            0 :     mut request: Request<Body>,
    2302            0 :     cancel: CancellationToken,
    2303            0 : ) -> Result<Response<Body>, ApiError> {
    2304            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2305            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2306            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2307              : 
    2308            0 :     let compact_request = json_request_maybe::<Option<CompactRequest>>(&mut request).await?;
    2309              : 
    2310            0 :     let state = get_state(&request);
    2311              : 
    2312            0 :     let mut flags = EnumSet::empty();
    2313              : 
    2314            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_l0_compaction")? {
    2315            0 :         flags |= CompactFlags::ForceL0Compaction;
    2316            0 :     }
    2317            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_repartition")? {
    2318            0 :         flags |= CompactFlags::ForceRepartition;
    2319            0 :     }
    2320            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_image_layer_creation")? {
    2321            0 :         flags |= CompactFlags::ForceImageLayerCreation;
    2322            0 :     }
    2323            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "enhanced_gc_bottom_most_compaction")? {
    2324            0 :         flags |= CompactFlags::EnhancedGcBottomMostCompaction;
    2325            0 :     }
    2326            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "dry_run")? {
    2327            0 :         flags |= CompactFlags::DryRun;
    2328            0 :     }
    2329              :     // Manual compaction does not yield for L0.
    2330              : 
    2331            0 :     let wait_until_uploaded =
    2332            0 :         parse_query_param::<_, bool>(&request, "wait_until_uploaded")?.unwrap_or(false);
    2333              : 
    2334            0 :     let wait_until_scheduled_compaction_done =
    2335            0 :         parse_query_param::<_, bool>(&request, "wait_until_scheduled_compaction_done")?
    2336            0 :             .unwrap_or(false);
    2337              : 
    2338            0 :     let sub_compaction = compact_request
    2339            0 :         .as_ref()
    2340            0 :         .map(|r| r.sub_compaction)
    2341            0 :         .unwrap_or(false);
    2342            0 :     let sub_compaction_max_job_size_mb = compact_request
    2343            0 :         .as_ref()
    2344            0 :         .and_then(|r| r.sub_compaction_max_job_size_mb);
    2345              : 
    2346            0 :     let options = CompactOptions {
    2347            0 :         compact_key_range: compact_request
    2348            0 :             .as_ref()
    2349            0 :             .and_then(|r| r.compact_key_range.clone()),
    2350            0 :         compact_lsn_range: compact_request
    2351            0 :             .as_ref()
    2352            0 :             .and_then(|r| r.compact_lsn_range.clone()),
    2353            0 :         flags,
    2354            0 :         sub_compaction,
    2355            0 :         sub_compaction_max_job_size_mb,
    2356              :     };
    2357              : 
    2358            0 :     let scheduled = compact_request
    2359            0 :         .as_ref()
    2360            0 :         .map(|r| r.scheduled)
    2361            0 :         .unwrap_or(false);
    2362              : 
    2363            0 :     async {
    2364            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id).await?;
    2365            0 :         let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download).with_scope_timeline(&timeline);
    2366            0 :         if scheduled {
    2367            0 :             let tenant = state
    2368            0 :                 .tenant_manager
    2369            0 :                 .get_attached_tenant_shard(tenant_shard_id)?;
    2370            0 :             let rx = tenant.schedule_compaction(timeline_id, options).await.map_err(ApiError::InternalServerError)?;
    2371            0 :             if wait_until_scheduled_compaction_done {
    2372              :                 // It is possible that this will take a long time, dropping the HTTP request will not cancel the compaction.
    2373            0 :                 rx.await.ok();
    2374            0 :             }
    2375              :         } else {
    2376            0 :             timeline
    2377            0 :                 .compact_with_options(&cancel, options, &ctx)
    2378            0 :                 .await
    2379            0 :                 .map_err(|e| ApiError::InternalServerError(e.into()))?;
    2380            0 :             if wait_until_uploaded {
    2381            0 :                 timeline.remote_client.wait_completion().await
    2382              :                 // XXX map to correct ApiError for the cases where it's due to shutdown
    2383            0 :                 .context("wait completion").map_err(ApiError::InternalServerError)?;
    2384            0 :             }
    2385              :         }
    2386            0 :         json_response(StatusCode::OK, ())
    2387            0 :     }
    2388            0 :     .instrument(info_span!("manual_compaction", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2389            0 :     .await
    2390            0 : }
    2391              : 
    2392            0 : async fn timeline_mark_invisible_handler(
    2393            0 :     mut request: Request<Body>,
    2394            0 :     _cancel: CancellationToken,
    2395            0 : ) -> Result<Response<Body>, ApiError> {
    2396            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2397            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2398            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2399              : 
    2400            0 :     let compact_request = json_request_maybe::<Option<MarkInvisibleRequest>>(&mut request).await?;
    2401              : 
    2402            0 :     let state = get_state(&request);
    2403              : 
    2404            0 :     let visibility = match compact_request {
    2405            0 :         Some(req) => match req.is_visible {
    2406            0 :             Some(true) => TimelineVisibilityState::Visible,
    2407            0 :             Some(false) | None => TimelineVisibilityState::Invisible,
    2408              :         },
    2409            0 :         None => TimelineVisibilityState::Invisible,
    2410              :     };
    2411              : 
    2412            0 :     async {
    2413            0 :         let tenant = state
    2414            0 :             .tenant_manager
    2415            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    2416            0 :         let timeline = tenant.get_timeline(timeline_id, true)?;
    2417            0 :         timeline.remote_client.schedule_index_upload_for_timeline_invisible_state(visibility).map_err(ApiError::InternalServerError)?;
    2418            0 :         json_response(StatusCode::OK, ())
    2419            0 :     }
    2420            0 :     .instrument(info_span!("manual_timeline_mark_invisible", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2421            0 :     .await
    2422            0 : }
    2423              : 
    2424              : // Run offload immediately on given timeline.
    2425            0 : async fn timeline_offload_handler(
    2426            0 :     request: Request<Body>,
    2427            0 :     _cancel: CancellationToken,
    2428            0 : ) -> Result<Response<Body>, ApiError> {
    2429            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2430            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2431            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2432              : 
    2433            0 :     let state = get_state(&request);
    2434              : 
    2435            0 :     async {
    2436            0 :         let tenant = state
    2437            0 :             .tenant_manager
    2438            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    2439              : 
    2440            0 :         if tenant.get_offloaded_timeline(timeline_id).is_ok() {
    2441            0 :             return json_response(StatusCode::OK, ());
    2442            0 :         }
    2443            0 :         let timeline =
    2444            0 :             active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    2445            0 :                 .await?;
    2446              : 
    2447            0 :         if !tenant.timeline_has_no_attached_children(timeline_id) {
    2448            0 :             return Err(ApiError::PreconditionFailed(
    2449            0 :                 "timeline has attached children".into(),
    2450            0 :             ));
    2451            0 :         }
    2452            0 :         if let (false, reason) = timeline.can_offload() {
    2453            0 :             return Err(ApiError::PreconditionFailed(
    2454            0 :                 format!("Timeline::can_offload() check failed: {reason}") .into(),
    2455            0 :             ));
    2456            0 :         }
    2457            0 :         offload_timeline(&tenant, &timeline)
    2458            0 :             .await
    2459            0 :             .map_err(|e| {
    2460            0 :                 match e {
    2461            0 :                     OffloadError::Cancelled => ApiError::ResourceUnavailable("Timeline shutting down".into()),
    2462            0 :                     OffloadError::AlreadyInProgress => ApiError::Conflict("Timeline already being offloaded or deleted".into()),
    2463            0 :                     _ => ApiError::InternalServerError(anyhow!(e))
    2464              :                 }
    2465            0 :             })?;
    2466              : 
    2467            0 :         json_response(StatusCode::OK, ())
    2468            0 :     }
    2469            0 :     .instrument(info_span!("manual_timeline_offload", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2470            0 :     .await
    2471            0 : }
    2472              : 
    2473              : // Run checkpoint immediately on given timeline.
    2474            0 : async fn timeline_checkpoint_handler(
    2475            0 :     request: Request<Body>,
    2476            0 :     cancel: CancellationToken,
    2477            0 : ) -> Result<Response<Body>, ApiError> {
    2478            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2479            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2480            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2481              : 
    2482            0 :     let state = get_state(&request);
    2483              : 
    2484            0 :     let mut flags = EnumSet::empty();
    2485            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_l0_compaction")? {
    2486            0 :         flags |= CompactFlags::ForceL0Compaction;
    2487            0 :     }
    2488            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_repartition")? {
    2489            0 :         flags |= CompactFlags::ForceRepartition;
    2490            0 :     }
    2491            0 :     if Some(true) == parse_query_param::<_, bool>(&request, "force_image_layer_creation")? {
    2492            0 :         flags |= CompactFlags::ForceImageLayerCreation;
    2493            0 :     }
    2494              : 
    2495              :     // By default, checkpoints come with a compaction, but this may be optionally disabled by tests that just want to flush + upload.
    2496            0 :     let compact = parse_query_param::<_, bool>(&request, "compact")?.unwrap_or(true);
    2497              : 
    2498            0 :     let wait_until_flushed: bool =
    2499            0 :         parse_query_param(&request, "wait_until_flushed")?.unwrap_or(true);
    2500              : 
    2501            0 :     let wait_until_uploaded =
    2502            0 :         parse_query_param::<_, bool>(&request, "wait_until_uploaded")?.unwrap_or(false);
    2503              : 
    2504            0 :     async {
    2505            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id).await?;
    2506            0 :         let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download).with_scope_timeline(&timeline);
    2507            0 :         if wait_until_flushed {
    2508            0 :             timeline.freeze_and_flush().await
    2509              :         } else {
    2510            0 :             timeline.freeze().await.and(Ok(()))
    2511            0 :         }.map_err(|e| {
    2512            0 :                 match e {
    2513            0 :                     tenant::timeline::FlushLayerError::Cancelled => ApiError::ShuttingDown,
    2514            0 :                     other => ApiError::InternalServerError(other.into()),
    2515              : 
    2516              :                 }
    2517            0 :             })?;
    2518            0 :         if compact {
    2519            0 :             timeline
    2520            0 :                 .compact(&cancel, flags, &ctx)
    2521            0 :                 .await
    2522            0 :                 .map_err(|e|
    2523            0 :                     if e.is_cancel() {
    2524            0 :                         ApiError::ShuttingDown
    2525              :                     } else {
    2526            0 :                         ApiError::InternalServerError(e.into_anyhow())
    2527            0 :                     }
    2528            0 :                 )?;
    2529            0 :         }
    2530              : 
    2531            0 :         if wait_until_uploaded {
    2532            0 :             tracing::info!("Waiting for uploads to complete...");
    2533            0 :             timeline.remote_client.wait_completion().await
    2534              :             // XXX map to correct ApiError for the cases where it's due to shutdown
    2535            0 :             .context("wait completion").map_err(ApiError::InternalServerError)?;
    2536            0 :             tracing::info!("Uploads completed up to {}", timeline.get_remote_consistent_lsn_projected().unwrap_or(Lsn(0)));
    2537            0 :         }
    2538              : 
    2539            0 :         json_response(StatusCode::OK, ())
    2540            0 :     }
    2541            0 :     .instrument(info_span!("manual_checkpoint", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2542            0 :     .await
    2543            0 : }
    2544              : 
    2545            0 : async fn timeline_download_remote_layers_handler_post(
    2546            0 :     mut request: Request<Body>,
    2547            0 :     _cancel: CancellationToken,
    2548            0 : ) -> Result<Response<Body>, ApiError> {
    2549            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2550            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2551            0 :     let body: DownloadRemoteLayersTaskSpawnRequest = json_request(&mut request).await?;
    2552            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2553              : 
    2554            0 :     let state = get_state(&request);
    2555              : 
    2556            0 :     let timeline =
    2557            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    2558            0 :             .await?;
    2559            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download)
    2560            0 :         .with_scope_timeline(&timeline);
    2561            0 :     match timeline.spawn_download_all_remote_layers(body, &ctx).await {
    2562            0 :         Ok(st) => json_response(StatusCode::ACCEPTED, st),
    2563            0 :         Err(st) => json_response(StatusCode::CONFLICT, st),
    2564              :     }
    2565            0 : }
    2566              : 
    2567            0 : async fn timeline_download_remote_layers_handler_get(
    2568            0 :     request: Request<Body>,
    2569            0 :     _cancel: CancellationToken,
    2570            0 : ) -> Result<Response<Body>, ApiError> {
    2571            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2572            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2573            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2574            0 :     let state = get_state(&request);
    2575              : 
    2576            0 :     let timeline =
    2577            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    2578            0 :             .await?;
    2579            0 :     let info = timeline
    2580            0 :         .get_download_all_remote_layers_task_info()
    2581            0 :         .context("task never started since last pageserver process start")
    2582            0 :         .map_err(|e| ApiError::NotFound(e.into()))?;
    2583            0 :     json_response(StatusCode::OK, info)
    2584            0 : }
    2585              : 
    2586            0 : async fn timeline_detach_ancestor_handler(
    2587            0 :     request: Request<Body>,
    2588            0 :     _cancel: CancellationToken,
    2589            0 : ) -> Result<Response<Body>, ApiError> {
    2590              :     use pageserver_api::models::detach_ancestor::AncestorDetached;
    2591              : 
    2592              :     use crate::tenant::timeline::detach_ancestor;
    2593              : 
    2594            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2595            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2596            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2597            0 :     let behavior: Option<DetachBehavior> = parse_query_param(&request, "detach_behavior")?;
    2598              : 
    2599            0 :     let behavior = behavior.unwrap_or_default();
    2600              : 
    2601            0 :     let span = tracing::info_span!("detach_ancestor", tenant_id=%tenant_shard_id.tenant_id, shard_id=%tenant_shard_id.shard_slug(), %timeline_id);
    2602              : 
    2603            0 :     async move {
    2604            0 :         let mut options = detach_ancestor::Options::default();
    2605              : 
    2606            0 :         let rewrite_concurrency =
    2607            0 :             parse_query_param::<_, std::num::NonZeroUsize>(&request, "rewrite_concurrency")?;
    2608            0 :         let copy_concurrency =
    2609            0 :             parse_query_param::<_, std::num::NonZeroUsize>(&request, "copy_concurrency")?;
    2610              : 
    2611            0 :         [
    2612            0 :             (&mut options.rewrite_concurrency, rewrite_concurrency),
    2613            0 :             (&mut options.copy_concurrency, copy_concurrency),
    2614            0 :         ]
    2615            0 :         .into_iter()
    2616            0 :         .filter_map(|(target, val)| val.map(|val| (target, val)))
    2617            0 :         .for_each(|(target, val)| *target = val);
    2618              : 
    2619            0 :         let state = get_state(&request);
    2620              : 
    2621            0 :         let tenant = state
    2622            0 :             .tenant_manager
    2623            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    2624              : 
    2625            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    2626              : 
    2627            0 :         let ctx = RequestContext::new(TaskKind::DetachAncestor, DownloadBehavior::Download);
    2628            0 :         let ctx = &ctx;
    2629              : 
    2630              :         // Flush the upload queues of all timelines before detaching ancestor. We do the same thing again
    2631              :         // during shutdown. This early upload ensures the pageserver does not need to upload too many
    2632              :         // things and creates downtime during timeline reloads.
    2633            0 :         for timeline in tenant.list_timelines() {
    2634            0 :             timeline
    2635            0 :                 .remote_client
    2636            0 :                 .wait_completion()
    2637            0 :                 .await
    2638            0 :                 .map_err(|e| {
    2639            0 :                     ApiError::PreconditionFailed(format!("cannot drain upload queue: {e}").into())
    2640            0 :                 })?;
    2641              :         }
    2642              : 
    2643            0 :         tracing::info!("all timeline upload queues are drained");
    2644              : 
    2645            0 :         let timeline = tenant.get_timeline(timeline_id, true)?;
    2646            0 :         let ctx = &ctx.with_scope_timeline(&timeline);
    2647              : 
    2648            0 :         let progress = timeline
    2649            0 :             .prepare_to_detach_from_ancestor(&tenant, options, behavior, ctx)
    2650            0 :             .await?;
    2651              : 
    2652              :         // uncomment to allow early as possible Tenant::drop
    2653              :         // drop(tenant);
    2654              : 
    2655            0 :         let resp = match progress {
    2656            0 :             detach_ancestor::Progress::Prepared(attempt, prepared) => {
    2657              :                 // it would be great to tag the guard on to the tenant activation future
    2658            0 :                 let reparented_timelines = state
    2659            0 :                     .tenant_manager
    2660            0 :                     .complete_detaching_timeline_ancestor(
    2661            0 :                         tenant_shard_id,
    2662            0 :                         timeline_id,
    2663            0 :                         prepared,
    2664            0 :                         behavior,
    2665            0 :                         attempt,
    2666            0 :                         ctx,
    2667            0 :                     )
    2668            0 :                     .await?;
    2669              : 
    2670            0 :                 AncestorDetached {
    2671            0 :                     reparented_timelines,
    2672            0 :                 }
    2673              :             }
    2674            0 :             detach_ancestor::Progress::Done(resp) => resp,
    2675              :         };
    2676              : 
    2677            0 :         json_response(StatusCode::OK, resp)
    2678            0 :     }
    2679            0 :     .instrument(span)
    2680            0 :     .await
    2681            0 : }
    2682              : 
    2683            0 : async fn deletion_queue_flush(
    2684            0 :     r: Request<Body>,
    2685            0 :     cancel: CancellationToken,
    2686            0 : ) -> Result<Response<Body>, ApiError> {
    2687            0 :     let state = get_state(&r);
    2688              : 
    2689            0 :     let execute = parse_query_param(&r, "execute")?.unwrap_or(false);
    2690              : 
    2691            0 :     let flush = async {
    2692            0 :         if execute {
    2693            0 :             state.deletion_queue_client.flush_execute().await
    2694              :         } else {
    2695            0 :             state.deletion_queue_client.flush().await
    2696              :         }
    2697            0 :     }
    2698              :     // DeletionQueueError's only case is shutting down.
    2699            0 :     .map_err(|_| ApiError::ShuttingDown);
    2700              : 
    2701            0 :     tokio::select! {
    2702            0 :         res = flush => {
    2703            0 :             res.map(|()| json_response(StatusCode::OK, ()))?
    2704              :         }
    2705            0 :         _ = cancel.cancelled() => {
    2706            0 :             Err(ApiError::ShuttingDown)
    2707              :         }
    2708              :     }
    2709            0 : }
    2710              : 
    2711            0 : async fn getpage_at_lsn_handler(
    2712            0 :     request: Request<Body>,
    2713            0 :     cancel: CancellationToken,
    2714            0 : ) -> Result<Response<Body>, ApiError> {
    2715            0 :     getpage_at_lsn_handler_inner(false, request, cancel).await
    2716            0 : }
    2717              : 
    2718            0 : async fn touchpage_at_lsn_handler(
    2719            0 :     request: Request<Body>,
    2720            0 :     cancel: CancellationToken,
    2721            0 : ) -> Result<Response<Body>, ApiError> {
    2722            0 :     getpage_at_lsn_handler_inner(true, request, cancel).await
    2723            0 : }
    2724              : 
    2725              : /// Try if `GetPage@Lsn` is successful, useful for manual debugging.
    2726            0 : async fn getpage_at_lsn_handler_inner(
    2727            0 :     touch: bool,
    2728            0 :     request: Request<Body>,
    2729            0 :     _cancel: CancellationToken,
    2730            0 : ) -> Result<Response<Body>, ApiError> {
    2731            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2732            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2733              :     // Require pageserver admin permission for this API instead of only tenant-level token.
    2734            0 :     check_permission(&request, None)?;
    2735            0 :     let state = get_state(&request);
    2736              : 
    2737              :     struct Key(pageserver_api::key::Key);
    2738              : 
    2739              :     impl std::str::FromStr for Key {
    2740              :         type Err = anyhow::Error;
    2741              : 
    2742            0 :         fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
    2743            0 :             pageserver_api::key::Key::from_hex(s).map(Key)
    2744            0 :         }
    2745              :     }
    2746              : 
    2747            0 :     let key: Key = parse_query_param(&request, "key")?
    2748            0 :         .ok_or_else(|| ApiError::BadRequest(anyhow!("missing 'key' query parameter")))?;
    2749            0 :     let lsn: Option<Lsn> = parse_query_param(&request, "lsn")?;
    2750              : 
    2751            0 :     async {
    2752            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id).await?;
    2753            0 :         let ctx = RequestContextBuilder::new(TaskKind::MgmtRequest)
    2754            0 :             .download_behavior(DownloadBehavior::Download)
    2755            0 :             .scope(context::Scope::new_timeline(&timeline))
    2756            0 :             .read_path_debug(true)
    2757            0 :             .root();
    2758              : 
    2759              :         // Use last_record_lsn if no lsn is provided
    2760            0 :         let lsn = lsn.unwrap_or_else(|| timeline.get_last_record_lsn());
    2761            0 :         let page = timeline.get(key.0, lsn, &ctx).await?;
    2762              : 
    2763            0 :         if touch {
    2764            0 :             json_response(StatusCode::OK, ())
    2765              :         } else {
    2766            0 :             Result::<_, ApiError>::Ok(
    2767            0 :                 Response::builder()
    2768            0 :                     .status(StatusCode::OK)
    2769            0 :                     .header(header::CONTENT_TYPE, "application/octet-stream")
    2770            0 :                     .body(hyper::Body::from(page))
    2771            0 :                     .unwrap(),
    2772            0 :             )
    2773              :         }
    2774            0 :     }
    2775            0 :     .instrument(info_span!("timeline_get", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2776            0 :     .await
    2777            0 : }
    2778              : 
    2779            0 : async fn timeline_collect_keyspace(
    2780            0 :     request: Request<Body>,
    2781            0 :     _cancel: CancellationToken,
    2782            0 : ) -> Result<Response<Body>, ApiError> {
    2783            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2784            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    2785            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    2786            0 :     let state = get_state(&request);
    2787              : 
    2788            0 :     let at_lsn: Option<Lsn> = parse_query_param(&request, "at_lsn")?;
    2789              : 
    2790            0 :     async {
    2791            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id).await?;
    2792            0 :         let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download).with_scope_timeline(&timeline);
    2793            0 :         let at_lsn = at_lsn.unwrap_or_else(|| timeline.get_last_record_lsn());
    2794            0 :         let (dense_ks, sparse_ks) = timeline
    2795            0 :             .collect_keyspace(at_lsn, &ctx)
    2796            0 :             .await
    2797            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))?;
    2798              : 
    2799              :         // This API is currently used by pagebench. Pagebench will iterate all keys within the keyspace.
    2800              :         // Therefore, we split dense/sparse keys in this API.
    2801            0 :         let res = pageserver_api::models::partitioning::Partitioning { keys: dense_ks, sparse_keys: sparse_ks, at_lsn };
    2802              : 
    2803            0 :         json_response(StatusCode::OK, res)
    2804            0 :     }
    2805            0 :     .instrument(info_span!("timeline_collect_keyspace", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug(), %timeline_id))
    2806            0 :     .await
    2807            0 : }
    2808              : 
    2809            0 : async fn active_timeline_of_active_tenant(
    2810            0 :     tenant_manager: &TenantManager,
    2811            0 :     tenant_shard_id: TenantShardId,
    2812            0 :     timeline_id: TimelineId,
    2813            0 : ) -> Result<Arc<Timeline>, ApiError> {
    2814            0 :     let tenant = tenant_manager.get_attached_tenant_shard(tenant_shard_id)?;
    2815              : 
    2816            0 :     tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    2817              : 
    2818            0 :     Ok(tenant.get_timeline(timeline_id, true)?)
    2819            0 : }
    2820              : 
    2821            0 : async fn always_panic_handler(
    2822            0 :     req: Request<Body>,
    2823            0 :     _cancel: CancellationToken,
    2824            0 : ) -> Result<Response<Body>, ApiError> {
    2825              :     // Deliberately cause a panic to exercise the panic hook registered via std::panic::set_hook().
    2826              :     // For pageserver, the relevant panic hook is `tracing_panic_hook` , and the `sentry` crate's wrapper around it.
    2827              :     // Use catch_unwind to ensure that tokio nor hyper are distracted by our panic.
    2828            0 :     let query = req.uri().query();
    2829            0 :     let _ = std::panic::catch_unwind(|| {
    2830            0 :         panic!("unconditional panic for testing panic hook integration; request query: {query:?}")
    2831              :     });
    2832            0 :     json_response(StatusCode::NO_CONTENT, ())
    2833            0 : }
    2834              : 
    2835            0 : async fn disk_usage_eviction_run(
    2836            0 :     mut r: Request<Body>,
    2837            0 :     cancel: CancellationToken,
    2838            0 : ) -> Result<Response<Body>, ApiError> {
    2839            0 :     check_permission(&r, None)?;
    2840              : 
    2841            0 :     #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
    2842              :     struct Config {
    2843              :         /// How many bytes to evict before reporting that pressure is relieved.
    2844              :         evict_bytes: u64,
    2845              : 
    2846              :         #[serde(default)]
    2847              :         eviction_order: pageserver_api::config::EvictionOrder,
    2848              :     }
    2849              : 
    2850              :     #[derive(Debug, Clone, Copy, serde::Serialize)]
    2851              :     struct Usage {
    2852              :         // remains unchanged after instantiation of the struct
    2853              :         evict_bytes: u64,
    2854              :         // updated by `add_available_bytes`
    2855              :         freed_bytes: u64,
    2856              :     }
    2857              : 
    2858              :     impl crate::disk_usage_eviction_task::Usage for Usage {
    2859            0 :         fn has_pressure(&self) -> bool {
    2860            0 :             self.evict_bytes > self.freed_bytes
    2861            0 :         }
    2862              : 
    2863            0 :         fn add_available_bytes(&mut self, bytes: u64) {
    2864            0 :             self.freed_bytes += bytes;
    2865            0 :         }
    2866              :     }
    2867              : 
    2868            0 :     let config = json_request::<Config>(&mut r).await?;
    2869              : 
    2870            0 :     let usage = Usage {
    2871            0 :         evict_bytes: config.evict_bytes,
    2872            0 :         freed_bytes: 0,
    2873            0 :     };
    2874              : 
    2875            0 :     let state = get_state(&r);
    2876            0 :     let eviction_state = state.disk_usage_eviction_state.clone();
    2877              : 
    2878            0 :     let res = crate::disk_usage_eviction_task::disk_usage_eviction_task_iteration_impl(
    2879            0 :         &eviction_state,
    2880            0 :         &state.remote_storage,
    2881            0 :         usage,
    2882            0 :         &state.tenant_manager,
    2883            0 :         config.eviction_order.into(),
    2884            0 :         &cancel,
    2885            0 :     )
    2886            0 :     .await;
    2887              : 
    2888            0 :     info!(?res, "disk_usage_eviction_task_iteration_impl finished");
    2889              : 
    2890            0 :     let res = res.map_err(ApiError::InternalServerError)?;
    2891              : 
    2892            0 :     json_response(StatusCode::OK, res)
    2893            0 : }
    2894              : 
    2895            0 : async fn secondary_upload_handler(
    2896            0 :     request: Request<Body>,
    2897            0 :     _cancel: CancellationToken,
    2898            0 : ) -> Result<Response<Body>, ApiError> {
    2899            0 :     let state = get_state(&request);
    2900            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    2901            0 :     state
    2902            0 :         .secondary_controller
    2903            0 :         .upload_tenant(tenant_shard_id)
    2904            0 :         .await?;
    2905              : 
    2906            0 :     json_response(StatusCode::OK, ())
    2907            0 : }
    2908              : 
    2909            0 : async fn tenant_scan_remote_handler(
    2910            0 :     request: Request<Body>,
    2911            0 :     cancel: CancellationToken,
    2912            0 : ) -> Result<Response<Body>, ApiError> {
    2913            0 :     let state = get_state(&request);
    2914            0 :     let tenant_id: TenantId = parse_request_param(&request, "tenant_id")?;
    2915              : 
    2916            0 :     let mut response = TenantScanRemoteStorageResponse::default();
    2917              : 
    2918            0 :     let (shards, _other_keys) =
    2919            0 :         list_remote_tenant_shards(&state.remote_storage, tenant_id, cancel.clone())
    2920            0 :             .await
    2921            0 :             .map_err(|e| ApiError::InternalServerError(anyhow::anyhow!(e)))?;
    2922              : 
    2923            0 :     for tenant_shard_id in shards {
    2924            0 :         let (timeline_ids, _other_keys) =
    2925            0 :             list_remote_timelines(&state.remote_storage, tenant_shard_id, cancel.clone())
    2926            0 :                 .await
    2927            0 :                 .map_err(|e| ApiError::InternalServerError(anyhow::anyhow!(e)))?;
    2928              : 
    2929            0 :         let mut generation = Generation::none();
    2930            0 :         for timeline_id in timeline_ids {
    2931            0 :             match download_index_part(
    2932            0 :                 &state.remote_storage,
    2933            0 :                 &tenant_shard_id,
    2934            0 :                 &timeline_id,
    2935              :                 Generation::MAX,
    2936            0 :                 &cancel,
    2937              :             )
    2938            0 :             .instrument(info_span!("download_index_part",
    2939              :                          tenant_id=%tenant_shard_id.tenant_id,
    2940            0 :                          shard_id=%tenant_shard_id.shard_slug(),
    2941              :                          %timeline_id))
    2942            0 :             .await
    2943              :             {
    2944            0 :                 Ok((index_part, index_generation, _index_mtime)) => {
    2945            0 :                     tracing::info!(
    2946            0 :                         "Found timeline {tenant_shard_id}/{timeline_id} metadata (gen {index_generation:?}, {} layers, {} consistent LSN)",
    2947            0 :                         index_part.layer_metadata.len(),
    2948            0 :                         index_part.metadata.disk_consistent_lsn()
    2949              :                     );
    2950            0 :                     generation = std::cmp::max(generation, index_generation);
    2951              :                 }
    2952              :                 Err(DownloadError::NotFound) => {
    2953              :                     // This is normal for tenants that were created with multiple shards: they have an unsharded path
    2954              :                     // containing the timeline's initdb tarball but no index.  Otherwise it is a bit strange.
    2955            0 :                     tracing::info!(
    2956            0 :                         "Timeline path {tenant_shard_id}/{timeline_id} exists in remote storage but has no index, skipping"
    2957              :                     );
    2958            0 :                     continue;
    2959              :                 }
    2960            0 :                 Err(e) => {
    2961            0 :                     return Err(ApiError::InternalServerError(anyhow::anyhow!(e)));
    2962              :                 }
    2963              :             };
    2964              :         }
    2965              : 
    2966            0 :         let result =
    2967            0 :             download_tenant_manifest(&state.remote_storage, &tenant_shard_id, generation, &cancel)
    2968            0 :                 .instrument(info_span!("download_tenant_manifest",
    2969              :                             tenant_id=%tenant_shard_id.tenant_id,
    2970            0 :                             shard_id=%tenant_shard_id.shard_slug()))
    2971            0 :                 .await;
    2972            0 :         let stripe_size = match result {
    2973            0 :             Ok((manifest, _, _)) => manifest.stripe_size,
    2974            0 :             Err(DownloadError::NotFound) => None,
    2975            0 :             Err(err) => return Err(ApiError::InternalServerError(anyhow!(err))),
    2976              :         };
    2977              : 
    2978            0 :         response.shards.push(TenantScanRemoteStorageShard {
    2979            0 :             tenant_shard_id,
    2980            0 :             generation: generation.into(),
    2981            0 :             stripe_size,
    2982            0 :         });
    2983              :     }
    2984              : 
    2985            0 :     if response.shards.is_empty() {
    2986            0 :         return Err(ApiError::NotFound(
    2987            0 :             anyhow::anyhow!("No shards found for tenant ID {tenant_id}").into(),
    2988            0 :         ));
    2989            0 :     }
    2990              : 
    2991            0 :     json_response(StatusCode::OK, response)
    2992            0 : }
    2993              : 
    2994            0 : async fn secondary_download_handler(
    2995            0 :     request: Request<Body>,
    2996            0 :     _cancel: CancellationToken,
    2997            0 : ) -> Result<Response<Body>, ApiError> {
    2998            0 :     let state = get_state(&request);
    2999            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3000            0 :     let wait = parse_query_param(&request, "wait_ms")?.map(Duration::from_millis);
    3001              : 
    3002              :     // We don't need this to issue the download request, but:
    3003              :     // - it enables us to cleanly return 404 if we get a request for an absent shard
    3004              :     // - we will use this to provide status feedback in the response
    3005            0 :     let Some(secondary_tenant) = state
    3006            0 :         .tenant_manager
    3007            0 :         .get_secondary_tenant_shard(tenant_shard_id)
    3008              :     else {
    3009            0 :         return Err(ApiError::NotFound(
    3010            0 :             anyhow::anyhow!("Shard {} not found", tenant_shard_id).into(),
    3011            0 :         ));
    3012              :     };
    3013              : 
    3014            0 :     let timeout = wait.unwrap_or(Duration::MAX);
    3015              : 
    3016            0 :     let result = tokio::time::timeout(
    3017            0 :         timeout,
    3018            0 :         state.secondary_controller.download_tenant(tenant_shard_id),
    3019            0 :     )
    3020            0 :     .await;
    3021              : 
    3022            0 :     let progress = secondary_tenant.progress.lock().unwrap().clone();
    3023              : 
    3024            0 :     let status = match result {
    3025              :         Ok(Ok(())) => {
    3026            0 :             if progress.layers_downloaded >= progress.layers_total {
    3027              :                 // Download job ran to completion
    3028            0 :                 StatusCode::OK
    3029              :             } else {
    3030              :                 // Download dropped out without errors because it ran out of time budget
    3031            0 :                 StatusCode::ACCEPTED
    3032              :             }
    3033              :         }
    3034              :         // Edge case: downloads aren't usually fallible: things like a missing heatmap are considered
    3035              :         // okay.  We could get an error here in the unlikely edge case that the tenant
    3036              :         // was detached between our check above and executing the download job.
    3037            0 :         Ok(Err(e)) => return Err(e.into()),
    3038              :         // A timeout is not an error: we have started the download, we're just not done
    3039              :         // yet.  The caller will get a response body indicating status.
    3040            0 :         Err(_) => StatusCode::ACCEPTED,
    3041              :     };
    3042              : 
    3043            0 :     json_response(status, progress)
    3044            0 : }
    3045              : 
    3046            0 : async fn wait_lsn_handler(
    3047            0 :     mut request: Request<Body>,
    3048            0 :     cancel: CancellationToken,
    3049            0 : ) -> Result<Response<Body>, ApiError> {
    3050            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3051            0 :     let wait_lsn_request: TenantWaitLsnRequest = json_request(&mut request).await?;
    3052              : 
    3053            0 :     let state = get_state(&request);
    3054            0 :     let tenant = state
    3055            0 :         .tenant_manager
    3056            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    3057              : 
    3058            0 :     let mut wait_futures = Vec::default();
    3059            0 :     for timeline in tenant.list_timelines() {
    3060            0 :         let Some(lsn) = wait_lsn_request.timelines.get(&timeline.timeline_id) else {
    3061            0 :             continue;
    3062              :         };
    3063              : 
    3064            0 :         let fut = {
    3065            0 :             let timeline = timeline.clone();
    3066            0 :             let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Error);
    3067            0 :             async move {
    3068            0 :                 timeline
    3069            0 :                     .wait_lsn(
    3070            0 :                         *lsn,
    3071            0 :                         WaitLsnWaiter::HttpEndpoint,
    3072            0 :                         WaitLsnTimeout::Custom(wait_lsn_request.timeout),
    3073            0 :                         &ctx,
    3074            0 :                     )
    3075            0 :                     .await
    3076            0 :             }
    3077              :         };
    3078            0 :         wait_futures.push(fut);
    3079              :     }
    3080              : 
    3081            0 :     if wait_futures.is_empty() {
    3082            0 :         return json_response(StatusCode::NOT_FOUND, ());
    3083            0 :     }
    3084              : 
    3085            0 :     let all_done = tokio::select! {
    3086            0 :         results = join_all(wait_futures) => {
    3087            0 :             results.iter().all(|res| res.is_ok())
    3088              :         },
    3089            0 :         _ = cancel.cancelled() => {
    3090            0 :             return Err(ApiError::Cancelled);
    3091              :         }
    3092              :     };
    3093              : 
    3094            0 :     let status = if all_done {
    3095            0 :         StatusCode::OK
    3096              :     } else {
    3097            0 :         StatusCode::ACCEPTED
    3098              :     };
    3099              : 
    3100            0 :     json_response(status, ())
    3101            0 : }
    3102              : 
    3103            0 : async fn secondary_status_handler(
    3104            0 :     request: Request<Body>,
    3105            0 :     _cancel: CancellationToken,
    3106            0 : ) -> Result<Response<Body>, ApiError> {
    3107            0 :     let state = get_state(&request);
    3108            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3109              : 
    3110            0 :     let Some(secondary_tenant) = state
    3111            0 :         .tenant_manager
    3112            0 :         .get_secondary_tenant_shard(tenant_shard_id)
    3113              :     else {
    3114            0 :         return Err(ApiError::NotFound(
    3115            0 :             anyhow::anyhow!("Shard {} not found", tenant_shard_id).into(),
    3116            0 :         ));
    3117              :     };
    3118              : 
    3119            0 :     let progress = secondary_tenant.progress.lock().unwrap().clone();
    3120              : 
    3121            0 :     json_response(StatusCode::OK, progress)
    3122            0 : }
    3123              : 
    3124            0 : async fn handler_404(_: Request<Body>) -> Result<Response<Body>, ApiError> {
    3125            0 :     json_response(
    3126              :         StatusCode::NOT_FOUND,
    3127            0 :         HttpErrorBody::from_msg("page not found".to_owned()),
    3128              :     )
    3129            0 : }
    3130              : 
    3131            0 : async fn post_tracing_event_handler(
    3132            0 :     mut r: Request<Body>,
    3133            0 :     _cancel: CancellationToken,
    3134            0 : ) -> Result<Response<Body>, ApiError> {
    3135            0 :     #[derive(Debug, serde::Deserialize)]
    3136              :     #[serde(rename_all = "lowercase")]
    3137              :     enum Level {
    3138              :         Error,
    3139              :         Warn,
    3140              :         Info,
    3141              :         Debug,
    3142              :         Trace,
    3143              :     }
    3144            0 :     #[derive(Debug, serde::Deserialize)]
    3145              :     struct Request {
    3146              :         level: Level,
    3147              :         message: String,
    3148              :     }
    3149            0 :     let body: Request = json_request(&mut r)
    3150            0 :         .await
    3151            0 :         .map_err(|_| ApiError::BadRequest(anyhow::anyhow!("invalid JSON body")))?;
    3152              : 
    3153            0 :     match body.level {
    3154            0 :         Level::Error => tracing::error!(?body.message),
    3155            0 :         Level::Warn => tracing::warn!(?body.message),
    3156            0 :         Level::Info => tracing::info!(?body.message),
    3157            0 :         Level::Debug => tracing::debug!(?body.message),
    3158            0 :         Level::Trace => tracing::trace!(?body.message),
    3159              :     }
    3160              : 
    3161            0 :     json_response(StatusCode::OK, ())
    3162            0 : }
    3163              : 
    3164            0 : async fn put_io_engine_handler(
    3165            0 :     mut r: Request<Body>,
    3166            0 :     _cancel: CancellationToken,
    3167            0 : ) -> Result<Response<Body>, ApiError> {
    3168            0 :     check_permission(&r, None)?;
    3169            0 :     let kind: crate::virtual_file::IoEngineKind = json_request(&mut r).await?;
    3170            0 :     crate::virtual_file::io_engine::set(kind);
    3171            0 :     json_response(StatusCode::OK, ())
    3172            0 : }
    3173              : 
    3174            0 : async fn put_io_mode_handler(
    3175            0 :     mut r: Request<Body>,
    3176            0 :     _cancel: CancellationToken,
    3177            0 : ) -> Result<Response<Body>, ApiError> {
    3178            0 :     check_permission(&r, None)?;
    3179            0 :     let mode: IoMode = json_request(&mut r).await?;
    3180            0 :     crate::virtual_file::set_io_mode(mode);
    3181            0 :     json_response(StatusCode::OK, ())
    3182            0 : }
    3183              : 
    3184              : /// Polled by control plane.
    3185              : ///
    3186              : /// See [`crate::utilization`].
    3187            0 : async fn get_utilization(
    3188            0 :     r: Request<Body>,
    3189            0 :     _cancel: CancellationToken,
    3190            0 : ) -> Result<Response<Body>, ApiError> {
    3191            0 :     fail::fail_point!("get-utilization-http-handler", |_| {
    3192            0 :         Err(ApiError::ResourceUnavailable("failpoint".into()))
    3193            0 :     });
    3194              : 
    3195              :     // this probably could be completely public, but lets make that change later.
    3196            0 :     check_permission(&r, None)?;
    3197              : 
    3198            0 :     let state = get_state(&r);
    3199            0 :     let mut g = state.latest_utilization.lock().await;
    3200              : 
    3201            0 :     let regenerate_every = Duration::from_secs(1);
    3202            0 :     let still_valid = g
    3203            0 :         .as_ref()
    3204            0 :         .is_some_and(|(captured_at, _)| captured_at.elapsed() < regenerate_every);
    3205              : 
    3206              :     // avoid needless statvfs calls even though those should be non-blocking fast.
    3207              :     // regenerate at most 1Hz to allow polling at any rate.
    3208            0 :     if !still_valid {
    3209            0 :         let path = state.conf.tenants_path();
    3210            0 :         let doc =
    3211            0 :             crate::utilization::regenerate(state.conf, path.as_std_path(), &state.tenant_manager)
    3212            0 :                 .map_err(ApiError::InternalServerError)?;
    3213              : 
    3214            0 :         let mut buf = Vec::new();
    3215            0 :         serde_json::to_writer(&mut buf, &doc)
    3216            0 :             .context("serialize")
    3217            0 :             .map_err(ApiError::InternalServerError)?;
    3218              : 
    3219            0 :         let body = bytes::Bytes::from(buf);
    3220              : 
    3221            0 :         *g = Some((std::time::Instant::now(), body));
    3222            0 :     }
    3223              : 
    3224              :     // hyper 0.14 doesn't yet have Response::clone so this is a bit of extra legwork
    3225            0 :     let cached = g.as_ref().expect("just set").1.clone();
    3226              : 
    3227            0 :     Response::builder()
    3228            0 :         .header(hyper::http::header::CONTENT_TYPE, "application/json")
    3229              :         // thought of using http date header, but that is second precision which does not give any
    3230              :         // debugging aid
    3231            0 :         .status(StatusCode::OK)
    3232            0 :         .body(hyper::Body::from(cached))
    3233            0 :         .context("build response")
    3234            0 :         .map_err(ApiError::InternalServerError)
    3235            0 : }
    3236              : 
    3237              : /// HADRON
    3238            0 : async fn list_tenant_visible_size_handler(
    3239            0 :     request: Request<Body>,
    3240            0 :     _cancel: CancellationToken,
    3241            0 : ) -> Result<Response<Body>, ApiError> {
    3242            0 :     check_permission(&request, None)?;
    3243            0 :     let state = get_state(&request);
    3244              : 
    3245            0 :     let mut map = BTreeMap::new();
    3246            0 :     for (tenant_shard_id, slot) in state.tenant_manager.list() {
    3247            0 :         match slot {
    3248            0 :             TenantSlot::Attached(tenant) => {
    3249            0 :                 let visible_size = tenant.get_visible_size();
    3250            0 :                 map.insert(tenant_shard_id, visible_size);
    3251            0 :             }
    3252              :             TenantSlot::Secondary(_) | TenantSlot::InProgress(_) => {
    3253            0 :                 continue;
    3254              :             }
    3255              :         }
    3256              :     }
    3257              : 
    3258            0 :     json_response(StatusCode::OK, map)
    3259            0 : }
    3260              : 
    3261            0 : async fn list_aux_files(
    3262            0 :     mut request: Request<Body>,
    3263            0 :     _cancel: CancellationToken,
    3264            0 : ) -> Result<Response<Body>, ApiError> {
    3265            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3266            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    3267            0 :     let body: ListAuxFilesRequest = json_request(&mut request).await?;
    3268            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    3269              : 
    3270            0 :     let state = get_state(&request);
    3271              : 
    3272            0 :     let timeline =
    3273            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    3274            0 :             .await?;
    3275              : 
    3276            0 :     let io_concurrency = IoConcurrency::spawn_from_conf(
    3277            0 :         state.conf.get_vectored_concurrent_io,
    3278            0 :         timeline.gate.enter().map_err(|_| ApiError::Cancelled)?,
    3279              :     );
    3280              : 
    3281            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download)
    3282            0 :         .with_scope_timeline(&timeline);
    3283            0 :     let files = timeline
    3284            0 :         .list_aux_files(body.lsn, &ctx, io_concurrency)
    3285            0 :         .await?;
    3286            0 :     json_response(StatusCode::OK, files)
    3287            0 : }
    3288              : 
    3289            0 : async fn perf_info(
    3290            0 :     request: Request<Body>,
    3291            0 :     _cancel: CancellationToken,
    3292            0 : ) -> Result<Response<Body>, ApiError> {
    3293            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3294            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    3295            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    3296              : 
    3297            0 :     let state = get_state(&request);
    3298              : 
    3299            0 :     let timeline =
    3300            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    3301            0 :             .await?;
    3302              : 
    3303            0 :     let result = timeline.perf_info().await;
    3304              : 
    3305            0 :     json_response(StatusCode::OK, result)
    3306            0 : }
    3307              : 
    3308            0 : async fn ingest_aux_files(
    3309            0 :     mut request: Request<Body>,
    3310            0 :     _cancel: CancellationToken,
    3311            0 : ) -> Result<Response<Body>, ApiError> {
    3312            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3313            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    3314            0 :     let body: IngestAuxFilesRequest = json_request(&mut request).await?;
    3315            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    3316              : 
    3317            0 :     let state = get_state(&request);
    3318              : 
    3319            0 :     let timeline =
    3320            0 :         active_timeline_of_active_tenant(&state.tenant_manager, tenant_shard_id, timeline_id)
    3321            0 :             .await?;
    3322              : 
    3323            0 :     let mut modification = timeline.begin_modification(
    3324            0 :         Lsn(timeline.get_last_record_lsn().0 + 8), /* advance LSN by 8 */
    3325            0 :     );
    3326            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Download);
    3327            0 :     for (fname, content) in body.aux_files {
    3328            0 :         modification
    3329            0 :             .put_file(&fname, content.as_bytes(), &ctx)
    3330            0 :             .await
    3331            0 :             .map_err(|e| ApiError::InternalServerError(e.into()))?;
    3332              :     }
    3333            0 :     modification
    3334            0 :         .commit(&ctx)
    3335            0 :         .await
    3336            0 :         .map_err(ApiError::InternalServerError)?;
    3337              : 
    3338            0 :     json_response(StatusCode::OK, ())
    3339            0 : }
    3340              : 
    3341              : /// Report on the largest tenants on this pageserver, for the storage controller to identify
    3342              : /// candidates for splitting
    3343            0 : async fn post_top_tenants(
    3344            0 :     mut r: Request<Body>,
    3345            0 :     _cancel: CancellationToken,
    3346            0 : ) -> Result<Response<Body>, ApiError> {
    3347            0 :     check_permission(&r, None)?;
    3348            0 :     let request: TopTenantShardsRequest = json_request(&mut r).await?;
    3349            0 :     let state = get_state(&r);
    3350              : 
    3351            0 :     fn get_size_metric(sizes: &TopTenantShardItem, order_by: &TenantSorting) -> u64 {
    3352            0 :         match order_by {
    3353            0 :             TenantSorting::ResidentSize => sizes.resident_size,
    3354            0 :             TenantSorting::MaxLogicalSize => sizes.max_logical_size,
    3355            0 :             TenantSorting::MaxLogicalSizePerShard => sizes.max_logical_size_per_shard,
    3356              :         }
    3357            0 :     }
    3358              : 
    3359              :     #[derive(Eq, PartialEq)]
    3360              :     struct HeapItem {
    3361              :         metric: u64,
    3362              :         sizes: TopTenantShardItem,
    3363              :     }
    3364              : 
    3365              :     impl PartialOrd for HeapItem {
    3366            0 :         fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
    3367            0 :             Some(self.cmp(other))
    3368            0 :         }
    3369              :     }
    3370              : 
    3371              :     /// Heap items have reverse ordering on their metric: this enables using BinaryHeap, which
    3372              :     /// supports popping the greatest item but not the smallest.
    3373              :     impl Ord for HeapItem {
    3374            0 :         fn cmp(&self, other: &Self) -> std::cmp::Ordering {
    3375            0 :             Reverse(self.metric).cmp(&Reverse(other.metric))
    3376            0 :         }
    3377              :     }
    3378              : 
    3379            0 :     let mut top_n: BinaryHeap<HeapItem> = BinaryHeap::with_capacity(request.limit);
    3380              : 
    3381              :     // FIXME: this is a lot of clones to take this tenant list
    3382            0 :     for (tenant_shard_id, tenant_slot) in state.tenant_manager.list() {
    3383            0 :         if let Some(shards_lt) = request.where_shards_lt {
    3384              :             // Ignore tenants which already have >= this many shards
    3385            0 :             if tenant_shard_id.shard_count >= shards_lt {
    3386            0 :                 continue;
    3387            0 :             }
    3388            0 :         }
    3389              : 
    3390            0 :         let sizes = match tenant_slot {
    3391            0 :             TenantSlot::Attached(tenant) => tenant.get_sizes(),
    3392              :             TenantSlot::Secondary(_) | TenantSlot::InProgress(_) => {
    3393            0 :                 continue;
    3394              :             }
    3395              :         };
    3396            0 :         let metric = get_size_metric(&sizes, &request.order_by);
    3397              : 
    3398            0 :         if let Some(gt) = request.where_gt {
    3399              :             // Ignore tenants whose metric is <= the lower size threshold, to do less sorting work
    3400            0 :             if metric <= gt {
    3401            0 :                 continue;
    3402            0 :             }
    3403            0 :         };
    3404              : 
    3405            0 :         match top_n.peek() {
    3406            0 :             None => {
    3407            0 :                 // Top N list is empty: candidate becomes first member
    3408            0 :                 top_n.push(HeapItem { metric, sizes });
    3409            0 :             }
    3410            0 :             Some(i) if i.metric > metric && top_n.len() < request.limit => {
    3411            0 :                 // Lowest item in list is greater than our candidate, but we aren't at limit yet: push to end
    3412            0 :                 top_n.push(HeapItem { metric, sizes });
    3413            0 :             }
    3414            0 :             Some(i) if i.metric > metric => {
    3415            0 :                 // List is at limit and lowest value is greater than our candidate, drop it.
    3416            0 :             }
    3417            0 :             Some(_) => top_n.push(HeapItem { metric, sizes }),
    3418              :         }
    3419              : 
    3420            0 :         while top_n.len() > request.limit {
    3421            0 :             top_n.pop();
    3422            0 :         }
    3423              :     }
    3424              : 
    3425            0 :     json_response(
    3426              :         StatusCode::OK,
    3427              :         TopTenantShardsResponse {
    3428            0 :             shards: top_n.into_iter().map(|i| i.sizes).collect(),
    3429              :         },
    3430              :     )
    3431            0 : }
    3432              : 
    3433            0 : async fn put_tenant_timeline_import_basebackup(
    3434            0 :     request: Request<Body>,
    3435            0 :     _cancel: CancellationToken,
    3436            0 : ) -> Result<Response<Body>, ApiError> {
    3437            0 :     let tenant_id: TenantId = parse_request_param(&request, "tenant_id")?;
    3438            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    3439            0 :     let base_lsn: Lsn = must_parse_query_param(&request, "base_lsn")?;
    3440            0 :     let end_lsn: Lsn = must_parse_query_param(&request, "end_lsn")?;
    3441            0 :     let pg_version: PgMajorVersion = must_parse_query_param(&request, "pg_version")?;
    3442              : 
    3443            0 :     check_permission(&request, Some(tenant_id))?;
    3444              : 
    3445            0 :     let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
    3446              : 
    3447            0 :     let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    3448              : 
    3449            0 :     let span = info_span!("import_basebackup",
    3450            0 :         tenant_id=%tenant_id, timeline_id=%timeline_id, shard_id=%tenant_shard_id.shard_slug(),
    3451              :         base_lsn=%base_lsn, end_lsn=%end_lsn, pg_version=%pg_version);
    3452            0 :     async move {
    3453            0 :         let state = get_state(&request);
    3454            0 :         let tenant = state
    3455            0 :             .tenant_manager
    3456            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    3457              : 
    3458            0 :         let broker_client = state.broker_client.clone();
    3459              : 
    3460            0 :         let mut body = StreamReader::new(
    3461            0 :             request
    3462            0 :                 .into_body()
    3463            0 :                 .map(|res| res.map_err(|error| std::io::Error::other(anyhow::anyhow!(error)))),
    3464              :         );
    3465              : 
    3466            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    3467              : 
    3468            0 :         let (timeline, timeline_ctx) = tenant
    3469            0 :             .create_empty_timeline(timeline_id, base_lsn, pg_version, &ctx)
    3470            0 :             .map_err(ApiError::InternalServerError)
    3471            0 :             .await?;
    3472              : 
    3473              :         // TODO mark timeline as not ready until it reaches end_lsn.
    3474              :         // We might have some wal to import as well, and we should prevent compute
    3475              :         // from connecting before that and writing conflicting wal.
    3476              :         //
    3477              :         // This is not relevant for pageserver->pageserver migrations, since there's
    3478              :         // no wal to import. But should be fixed if we want to import from postgres.
    3479              : 
    3480              :         // TODO leave clean state on error. For now you can use detach to clean
    3481              :         // up broken state from a failed import.
    3482              : 
    3483              :         // Import basebackup provided via CopyData
    3484            0 :         info!("importing basebackup");
    3485              : 
    3486            0 :         timeline
    3487            0 :             .import_basebackup_from_tar(
    3488            0 :                 tenant.clone(),
    3489            0 :                 &mut body,
    3490            0 :                 base_lsn,
    3491            0 :                 broker_client,
    3492            0 :                 &timeline_ctx,
    3493            0 :             )
    3494            0 :             .await
    3495            0 :             .map_err(ApiError::InternalServerError)?;
    3496              : 
    3497              :         // Read the end of the tar archive.
    3498            0 :         read_tar_eof(body)
    3499            0 :             .await
    3500            0 :             .map_err(ApiError::InternalServerError)?;
    3501              : 
    3502              :         // TODO check checksum
    3503              :         // Meanwhile you can verify client-side by taking fullbackup
    3504              :         // and checking that it matches in size with what was imported.
    3505              :         // It wouldn't work if base came from vanilla postgres though,
    3506              :         // since we discard some log files.
    3507              : 
    3508            0 :         info!("done");
    3509            0 :         json_response(StatusCode::OK, ())
    3510            0 :     }
    3511            0 :     .instrument(span)
    3512            0 :     .await
    3513            0 : }
    3514              : 
    3515            0 : async fn put_tenant_timeline_import_wal(
    3516            0 :     request: Request<Body>,
    3517            0 :     _cancel: CancellationToken,
    3518            0 : ) -> Result<Response<Body>, ApiError> {
    3519            0 :     let tenant_id: TenantId = parse_request_param(&request, "tenant_id")?;
    3520            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    3521            0 :     let start_lsn: Lsn = must_parse_query_param(&request, "start_lsn")?;
    3522            0 :     let end_lsn: Lsn = must_parse_query_param(&request, "end_lsn")?;
    3523              : 
    3524            0 :     check_permission(&request, Some(tenant_id))?;
    3525              : 
    3526            0 :     let span = info_span!("import_wal", tenant_id=%tenant_id, timeline_id=%timeline_id, start_lsn=%start_lsn, end_lsn=%end_lsn);
    3527            0 :     async move {
    3528            0 :         let state = get_state(&request);
    3529              : 
    3530            0 :         let timeline = active_timeline_of_active_tenant(&state.tenant_manager, TenantShardId::unsharded(tenant_id), timeline_id).await?;
    3531            0 :         let ctx = RequestContextBuilder::new(TaskKind::MgmtRequest)
    3532            0 :             .download_behavior(DownloadBehavior::Warn)
    3533            0 :             .scope(context::Scope::new_timeline(&timeline))
    3534            0 :             .root();
    3535              : 
    3536            0 :         let mut body = StreamReader::new(request.into_body().map(|res| {
    3537            0 :             res.map_err(|error| {
    3538            0 :                 std::io::Error::other( anyhow::anyhow!(error))
    3539            0 :             })
    3540            0 :         }));
    3541              : 
    3542            0 :         let last_record_lsn = timeline.get_last_record_lsn();
    3543            0 :         if last_record_lsn != start_lsn {
    3544            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!("Cannot import WAL from Lsn {start_lsn} because timeline does not start from the same lsn: {last_record_lsn}")));
    3545            0 :         }
    3546              : 
    3547              :         // TODO leave clean state on error. For now you can use detach to clean
    3548              :         // up broken state from a failed import.
    3549              : 
    3550              :         // Import wal provided via CopyData
    3551            0 :         info!("importing wal");
    3552            0 :         crate::import_datadir::import_wal_from_tar(&timeline, &mut body, start_lsn, end_lsn, &ctx).await.map_err(ApiError::InternalServerError)?;
    3553            0 :         info!("wal import complete");
    3554              : 
    3555              :         // Read the end of the tar archive.
    3556            0 :         read_tar_eof(body).await.map_err(ApiError::InternalServerError)?;
    3557              : 
    3558              :         // TODO Does it make sense to overshoot?
    3559            0 :         if timeline.get_last_record_lsn() < end_lsn {
    3560            0 :             return Err(ApiError::InternalServerError(anyhow::anyhow!("Cannot import WAL from Lsn {start_lsn} because timeline does not start from the same lsn: {last_record_lsn}")));
    3561            0 :         }
    3562              : 
    3563              :         // Flush data to disk, then upload to s3. No need for a forced checkpoint.
    3564              :         // We only want to persist the data, and it doesn't matter if it's in the
    3565              :         // shape of deltas or images.
    3566            0 :         info!("flushing layers");
    3567            0 :         timeline.freeze_and_flush().await.map_err(|e| match e {
    3568            0 :             tenant::timeline::FlushLayerError::Cancelled => ApiError::ShuttingDown,
    3569            0 :             other => ApiError::InternalServerError(anyhow::anyhow!(other)),
    3570            0 :         })?;
    3571              : 
    3572            0 :         info!("done");
    3573              : 
    3574            0 :         json_response(StatusCode::OK, ())
    3575            0 :     }.instrument(span).await
    3576            0 : }
    3577              : 
    3578              : /// Activate a timeline after its import has completed
    3579              : ///
    3580              : /// The endpoint is idempotent and callers are expected to retry all
    3581              : /// errors until a successful response.
    3582            0 : async fn activate_post_import_handler(
    3583            0 :     request: Request<Body>,
    3584            0 :     _cancel: CancellationToken,
    3585            0 : ) -> Result<Response<Body>, ApiError> {
    3586            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3587            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    3588              : 
    3589            0 :     let timeline_id: TimelineId = parse_request_param(&request, "timeline_id")?;
    3590              :     const DEFAULT_ACTIVATE_TIMEOUT: Duration = Duration::from_secs(1);
    3591            0 :     let activate_timeout = parse_query_param(&request, "timeline_activate_timeout_ms")?
    3592            0 :         .map(Duration::from_millis)
    3593            0 :         .unwrap_or(DEFAULT_ACTIVATE_TIMEOUT);
    3594              : 
    3595            0 :     let span = info_span!(
    3596              :         "activate_post_import_handler",
    3597              :         tenant_id=%tenant_shard_id.tenant_id,
    3598              :         timeline_id=%timeline_id,
    3599            0 :         shard_id=%tenant_shard_id.shard_slug()
    3600              :     );
    3601              : 
    3602            0 :     async move {
    3603            0 :         let state = get_state(&request);
    3604            0 :         let tenant = state
    3605            0 :             .tenant_manager
    3606            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    3607              : 
    3608            0 :         tenant.wait_to_become_active(ACTIVE_TENANT_TIMEOUT).await?;
    3609              : 
    3610            0 :         tenant.finalize_importing_timeline(timeline_id).await?;
    3611              : 
    3612            0 :         match tenant.get_timeline(timeline_id, false) {
    3613            0 :             Ok(_timeline) => {
    3614            0 :                 // Timeline is already visible. Reset not required: fall through.
    3615            0 :             }
    3616              :             Err(GetTimelineError::NotFound { .. }) => {
    3617              :                 // This is crude: we reset the whole tenant such that the new timeline is detected
    3618              :                 // and activated. We can come up with something more granular in the future.
    3619              :                 //
    3620              :                 // Note that we only reset the tenant if required: when the timeline is
    3621              :                 // not present in [`Tenant::timelines`].
    3622            0 :                 let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn);
    3623            0 :                 state
    3624            0 :                     .tenant_manager
    3625            0 :                     .reset_tenant(tenant_shard_id, false, &ctx)
    3626            0 :                     .await
    3627            0 :                     .map_err(ApiError::InternalServerError)?;
    3628              :             }
    3629              :             Err(GetTimelineError::ShuttingDown) => {
    3630            0 :                 return Err(ApiError::ShuttingDown);
    3631              :             }
    3632              :             Err(GetTimelineError::NotActive { .. }) => {
    3633            0 :                 unreachable!("Called get_timeline with active_only=false");
    3634              :             }
    3635              :         }
    3636              : 
    3637            0 :         let timeline = tenant.get_timeline(timeline_id, false)?;
    3638              : 
    3639            0 :         let ctx = RequestContext::new(TaskKind::MgmtRequest, DownloadBehavior::Warn)
    3640            0 :             .with_scope_timeline(&timeline);
    3641              : 
    3642            0 :         let result =
    3643            0 :             tokio::time::timeout(activate_timeout, timeline.wait_to_become_active(&ctx)).await;
    3644            0 :         match result {
    3645            0 :             Ok(Ok(())) => {
    3646            0 :                 // fallthrough
    3647            0 :             }
    3648              :             // Timeline reached some other state that's not active
    3649              :             // TODO(vlad): if the tenant is broken, return a permananet error
    3650            0 :             Ok(Err(_timeline_state)) => {
    3651            0 :                 return Err(ApiError::InternalServerError(anyhow::anyhow!(
    3652            0 :                     "Timeline activation failed"
    3653            0 :                 )));
    3654              :             }
    3655              :             // Activation timed out
    3656              :             Err(_) => {
    3657            0 :                 return Err(ApiError::Timeout("Timeline activation timed out".into()));
    3658              :             }
    3659              :         }
    3660              : 
    3661            0 :         let timeline_info = build_timeline_info(
    3662            0 :             &timeline, false, // include_non_incremental_logical_size,
    3663            0 :             false, // force_await_initial_logical_size
    3664            0 :             false, // include_image_consistent_lsn
    3665            0 :             &ctx,
    3666            0 :         )
    3667            0 :         .await
    3668            0 :         .context("get local timeline info")
    3669            0 :         .map_err(ApiError::InternalServerError)?;
    3670              : 
    3671            0 :         json_response(StatusCode::OK, timeline_info)
    3672            0 :     }
    3673            0 :     .instrument(span)
    3674            0 :     .await
    3675            0 : }
    3676              : 
    3677              : // [Hadron] Reset gauge metrics that are used to raised alerts. We need this API as a stop-gap measure to reset alerts
    3678              : // after we manually rectify situations such as local SSD data loss. We will eventually automate this.
    3679            0 : async fn hadron_reset_alert_gauges(
    3680            0 :     request: Request<Body>,
    3681            0 :     _cancel: CancellationToken,
    3682            0 : ) -> Result<Response<Body>, ApiError> {
    3683            0 :     check_permission(&request, None)?;
    3684            0 :     LOCAL_DATA_LOSS_SUSPECTED.set(0);
    3685            0 :     json_response(StatusCode::OK, ())
    3686            0 : }
    3687              : 
    3688              : /// Read the end of a tar archive.
    3689              : ///
    3690              : /// A tar archive normally ends with two consecutive blocks of zeros, 512 bytes each.
    3691              : /// `tokio_tar` already read the first such block. Read the second all-zeros block,
    3692              : /// and check that there is no more data after the EOF marker.
    3693              : ///
    3694              : /// 'tar' command can also write extra blocks of zeros, up to a record
    3695              : /// size, controlled by the --record-size argument. Ignore them too.
    3696            0 : async fn read_tar_eof(mut reader: (impl tokio::io::AsyncRead + Unpin)) -> anyhow::Result<()> {
    3697              :     use tokio::io::AsyncReadExt;
    3698            0 :     let mut buf = [0u8; 512];
    3699              : 
    3700              :     // Read the all-zeros block, and verify it
    3701            0 :     let mut total_bytes = 0;
    3702            0 :     while total_bytes < 512 {
    3703            0 :         let nbytes = reader.read(&mut buf[total_bytes..]).await?;
    3704            0 :         total_bytes += nbytes;
    3705            0 :         if nbytes == 0 {
    3706            0 :             break;
    3707            0 :         }
    3708              :     }
    3709            0 :     if total_bytes < 512 {
    3710            0 :         anyhow::bail!("incomplete or invalid tar EOF marker");
    3711            0 :     }
    3712            0 :     if !buf.iter().all(|&x| x == 0) {
    3713            0 :         anyhow::bail!("invalid tar EOF marker");
    3714            0 :     }
    3715              : 
    3716              :     // Drain any extra zero-blocks after the EOF marker
    3717            0 :     let mut trailing_bytes = 0;
    3718            0 :     let mut seen_nonzero_bytes = false;
    3719              :     loop {
    3720            0 :         let nbytes = reader.read(&mut buf).await?;
    3721            0 :         trailing_bytes += nbytes;
    3722            0 :         if !buf.iter().all(|&x| x == 0) {
    3723            0 :             seen_nonzero_bytes = true;
    3724            0 :         }
    3725            0 :         if nbytes == 0 {
    3726            0 :             break;
    3727            0 :         }
    3728              :     }
    3729            0 :     if seen_nonzero_bytes {
    3730            0 :         anyhow::bail!("unexpected non-zero bytes after the tar archive");
    3731            0 :     }
    3732            0 :     if trailing_bytes % 512 != 0 {
    3733            0 :         anyhow::bail!(
    3734            0 :             "unexpected number of zeros ({trailing_bytes}), not divisible by tar block size (512 bytes), after the tar archive"
    3735              :         );
    3736            0 :     }
    3737            0 :     Ok(())
    3738            0 : }
    3739              : 
    3740            0 : async fn force_refresh_feature_flag(
    3741            0 :     request: Request<Body>,
    3742            0 :     _cancel: CancellationToken,
    3743            0 : ) -> Result<Response<Body>, ApiError> {
    3744            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3745            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    3746              : 
    3747            0 :     let state = get_state(&request);
    3748            0 :     let tenant = state
    3749            0 :         .tenant_manager
    3750            0 :         .get_attached_tenant_shard(tenant_shard_id)?;
    3751            0 :     tenant
    3752            0 :         .feature_resolver
    3753            0 :         .refresh_properties_and_flags(&tenant);
    3754            0 :     json_response(StatusCode::OK, ())
    3755            0 : }
    3756              : 
    3757            0 : async fn tenant_evaluate_feature_flag(
    3758            0 :     request: Request<Body>,
    3759            0 :     _cancel: CancellationToken,
    3760            0 : ) -> Result<Response<Body>, ApiError> {
    3761            0 :     let tenant_shard_id: TenantShardId = parse_request_param(&request, "tenant_shard_id")?;
    3762            0 :     check_permission(&request, Some(tenant_shard_id.tenant_id))?;
    3763              : 
    3764            0 :     let flag: String = parse_request_param(&request, "flag_key")?;
    3765            0 :     let as_type: Option<String> = parse_query_param(&request, "as")?;
    3766              : 
    3767            0 :     let state = get_state(&request);
    3768              : 
    3769            0 :     async {
    3770            0 :         let tenant = state
    3771            0 :             .tenant_manager
    3772            0 :             .get_attached_tenant_shard(tenant_shard_id)?;
    3773              :         // TODO: the properties we get here might be stale right after it is collected. But such races are rare (updated every 10s)
    3774              :         // and we don't need to worry about it for now.
    3775            0 :         let properties = tenant.feature_resolver.collect_properties();
    3776            0 :         if as_type.as_deref() == Some("boolean") {
    3777            0 :             let result = tenant.feature_resolver.evaluate_boolean(&flag);
    3778            0 :             let result = result.map(|_| true).map_err(|e| e.to_string());
    3779            0 :             json_response(StatusCode::OK, json!({ "result": result, "properties": properties }))
    3780            0 :         } else if as_type.as_deref() == Some("multivariate") {
    3781            0 :             let result = tenant.feature_resolver.evaluate_multivariate(&flag).map_err(|e| e.to_string());
    3782            0 :             json_response(StatusCode::OK, json!({ "result": result, "properties": properties }))
    3783              :         } else {
    3784              :             // Auto infer the type of the feature flag.
    3785            0 :             let is_boolean = tenant.feature_resolver.is_feature_flag_boolean(&flag).map_err(|e| ApiError::InternalServerError(anyhow::anyhow!("{e}")))?;
    3786            0 :             if is_boolean {
    3787            0 :                 let result = tenant.feature_resolver.evaluate_boolean(&flag);
    3788            0 :                 let result = result.map(|_| true).map_err(|e| e.to_string());
    3789            0 :                 json_response(StatusCode::OK, json!({ "result": result, "properties": properties }))
    3790              :             } else {
    3791            0 :                 let result = tenant.feature_resolver.evaluate_multivariate(&flag).map_err(|e| e.to_string());
    3792            0 :                 json_response(StatusCode::OK, json!({ "result": result, "properties": properties }))
    3793              :             }
    3794              :         }
    3795            0 :     }
    3796            0 :     .instrument(info_span!("tenant_evaluate_feature_flag", tenant_id = %tenant_shard_id.tenant_id, shard_id = %tenant_shard_id.shard_slug()))
    3797            0 :     .await
    3798            0 : }
    3799              : 
    3800            0 : async fn force_override_feature_flag_for_testing_put(
    3801            0 :     request: Request<Body>,
    3802            0 :     _cancel: CancellationToken,
    3803            0 : ) -> Result<Response<Body>, ApiError> {
    3804            0 :     check_permission(&request, None)?;
    3805              : 
    3806            0 :     let flag: String = parse_request_param(&request, "flag_key")?;
    3807            0 :     let value: String = must_parse_query_param(&request, "value")?;
    3808            0 :     let state = get_state(&request);
    3809            0 :     state
    3810            0 :         .feature_resolver
    3811            0 :         .force_override_for_testing(&flag, Some(&value));
    3812            0 :     json_response(StatusCode::OK, ())
    3813            0 : }
    3814              : 
    3815            0 : async fn force_override_feature_flag_for_testing_delete(
    3816            0 :     request: Request<Body>,
    3817            0 :     _cancel: CancellationToken,
    3818            0 : ) -> Result<Response<Body>, ApiError> {
    3819            0 :     check_permission(&request, None)?;
    3820              : 
    3821            0 :     let flag: String = parse_request_param(&request, "flag_key")?;
    3822            0 :     let state = get_state(&request);
    3823            0 :     state
    3824            0 :         .feature_resolver
    3825            0 :         .force_override_for_testing(&flag, None);
    3826            0 :     json_response(StatusCode::OK, ())
    3827            0 : }
    3828              : 
    3829            0 : async fn update_feature_flag_spec(
    3830            0 :     mut request: Request<Body>,
    3831            0 :     _cancel: CancellationToken,
    3832            0 : ) -> Result<Response<Body>, ApiError> {
    3833            0 :     check_permission(&request, None)?;
    3834            0 :     let body = json_request(&mut request).await?;
    3835            0 :     let state = get_state(&request);
    3836            0 :     state
    3837            0 :         .feature_resolver
    3838            0 :         .update(body)
    3839            0 :         .map_err(ApiError::InternalServerError)?;
    3840            0 :     json_response(StatusCode::OK, ())
    3841            0 : }
    3842              : 
    3843              : /// Common functionality of all the HTTP API handlers.
    3844              : ///
    3845              : /// - Adds a tracing span to each request (by `request_span`)
    3846              : /// - Logs the request depending on the request method (by `request_span`)
    3847              : /// - Logs the response if it was not successful (by `request_span`
    3848              : /// - Shields the handler function from async cancellations. Hyper can drop the handler
    3849              : ///   Future if the connection to the client is lost, but most of the pageserver code is
    3850              : ///   not async cancellation safe. This converts the dropped future into a graceful cancellation
    3851              : ///   request with a CancellationToken.
    3852            0 : async fn api_handler<R, H>(request: Request<Body>, handler: H) -> Result<Response<Body>, ApiError>
    3853            0 : where
    3854            0 :     R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
    3855            0 :     H: FnOnce(Request<Body>, CancellationToken) -> R + Send + Sync + 'static,
    3856            0 : {
    3857            0 :     if request.uri() != &"/v1/failpoints".parse::<Uri>().unwrap() {
    3858            0 :         fail::fail_point!("api-503", |_| Err(ApiError::ResourceUnavailable(
    3859            0 :             "failpoint".into()
    3860            0 :         )));
    3861              : 
    3862            0 :         fail::fail_point!("api-500", |_| Err(ApiError::InternalServerError(
    3863            0 :             anyhow::anyhow!("failpoint")
    3864            0 :         )));
    3865            0 :     }
    3866              : 
    3867              :     // Spawn a new task to handle the request, to protect the handler from unexpected
    3868              :     // async cancellations. Most pageserver functions are not async cancellation safe.
    3869              :     // We arm a drop-guard, so that if Hyper drops the Future, we signal the task
    3870              :     // with the cancellation token.
    3871            0 :     let token = CancellationToken::new();
    3872            0 :     let cancel_guard = token.clone().drop_guard();
    3873            0 :     let result = request_span(request, move |r| async {
    3874            0 :         let handle = tokio::spawn(
    3875            0 :             async {
    3876            0 :                 let token_cloned = token.clone();
    3877            0 :                 let result = handler(r, token).await;
    3878            0 :                 if token_cloned.is_cancelled() {
    3879              :                     // dropguard has executed: we will never turn this result into response.
    3880              :                     //
    3881              :                     // at least temporarily do {:?} logging; these failures are rare enough but
    3882              :                     // could hide difficult errors.
    3883            0 :                     match &result {
    3884            0 :                         Ok(response) => {
    3885            0 :                             let status = response.status();
    3886            0 :                             info!(%status, "Cancelled request finished successfully")
    3887              :                         }
    3888            0 :                         Err(e) => match e {
    3889              :                             ApiError::ShuttingDown | ApiError::ResourceUnavailable(_) => {
    3890              :                                 // Don't log this at error severity: they are normal during lifecycle of tenants/process
    3891            0 :                                 info!("Cancelled request aborted for shutdown")
    3892              :                             }
    3893              :                             _ => {
    3894              :                                 // Log these in a highly visible way, because we have no client to send the response to, but
    3895              :                                 // would like to know that something went wrong.
    3896            0 :                                 error!("Cancelled request finished with an error: {e:?}")
    3897              :                             }
    3898              :                         },
    3899              :                     }
    3900            0 :                 }
    3901              :                 // only logging for cancelled panicked request handlers is the tracing_panic_hook,
    3902              :                 // which should suffice.
    3903              :                 //
    3904              :                 // there is still a chance to lose the result due to race between
    3905              :                 // returning from here and the actual connection closing happening
    3906              :                 // before outer task gets to execute. leaving that up for #5815.
    3907            0 :                 result
    3908            0 :             }
    3909            0 :             .in_current_span(),
    3910              :         );
    3911              : 
    3912            0 :         match handle.await {
    3913              :             // TODO: never actually return Err from here, always Ok(...) so that we can log
    3914              :             // spanned errors. Call api_error_handler instead and return appropriate Body.
    3915            0 :             Ok(result) => result,
    3916            0 :             Err(e) => {
    3917              :                 // The handler task panicked. We have a global panic handler that logs the
    3918              :                 // panic with its backtrace, so no need to log that here. Only log a brief
    3919              :                 // message to make it clear that we returned the error to the client.
    3920            0 :                 error!("HTTP request handler task panicked: {e:#}");
    3921              : 
    3922              :                 // Don't return an Error here, because then fallback error handler that was
    3923              :                 // installed in make_router() will print the error. Instead, construct the
    3924              :                 // HTTP error response and return that.
    3925            0 :                 Ok(
    3926            0 :                     ApiError::InternalServerError(anyhow!("HTTP request handler task panicked"))
    3927            0 :                         .into_response(),
    3928            0 :                 )
    3929              :             }
    3930              :         }
    3931            0 :     })
    3932            0 :     .await;
    3933              : 
    3934            0 :     cancel_guard.disarm();
    3935              : 
    3936            0 :     result
    3937            0 : }
    3938              : 
    3939              : /// Like api_handler, but returns an error response if the server is built without
    3940              : /// the 'testing' feature.
    3941            0 : async fn testing_api_handler<R, H>(
    3942            0 :     desc: &str,
    3943            0 :     request: Request<Body>,
    3944            0 :     handler: H,
    3945            0 : ) -> Result<Response<Body>, ApiError>
    3946            0 : where
    3947            0 :     R: std::future::Future<Output = Result<Response<Body>, ApiError>> + Send + 'static,
    3948            0 :     H: FnOnce(Request<Body>, CancellationToken) -> R + Send + Sync + 'static,
    3949            0 : {
    3950            0 :     if cfg!(feature = "testing") {
    3951            0 :         api_handler(request, handler).await
    3952              :     } else {
    3953            0 :         std::future::ready(Err(ApiError::BadRequest(anyhow!(
    3954            0 :             "Cannot {desc} because pageserver was compiled without testing APIs",
    3955            0 :         ))))
    3956            0 :         .await
    3957              :     }
    3958            0 : }
    3959              : 
    3960            0 : pub fn make_router(
    3961            0 :     state: Arc<State>,
    3962            0 :     launch_ts: &'static LaunchTimestamp,
    3963            0 :     auth: Option<Arc<SwappableJwtAuth>>,
    3964            0 : ) -> anyhow::Result<RouterBuilder<hyper::Body, ApiError>> {
    3965            0 :     let spec = include_bytes!("openapi_spec.yml");
    3966            0 :     let mut router = attach_openapi_ui(endpoint::make_router(), spec, "/swagger.yml", "/v1/doc");
    3967            0 :     if auth.is_some() {
    3968            0 :         router = router.middleware(auth_middleware(|request| {
    3969            0 :             let state = get_state(request);
    3970            0 :             if state.allowlist_routes.contains(&request.uri().path()) {
    3971            0 :                 None
    3972              :             } else {
    3973            0 :                 state.auth.as_deref()
    3974              :             }
    3975            0 :         }))
    3976            0 :     }
    3977              : 
    3978            0 :     router = router.middleware(
    3979            0 :         endpoint::add_response_header_middleware(
    3980            0 :             "PAGESERVER_LAUNCH_TIMESTAMP",
    3981            0 :             &launch_ts.to_string(),
    3982              :         )
    3983            0 :         .expect("construct launch timestamp header middleware"),
    3984              :     );
    3985              : 
    3986            0 :     let force_metric_collection_on_scrape = state.conf.force_metric_collection_on_scrape;
    3987              : 
    3988            0 :     let prometheus_metrics_handler_wrapper =
    3989            0 :         move |req| prometheus_metrics_handler(req, force_metric_collection_on_scrape);
    3990              : 
    3991            0 :     Ok(router
    3992            0 :         .data(state)
    3993            0 :         .get("/metrics", move |r| request_span(r, prometheus_metrics_handler_wrapper))
    3994            0 :         .get("/profile/cpu", |r| request_span(r, profile_cpu_handler))
    3995            0 :         .get("/profile/heap", |r| request_span(r, profile_heap_handler))
    3996            0 :         .get("/v1/status", |r| api_handler(r, status_handler))
    3997            0 :         .put("/v1/failpoints", |r| {
    3998            0 :             testing_api_handler("manage failpoints", r, failpoints_handler)
    3999            0 :         })
    4000            0 :         .post("/v1/reload_auth_validation_keys", |r| {
    4001            0 :             api_handler(r, reload_auth_validation_keys_handler)
    4002            0 :         })
    4003            0 :         .get("/v1/tenant", |r| api_handler(r, tenant_list_handler))
    4004            0 :         .get("/v1/tenant/:tenant_shard_id", |r| {
    4005            0 :             api_handler(r, tenant_status)
    4006            0 :         })
    4007            0 :         .delete("/v1/tenant/:tenant_shard_id", |r| {
    4008            0 :             api_handler(r, tenant_delete_handler)
    4009            0 :         })
    4010            0 :         .get("/v1/tenant/:tenant_shard_id/synthetic_size", |r| {
    4011            0 :             api_handler(r, tenant_size_handler)
    4012            0 :         })
    4013            0 :         .patch("/v1/tenant/config", |r| {
    4014            0 :             api_handler(r, patch_tenant_config_handler)
    4015            0 :         })
    4016            0 :         .put("/v1/tenant/config", |r| {
    4017            0 :             api_handler(r, update_tenant_config_handler)
    4018            0 :         })
    4019            0 :         .put("/v1/tenant/:tenant_shard_id/shard_split", |r| {
    4020            0 :             api_handler(r, tenant_shard_split_handler)
    4021            0 :         })
    4022            0 :         .get("/v1/tenant/:tenant_shard_id/config", |r| {
    4023            0 :             api_handler(r, get_tenant_config_handler)
    4024            0 :         })
    4025            0 :         .put("/v1/tenant/:tenant_shard_id/location_config", |r| {
    4026            0 :             api_handler(r, put_tenant_location_config_handler)
    4027            0 :         })
    4028            0 :         .get("/v1/location_config", |r| {
    4029            0 :             api_handler(r, list_location_config_handler)
    4030            0 :         })
    4031            0 :         .get("/v1/location_config/:tenant_shard_id", |r| {
    4032            0 :             api_handler(r, get_location_config_handler)
    4033            0 :         })
    4034            0 :         .put(
    4035              :             "/v1/tenant/:tenant_shard_id/time_travel_remote_storage",
    4036            0 :             |r| api_handler(r, tenant_time_travel_remote_storage_handler),
    4037              :         )
    4038            0 :         .get("/v1/tenant/:tenant_shard_id/timeline", |r| {
    4039            0 :             api_handler(r, timeline_list_handler)
    4040            0 :         })
    4041            0 :         .get("/v1/tenant/:tenant_shard_id/timeline_and_offloaded", |r| {
    4042            0 :             api_handler(r, timeline_and_offloaded_list_handler)
    4043            0 :         })
    4044            0 :         .post("/v1/tenant/:tenant_shard_id/timeline", |r| {
    4045            0 :             api_handler(r, timeline_create_handler)
    4046            0 :         })
    4047            0 :         .post("/v1/tenant/:tenant_shard_id/reset", |r| {
    4048            0 :             api_handler(r, tenant_reset_handler)
    4049            0 :         })
    4050            0 :         .post(
    4051              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/preserve_initdb_archive",
    4052            0 :             |r| api_handler(r, timeline_preserve_initdb_handler),
    4053              :         )
    4054            0 :         .put(
    4055              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/archival_config",
    4056            0 :             |r| api_handler(r, timeline_archival_config_handler),
    4057              :         )
    4058            0 :         .get("/v1/tenant/:tenant_shard_id/timeline/:timeline_id", |r| {
    4059            0 :             api_handler(r, timeline_detail_handler)
    4060            0 :         })
    4061            0 :         .get(
    4062              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/get_lsn_by_timestamp",
    4063            0 :             |r| api_handler(r, get_lsn_by_timestamp_handler),
    4064              :         )
    4065            0 :         .get(
    4066              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/get_timestamp_of_lsn",
    4067            0 :             |r| api_handler(r, get_timestamp_of_lsn_handler),
    4068              :         )
    4069            0 :         .post(
    4070              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/patch_index_part",
    4071            0 :             |r| api_handler(r, timeline_patch_index_part_handler),
    4072              :         )
    4073            0 :         .post(
    4074              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/lsn_lease",
    4075            0 :             |r| api_handler(r, lsn_lease_handler),
    4076              :         )
    4077            0 :         .put(
    4078              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/do_gc",
    4079            0 :             |r| api_handler(r, timeline_gc_handler),
    4080              :         )
    4081            0 :         .get(
    4082              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/compact",
    4083            0 :             |r| api_handler(r, timeline_compact_info_handler),
    4084              :         )
    4085            0 :         .put(
    4086              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/compact",
    4087            0 :             |r| api_handler(r, timeline_compact_handler),
    4088              :         )
    4089            0 :         .delete(
    4090              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/compact",
    4091            0 :             |r| api_handler(r, timeline_cancel_compact_handler),
    4092              :         )
    4093            0 :         .put(
    4094              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/offload",
    4095            0 :             |r| testing_api_handler("attempt timeline offload", r, timeline_offload_handler),
    4096              :         )
    4097            0 :         .put(
    4098              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/mark_invisible",
    4099            0 :             |r| api_handler( r, timeline_mark_invisible_handler),
    4100              :         )
    4101            0 :         .put(
    4102              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/checkpoint",
    4103            0 :             |r| testing_api_handler("run timeline checkpoint", r, timeline_checkpoint_handler),
    4104              :         )
    4105            0 :         .post(
    4106              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/download_remote_layers",
    4107            0 :             |r| api_handler(r, timeline_download_remote_layers_handler_post),
    4108              :         )
    4109            0 :         .get(
    4110              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/download_remote_layers",
    4111            0 :             |r| api_handler(r, timeline_download_remote_layers_handler_get),
    4112              :         )
    4113            0 :         .put(
    4114              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/detach_ancestor",
    4115            0 :             |r| api_handler(r, timeline_detach_ancestor_handler),
    4116              :         )
    4117            0 :         .delete("/v1/tenant/:tenant_shard_id/timeline/:timeline_id", |r| {
    4118            0 :             api_handler(r, timeline_delete_handler)
    4119            0 :         })
    4120            0 :         .get(
    4121              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/layer",
    4122            0 :             |r| api_handler(r, layer_map_info_handler),
    4123              :         )
    4124            0 :         .post(
    4125              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/download_heatmap_layers",
    4126            0 :             |r| api_handler(r, timeline_download_heatmap_layers_handler),
    4127              :         )
    4128            0 :         .delete(
    4129              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/download_heatmap_layers",
    4130            0 :             |r| api_handler(r, timeline_shutdown_download_heatmap_layers_handler),
    4131              :         )
    4132            0 :         .get(
    4133              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/layer/:layer_file_name",
    4134            0 :             |r| api_handler(r, layer_download_handler),
    4135              :         )
    4136            0 :         .delete(
    4137              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/layer/:layer_file_name",
    4138            0 :             |r| api_handler(r, evict_timeline_layer_handler),
    4139              :         )
    4140            0 :         .post(
    4141              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/layer/:layer_name/scan_disposable_keys",
    4142            0 :             |r| testing_api_handler("timeline_layer_scan_disposable_keys", r, timeline_layer_scan_disposable_keys),
    4143              :         )
    4144            0 :         .post(
    4145              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/block_gc",
    4146            0 :             |r| api_handler(r, timeline_gc_blocking_handler),
    4147              :         )
    4148            0 :         .post(
    4149              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/unblock_gc",
    4150            0 :             |r| api_handler(r, timeline_gc_unblocking_handler),
    4151              :         )
    4152            0 :         .get(
    4153              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/page_trace",
    4154            0 :             |r| api_handler(r, timeline_page_trace_handler),
    4155              :         )
    4156            0 :         .post("/v1/tenant/:tenant_shard_id/heatmap_upload", |r| {
    4157            0 :             api_handler(r, secondary_upload_handler)
    4158            0 :         })
    4159            0 :         .get("/v1/tenant/:tenant_id/scan_remote_storage", |r| {
    4160            0 :             api_handler(r, tenant_scan_remote_handler)
    4161            0 :         })
    4162            0 :         .put("/v1/disk_usage_eviction/run", |r| {
    4163            0 :             api_handler(r, disk_usage_eviction_run)
    4164            0 :         })
    4165            0 :         .put("/v1/deletion_queue/flush", |r| {
    4166            0 :             api_handler(r, deletion_queue_flush)
    4167            0 :         })
    4168            0 :         .get("/v1/tenant/:tenant_shard_id/secondary/status", |r| {
    4169            0 :             api_handler(r, secondary_status_handler)
    4170            0 :         })
    4171            0 :         .post("/v1/tenant/:tenant_shard_id/secondary/download", |r| {
    4172            0 :             api_handler(r, secondary_download_handler)
    4173            0 :         })
    4174            0 :         .post("/v1/tenant/:tenant_shard_id/wait_lsn", |r| {
    4175            0 :             api_handler(r, wait_lsn_handler)
    4176            0 :         })
    4177            0 :         .put("/v1/tenant/:tenant_shard_id/break", |r| {
    4178            0 :             testing_api_handler("set tenant state to broken", r, handle_tenant_break)
    4179            0 :         })
    4180            0 :         .get("/v1/panic", |r| api_handler(r, always_panic_handler))
    4181            0 :         .post("/v1/tracing/event", |r| {
    4182            0 :             testing_api_handler("emit a tracing event", r, post_tracing_event_handler)
    4183            0 :         })
    4184            0 :         .get(
    4185              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/getpage",
    4186            0 :             |r|  testing_api_handler("getpage@lsn", r, getpage_at_lsn_handler),
    4187              :         )
    4188            0 :         .get(
    4189              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/touchpage",
    4190            0 :             |r| api_handler(r, touchpage_at_lsn_handler),
    4191              :         )
    4192            0 :         .get(
    4193              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/keyspace",
    4194            0 :             |r| api_handler(r, timeline_collect_keyspace),
    4195              :         )
    4196            0 :         .put("/v1/io_engine", |r| api_handler(r, put_io_engine_handler))
    4197            0 :         .put("/v1/io_mode", |r| api_handler(r, put_io_mode_handler))
    4198            0 :         .get("/v1/utilization", |r| api_handler(r, get_utilization))
    4199            0 :         .get("/v1/list_tenant_visible_size", |r| api_handler(r, list_tenant_visible_size_handler))
    4200            0 :         .post(
    4201              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/ingest_aux_files",
    4202            0 :             |r| testing_api_handler("ingest_aux_files", r, ingest_aux_files),
    4203              :         )
    4204            0 :         .post(
    4205              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/list_aux_files",
    4206            0 :             |r| testing_api_handler("list_aux_files", r, list_aux_files),
    4207              :         )
    4208            0 :         .post("/v1/top_tenants", |r| api_handler(r, post_top_tenants))
    4209            0 :         .post(
    4210              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/perf_info",
    4211            0 :             |r| testing_api_handler("perf_info", r, perf_info),
    4212              :         )
    4213            0 :         .put(
    4214              :             "/v1/tenant/:tenant_id/timeline/:timeline_id/import_basebackup",
    4215            0 :             |r| api_handler(r, put_tenant_timeline_import_basebackup),
    4216              :         )
    4217            0 :         .put(
    4218              :             "/v1/tenant/:tenant_id/timeline/:timeline_id/import_wal",
    4219            0 :             |r| api_handler(r, put_tenant_timeline_import_wal),
    4220              :         )
    4221            0 :         .put(
    4222              :             "/v1/tenant/:tenant_shard_id/timeline/:timeline_id/activate_post_import",
    4223            0 :             |r| api_handler(r, activate_post_import_handler),
    4224              :         )
    4225            0 :         .get("/v1/tenant/:tenant_shard_id/feature_flag/:flag_key", |r| {
    4226            0 :             api_handler(r, tenant_evaluate_feature_flag)
    4227            0 :         })
    4228            0 :         .post("/v1/tenant/:tenant_shard_id/force_refresh_feature_flag", |r| {
    4229            0 :             api_handler(r, force_refresh_feature_flag)
    4230            0 :         })
    4231            0 :         .put("/v1/feature_flag/:flag_key", |r| {
    4232            0 :             testing_api_handler("force override feature flag - put", r, force_override_feature_flag_for_testing_put)
    4233            0 :         })
    4234            0 :         .delete("/v1/feature_flag/:flag_key", |r| {
    4235            0 :             testing_api_handler("force override feature flag - delete", r, force_override_feature_flag_for_testing_delete)
    4236            0 :         })
    4237            0 :         .post("/v1/feature_flag_spec", |r| {
    4238            0 :             api_handler(r, update_feature_flag_spec)
    4239            0 :         })
    4240            0 :         .post("/hadron-internal/reset_alert_gauges", |r| {
    4241            0 :             api_handler(r, hadron_reset_alert_gauges)
    4242            0 :         })
    4243            0 :         .any(handler_404))
    4244            0 : }
        

Generated by: LCOV version 2.1-beta