LCOV - code coverage report
Current view: top level - pageserver/src - page_service.rs (source / functions) Coverage Total Hit
Test: bd5ac6a31f9a6350183cc934f602462809434088.info Lines: 25.8 % 1126 290
Test Date: 2025-01-10 11:42:44 Functions: 7.8 % 103 8

            Line data    Source code
       1              : //! The Page Service listens for client connections and serves their GetPage@LSN
       2              : //! requests.
       3              : 
       4              : use anyhow::{bail, Context};
       5              : use async_compression::tokio::write::GzipEncoder;
       6              : use bytes::Buf;
       7              : use futures::FutureExt;
       8              : use itertools::Itertools;
       9              : use once_cell::sync::OnceCell;
      10              : use pageserver_api::config::{
      11              :     PageServicePipeliningConfig, PageServicePipeliningConfigPipelined,
      12              :     PageServiceProtocolPipelinedExecutionStrategy,
      13              : };
      14              : use pageserver_api::models::{self, TenantState};
      15              : use pageserver_api::models::{
      16              :     PagestreamBeMessage, PagestreamDbSizeRequest, PagestreamDbSizeResponse,
      17              :     PagestreamErrorResponse, PagestreamExistsRequest, PagestreamExistsResponse,
      18              :     PagestreamFeMessage, PagestreamGetPageRequest, PagestreamGetSlruSegmentRequest,
      19              :     PagestreamGetSlruSegmentResponse, PagestreamNblocksRequest, PagestreamNblocksResponse,
      20              :     PagestreamProtocolVersion, PagestreamRequest,
      21              : };
      22              : use pageserver_api::shard::TenantShardId;
      23              : use postgres_backend::{
      24              :     is_expected_io_error, AuthType, PostgresBackend, PostgresBackendReader, QueryError,
      25              : };
      26              : use pq_proto::framed::ConnectionError;
      27              : use pq_proto::FeStartupPacket;
      28              : use pq_proto::{BeMessage, FeMessage, RowDescriptor};
      29              : use std::borrow::Cow;
      30              : use std::io;
      31              : use std::num::NonZeroUsize;
      32              : use std::str;
      33              : use std::str::FromStr;
      34              : use std::sync::Arc;
      35              : use std::time::SystemTime;
      36              : use std::time::{Duration, Instant};
      37              : use tokio::io::{AsyncRead, AsyncWrite};
      38              : use tokio::io::{AsyncWriteExt, BufWriter};
      39              : use tokio::task::JoinHandle;
      40              : use tokio_util::sync::CancellationToken;
      41              : use tracing::*;
      42              : use utils::sync::spsc_fold;
      43              : use utils::{
      44              :     auth::{Claims, Scope, SwappableJwtAuth},
      45              :     id::{TenantId, TimelineId},
      46              :     lsn::Lsn,
      47              :     simple_rcu::RcuReadGuard,
      48              : };
      49              : 
      50              : use crate::auth::check_permission;
      51              : use crate::basebackup::BasebackupError;
      52              : use crate::config::PageServerConf;
      53              : use crate::context::{DownloadBehavior, RequestContext};
      54              : use crate::metrics::{self, SmgrOpTimer};
      55              : use crate::metrics::{ComputeCommandKind, COMPUTE_COMMANDS_COUNTERS, LIVE_CONNECTIONS};
      56              : use crate::pgdatadir_mapping::Version;
      57              : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id;
      58              : use crate::span::debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id;
      59              : use crate::task_mgr::TaskKind;
      60              : use crate::task_mgr::{self, COMPUTE_REQUEST_RUNTIME};
      61              : use crate::tenant::mgr::ShardSelector;
      62              : use crate::tenant::mgr::TenantManager;
      63              : use crate::tenant::mgr::{GetActiveTenantError, GetTenantError, ShardResolveResult};
      64              : use crate::tenant::timeline::{self, WaitLsnError};
      65              : use crate::tenant::GetTimelineError;
      66              : use crate::tenant::PageReconstructError;
      67              : use crate::tenant::Timeline;
      68              : use crate::{basebackup, timed_after_cancellation};
      69              : use pageserver_api::key::rel_block_to_key;
      70              : use pageserver_api::reltag::SlruKind;
      71              : use postgres_ffi::pg_constants::DEFAULTTABLESPACE_OID;
      72              : use postgres_ffi::BLCKSZ;
      73              : 
      74              : /// How long we may wait for a [`crate::tenant::mgr::TenantSlot::InProgress`]` and/or a [`crate::tenant::Tenant`] which
      75              : /// is not yet in state [`TenantState::Active`].
      76              : ///
      77              : /// NB: this is a different value than [`crate::http::routes::ACTIVE_TENANT_TIMEOUT`].
      78              : const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(30000);
      79              : 
      80              : ///////////////////////////////////////////////////////////////////////////////
      81              : 
      82              : pub struct Listener {
      83              :     cancel: CancellationToken,
      84              :     /// Cancel the listener task through `listen_cancel` to shut down the listener
      85              :     /// and get a handle on the existing connections.
      86              :     task: JoinHandle<Connections>,
      87              : }
      88              : 
      89              : pub struct Connections {
      90              :     cancel: CancellationToken,
      91              :     tasks: tokio::task::JoinSet<ConnectionHandlerResult>,
      92              : }
      93              : 
      94            0 : pub fn spawn(
      95            0 :     conf: &'static PageServerConf,
      96            0 :     tenant_manager: Arc<TenantManager>,
      97            0 :     pg_auth: Option<Arc<SwappableJwtAuth>>,
      98            0 :     tcp_listener: tokio::net::TcpListener,
      99            0 : ) -> Listener {
     100            0 :     let cancel = CancellationToken::new();
     101            0 :     let libpq_ctx = RequestContext::todo_child(
     102            0 :         TaskKind::LibpqEndpointListener,
     103            0 :         // listener task shouldn't need to download anything. (We will
     104            0 :         // create a separate sub-contexts for each connection, with their
     105            0 :         // own download behavior. This context is used only to listen and
     106            0 :         // accept connections.)
     107            0 :         DownloadBehavior::Error,
     108            0 :     );
     109            0 :     let task = COMPUTE_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
     110            0 :         "libpq listener",
     111            0 :         libpq_listener_main(
     112            0 :             tenant_manager,
     113            0 :             pg_auth,
     114            0 :             tcp_listener,
     115            0 :             conf.pg_auth_type,
     116            0 :             conf.page_service_pipelining.clone(),
     117            0 :             libpq_ctx,
     118            0 :             cancel.clone(),
     119            0 :         )
     120            0 :         .map(anyhow::Ok),
     121            0 :     ));
     122            0 : 
     123            0 :     Listener { cancel, task }
     124            0 : }
     125              : 
     126              : impl Listener {
     127            0 :     pub async fn stop_accepting(self) -> Connections {
     128            0 :         self.cancel.cancel();
     129            0 :         self.task
     130            0 :             .await
     131            0 :             .expect("unreachable: we wrap the listener task in task_mgr::exit_on_panic_or_error")
     132            0 :     }
     133              : }
     134              : impl Connections {
     135            0 :     pub(crate) async fn shutdown(self) {
     136            0 :         let Self { cancel, mut tasks } = self;
     137            0 :         cancel.cancel();
     138            0 :         while let Some(res) = tasks.join_next().await {
     139            0 :             Self::handle_connection_completion(res);
     140            0 :         }
     141            0 :     }
     142              : 
     143            0 :     fn handle_connection_completion(res: Result<anyhow::Result<()>, tokio::task::JoinError>) {
     144            0 :         match res {
     145            0 :             Ok(Ok(())) => {}
     146            0 :             Ok(Err(e)) => error!("error in page_service connection task: {:?}", e),
     147            0 :             Err(e) => error!("page_service connection task panicked: {:?}", e),
     148              :         }
     149            0 :     }
     150              : }
     151              : 
     152              : ///
     153              : /// Main loop of the page service.
     154              : ///
     155              : /// Listens for connections, and launches a new handler task for each.
     156              : ///
     157              : /// Returns Ok(()) upon cancellation via `cancel`, returning the set of
     158              : /// open connections.
     159              : ///
     160            0 : pub async fn libpq_listener_main(
     161            0 :     tenant_manager: Arc<TenantManager>,
     162            0 :     auth: Option<Arc<SwappableJwtAuth>>,
     163            0 :     listener: tokio::net::TcpListener,
     164            0 :     auth_type: AuthType,
     165            0 :     pipelining_config: PageServicePipeliningConfig,
     166            0 :     listener_ctx: RequestContext,
     167            0 :     listener_cancel: CancellationToken,
     168            0 : ) -> Connections {
     169            0 :     let connections_cancel = CancellationToken::new();
     170            0 :     let mut connection_handler_tasks = tokio::task::JoinSet::default();
     171              : 
     172              :     loop {
     173            0 :         let accepted = tokio::select! {
     174              :             biased;
     175            0 :             _ = listener_cancel.cancelled() => break,
     176            0 :             next = connection_handler_tasks.join_next(), if !connection_handler_tasks.is_empty() => {
     177            0 :                 let res = next.expect("we dont poll while empty");
     178            0 :                 Connections::handle_connection_completion(res);
     179            0 :                 continue;
     180              :             }
     181            0 :             accepted = listener.accept() => accepted,
     182            0 :         };
     183            0 : 
     184            0 :         match accepted {
     185            0 :             Ok((socket, peer_addr)) => {
     186            0 :                 // Connection established. Spawn a new task to handle it.
     187            0 :                 debug!("accepted connection from {}", peer_addr);
     188            0 :                 let local_auth = auth.clone();
     189            0 :                 let connection_ctx = listener_ctx
     190            0 :                     .detached_child(TaskKind::PageRequestHandler, DownloadBehavior::Download);
     191            0 :                 connection_handler_tasks.spawn(page_service_conn_main(
     192            0 :                     tenant_manager.clone(),
     193            0 :                     local_auth,
     194            0 :                     socket,
     195            0 :                     auth_type,
     196            0 :                     pipelining_config.clone(),
     197            0 :                     connection_ctx,
     198            0 :                     connections_cancel.child_token(),
     199            0 :                 ));
     200              :             }
     201            0 :             Err(err) => {
     202            0 :                 // accept() failed. Log the error, and loop back to retry on next connection.
     203            0 :                 error!("accept() failed: {:?}", err);
     204              :             }
     205              :         }
     206              :     }
     207              : 
     208            0 :     debug!("page_service listener loop terminated");
     209              : 
     210            0 :     Connections {
     211            0 :         cancel: connections_cancel,
     212            0 :         tasks: connection_handler_tasks,
     213            0 :     }
     214            0 : }
     215              : 
     216              : type ConnectionHandlerResult = anyhow::Result<()>;
     217              : 
     218              : #[instrument(skip_all, fields(peer_addr))]
     219              : async fn page_service_conn_main(
     220              :     tenant_manager: Arc<TenantManager>,
     221              :     auth: Option<Arc<SwappableJwtAuth>>,
     222              :     socket: tokio::net::TcpStream,
     223              :     auth_type: AuthType,
     224              :     pipelining_config: PageServicePipeliningConfig,
     225              :     connection_ctx: RequestContext,
     226              :     cancel: CancellationToken,
     227              : ) -> ConnectionHandlerResult {
     228              :     let _guard = LIVE_CONNECTIONS
     229              :         .with_label_values(&["page_service"])
     230              :         .guard();
     231              : 
     232              :     socket
     233              :         .set_nodelay(true)
     234              :         .context("could not set TCP_NODELAY")?;
     235              : 
     236              :     let peer_addr = socket.peer_addr().context("get peer address")?;
     237              :     tracing::Span::current().record("peer_addr", field::display(peer_addr));
     238              : 
     239              :     // setup read timeout of 10 minutes. the timeout is rather arbitrary for requirements:
     240              :     // - long enough for most valid compute connections
     241              :     // - less than infinite to stop us from "leaking" connections to long-gone computes
     242              :     //
     243              :     // no write timeout is used, because the kernel is assumed to error writes after some time.
     244              :     let mut socket = tokio_io_timeout::TimeoutReader::new(socket);
     245              : 
     246              :     let default_timeout_ms = 10 * 60 * 1000; // 10 minutes by default
     247            0 :     let socket_timeout_ms = (|| {
     248            0 :         fail::fail_point!("simulated-bad-compute-connection", |avg_timeout_ms| {
     249              :             // Exponential distribution for simulating
     250              :             // poor network conditions, expect about avg_timeout_ms to be around 15
     251              :             // in tests
     252            0 :             if let Some(avg_timeout_ms) = avg_timeout_ms {
     253            0 :                 let avg = avg_timeout_ms.parse::<i64>().unwrap() as f32;
     254            0 :                 let u = rand::random::<f32>();
     255            0 :                 ((1.0 - u).ln() / (-avg)) as u64
     256              :             } else {
     257            0 :                 default_timeout_ms
     258              :             }
     259            0 :         });
     260            0 :         default_timeout_ms
     261              :     })();
     262              : 
     263              :     // A timeout here does not mean the client died, it can happen if it's just idle for
     264              :     // a while: we will tear down this PageServerHandler and instantiate a new one if/when
     265              :     // they reconnect.
     266              :     socket.set_timeout(Some(std::time::Duration::from_millis(socket_timeout_ms)));
     267              :     let socket = Box::pin(socket);
     268              : 
     269              :     fail::fail_point!("ps::connection-start::pre-login");
     270              : 
     271              :     // XXX: pgbackend.run() should take the connection_ctx,
     272              :     // and create a child per-query context when it invokes process_query.
     273              :     // But it's in a shared crate, so, we store connection_ctx inside PageServerHandler
     274              :     // and create the per-query context in process_query ourselves.
     275              :     let mut conn_handler = PageServerHandler::new(
     276              :         tenant_manager,
     277              :         auth,
     278              :         pipelining_config,
     279              :         connection_ctx,
     280              :         cancel.clone(),
     281              :     );
     282              :     let pgbackend = PostgresBackend::new_from_io(socket, peer_addr, auth_type, None)?;
     283              : 
     284              :     match pgbackend.run(&mut conn_handler, &cancel).await {
     285              :         Ok(()) => {
     286              :             // we've been requested to shut down
     287              :             Ok(())
     288              :         }
     289              :         Err(QueryError::Disconnected(ConnectionError::Io(io_error))) => {
     290              :             if is_expected_io_error(&io_error) {
     291              :                 info!("Postgres client disconnected ({io_error})");
     292              :                 Ok(())
     293              :             } else {
     294              :                 let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
     295              :                 Err(io_error).context(format!(
     296              :                     "Postgres connection error for tenant_id={:?} client at peer_addr={}",
     297              :                     tenant_id, peer_addr
     298              :                 ))
     299              :             }
     300              :         }
     301              :         other => {
     302              :             let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
     303              :             other.context(format!(
     304              :                 "Postgres query error for tenant_id={:?} client peer_addr={}",
     305              :                 tenant_id, peer_addr
     306              :             ))
     307              :         }
     308              :     }
     309              : }
     310              : 
     311              : struct PageServerHandler {
     312              :     auth: Option<Arc<SwappableJwtAuth>>,
     313              :     claims: Option<Claims>,
     314              : 
     315              :     /// The context created for the lifetime of the connection
     316              :     /// services by this PageServerHandler.
     317              :     /// For each query received over the connection,
     318              :     /// `process_query` creates a child context from this one.
     319              :     connection_ctx: RequestContext,
     320              : 
     321              :     cancel: CancellationToken,
     322              : 
     323              :     /// None only while pagestream protocol is being processed.
     324              :     timeline_handles: Option<TimelineHandles>,
     325              : 
     326              :     pipelining_config: PageServicePipeliningConfig,
     327              : }
     328              : 
     329              : struct TimelineHandles {
     330              :     wrapper: TenantManagerWrapper,
     331              :     /// Note on size: the typical size of this map is 1.  The largest size we expect
     332              :     /// to see is the number of shards divided by the number of pageservers (typically < 2),
     333              :     /// or the ratio used when splitting shards (i.e. how many children created from one)
     334              :     /// parent shard, where a "large" number might be ~8.
     335              :     handles: timeline::handle::Cache<TenantManagerTypes>,
     336              : }
     337              : 
     338              : impl TimelineHandles {
     339            0 :     fn new(tenant_manager: Arc<TenantManager>) -> Self {
     340            0 :         Self {
     341            0 :             wrapper: TenantManagerWrapper {
     342            0 :                 tenant_manager,
     343            0 :                 tenant_id: OnceCell::new(),
     344            0 :             },
     345            0 :             handles: Default::default(),
     346            0 :         }
     347            0 :     }
     348            0 :     async fn get(
     349            0 :         &mut self,
     350            0 :         tenant_id: TenantId,
     351            0 :         timeline_id: TimelineId,
     352            0 :         shard_selector: ShardSelector,
     353            0 :     ) -> Result<timeline::handle::Handle<TenantManagerTypes>, GetActiveTimelineError> {
     354            0 :         if *self.wrapper.tenant_id.get_or_init(|| tenant_id) != tenant_id {
     355            0 :             return Err(GetActiveTimelineError::Tenant(
     356            0 :                 GetActiveTenantError::SwitchedTenant,
     357            0 :             ));
     358            0 :         }
     359            0 :         self.handles
     360            0 :             .get(timeline_id, shard_selector, &self.wrapper)
     361            0 :             .await
     362            0 :             .map_err(|e| match e {
     363            0 :                 timeline::handle::GetError::TenantManager(e) => e,
     364              :                 timeline::handle::GetError::TimelineGateClosed => {
     365            0 :                     trace!("timeline gate closed");
     366            0 :                     GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown)
     367              :                 }
     368              :                 timeline::handle::GetError::PerTimelineStateShutDown => {
     369            0 :                     trace!("per-timeline state shut down");
     370            0 :                     GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown)
     371              :                 }
     372            0 :             })
     373            0 :     }
     374              : 
     375            0 :     fn tenant_id(&self) -> Option<TenantId> {
     376            0 :         self.wrapper.tenant_id.get().copied()
     377            0 :     }
     378              : }
     379              : 
     380              : pub(crate) struct TenantManagerWrapper {
     381              :     tenant_manager: Arc<TenantManager>,
     382              :     // We do not support switching tenant_id on a connection at this point.
     383              :     // We can can add support for this later if needed without changing
     384              :     // the protocol.
     385              :     tenant_id: once_cell::sync::OnceCell<TenantId>,
     386              : }
     387              : 
     388              : #[derive(Debug)]
     389              : pub(crate) struct TenantManagerTypes;
     390              : 
     391              : impl timeline::handle::Types for TenantManagerTypes {
     392              :     type TenantManagerError = GetActiveTimelineError;
     393              :     type TenantManager = TenantManagerWrapper;
     394              :     type Timeline = Arc<Timeline>;
     395              : }
     396              : 
     397              : impl timeline::handle::ArcTimeline<TenantManagerTypes> for Arc<Timeline> {
     398            0 :     fn gate(&self) -> &utils::sync::gate::Gate {
     399            0 :         &self.gate
     400            0 :     }
     401              : 
     402            0 :     fn shard_timeline_id(&self) -> timeline::handle::ShardTimelineId {
     403            0 :         Timeline::shard_timeline_id(self)
     404            0 :     }
     405              : 
     406            0 :     fn per_timeline_state(&self) -> &timeline::handle::PerTimelineState<TenantManagerTypes> {
     407            0 :         &self.handles
     408            0 :     }
     409              : 
     410            0 :     fn get_shard_identity(&self) -> &pageserver_api::shard::ShardIdentity {
     411            0 :         Timeline::get_shard_identity(self)
     412            0 :     }
     413              : }
     414              : 
     415              : impl timeline::handle::TenantManager<TenantManagerTypes> for TenantManagerWrapper {
     416            0 :     async fn resolve(
     417            0 :         &self,
     418            0 :         timeline_id: TimelineId,
     419            0 :         shard_selector: ShardSelector,
     420            0 :     ) -> Result<Arc<Timeline>, GetActiveTimelineError> {
     421            0 :         let tenant_id = self.tenant_id.get().expect("we set this in get()");
     422            0 :         let timeout = ACTIVE_TENANT_TIMEOUT;
     423            0 :         let wait_start = Instant::now();
     424            0 :         let deadline = wait_start + timeout;
     425            0 :         let tenant_shard = loop {
     426            0 :             let resolved = self
     427            0 :                 .tenant_manager
     428            0 :                 .resolve_attached_shard(tenant_id, shard_selector);
     429            0 :             match resolved {
     430            0 :                 ShardResolveResult::Found(tenant_shard) => break tenant_shard,
     431              :                 ShardResolveResult::NotFound => {
     432            0 :                     return Err(GetActiveTimelineError::Tenant(
     433            0 :                         GetActiveTenantError::NotFound(GetTenantError::NotFound(*tenant_id)),
     434            0 :                     ));
     435              :                 }
     436            0 :                 ShardResolveResult::InProgress(barrier) => {
     437            0 :                     // We can't authoritatively answer right now: wait for InProgress state
     438            0 :                     // to end, then try again
     439            0 :                     tokio::select! {
     440            0 :                         _  = barrier.wait() => {
     441            0 :                             // The barrier completed: proceed around the loop to try looking up again
     442            0 :                         },
     443            0 :                         _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
     444            0 :                             return Err(GetActiveTimelineError::Tenant(GetActiveTenantError::WaitForActiveTimeout {
     445            0 :                                 latest_state: None,
     446            0 :                                 wait_time: timeout,
     447            0 :                             }));
     448              :                         }
     449              :                     }
     450              :                 }
     451              :             };
     452              :         };
     453              : 
     454            0 :         tracing::debug!("Waiting for tenant to enter active state...");
     455            0 :         tenant_shard
     456            0 :             .wait_to_become_active(deadline.duration_since(Instant::now()))
     457            0 :             .await
     458            0 :             .map_err(GetActiveTimelineError::Tenant)?;
     459              : 
     460            0 :         let timeline = tenant_shard
     461            0 :             .get_timeline(timeline_id, true)
     462            0 :             .map_err(GetActiveTimelineError::Timeline)?;
     463            0 :         set_tracing_field_shard_id(&timeline);
     464            0 :         Ok(timeline)
     465            0 :     }
     466              : }
     467              : 
     468              : #[derive(thiserror::Error, Debug)]
     469              : enum PageStreamError {
     470              :     /// We encountered an error that should prompt the client to reconnect:
     471              :     /// in practice this means we drop the connection without sending a response.
     472              :     #[error("Reconnect required: {0}")]
     473              :     Reconnect(Cow<'static, str>),
     474              : 
     475              :     /// We were instructed to shutdown while processing the query
     476              :     #[error("Shutting down")]
     477              :     Shutdown,
     478              : 
     479              :     /// Something went wrong reading a page: this likely indicates a pageserver bug
     480              :     #[error("Read error")]
     481              :     Read(#[source] PageReconstructError),
     482              : 
     483              :     /// Ran out of time waiting for an LSN
     484              :     #[error("LSN timeout: {0}")]
     485              :     LsnTimeout(WaitLsnError),
     486              : 
     487              :     /// The entity required to serve the request (tenant or timeline) is not found,
     488              :     /// or is not found in a suitable state to serve a request.
     489              :     #[error("Not found: {0}")]
     490              :     NotFound(Cow<'static, str>),
     491              : 
     492              :     /// Request asked for something that doesn't make sense, like an invalid LSN
     493              :     #[error("Bad request: {0}")]
     494              :     BadRequest(Cow<'static, str>),
     495              : }
     496              : 
     497              : impl From<PageReconstructError> for PageStreamError {
     498            0 :     fn from(value: PageReconstructError) -> Self {
     499            0 :         match value {
     500            0 :             PageReconstructError::Cancelled => Self::Shutdown,
     501            0 :             e => Self::Read(e),
     502              :         }
     503            0 :     }
     504              : }
     505              : 
     506              : impl From<GetActiveTimelineError> for PageStreamError {
     507            0 :     fn from(value: GetActiveTimelineError) -> Self {
     508            0 :         match value {
     509              :             GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled)
     510              :             | GetActiveTimelineError::Tenant(GetActiveTenantError::WillNotBecomeActive(
     511              :                 TenantState::Stopping { .. },
     512              :             ))
     513            0 :             | GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown) => Self::Shutdown,
     514            0 :             GetActiveTimelineError::Tenant(e) => Self::NotFound(format!("{e}").into()),
     515            0 :             GetActiveTimelineError::Timeline(e) => Self::NotFound(format!("{e}").into()),
     516              :         }
     517            0 :     }
     518              : }
     519              : 
     520              : impl From<WaitLsnError> for PageStreamError {
     521            0 :     fn from(value: WaitLsnError) -> Self {
     522            0 :         match value {
     523            0 :             e @ WaitLsnError::Timeout(_) => Self::LsnTimeout(e),
     524            0 :             WaitLsnError::Shutdown => Self::Shutdown,
     525            0 :             e @ WaitLsnError::BadState { .. } => Self::Reconnect(format!("{e}").into()),
     526              :         }
     527            0 :     }
     528              : }
     529              : 
     530              : impl From<WaitLsnError> for QueryError {
     531            0 :     fn from(value: WaitLsnError) -> Self {
     532            0 :         match value {
     533            0 :             e @ WaitLsnError::Timeout(_) => Self::Other(anyhow::Error::new(e)),
     534            0 :             WaitLsnError::Shutdown => Self::Shutdown,
     535            0 :             WaitLsnError::BadState { .. } => Self::Reconnect,
     536              :         }
     537            0 :     }
     538              : }
     539              : 
     540              : #[derive(thiserror::Error, Debug)]
     541              : struct BatchedPageStreamError {
     542              :     req: PagestreamRequest,
     543              :     err: PageStreamError,
     544              : }
     545              : 
     546              : impl std::fmt::Display for BatchedPageStreamError {
     547            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     548            0 :         self.err.fmt(f)
     549            0 :     }
     550              : }
     551              : 
     552              : struct BatchedGetPageRequest {
     553              :     req: PagestreamGetPageRequest,
     554              :     timer: SmgrOpTimer,
     555              : }
     556              : 
     557              : enum BatchedFeMessage {
     558              :     Exists {
     559              :         span: Span,
     560              :         timer: SmgrOpTimer,
     561              :         shard: timeline::handle::Handle<TenantManagerTypes>,
     562              :         req: models::PagestreamExistsRequest,
     563              :     },
     564              :     Nblocks {
     565              :         span: Span,
     566              :         timer: SmgrOpTimer,
     567              :         shard: timeline::handle::Handle<TenantManagerTypes>,
     568              :         req: models::PagestreamNblocksRequest,
     569              :     },
     570              :     GetPage {
     571              :         span: Span,
     572              :         shard: timeline::handle::Handle<TenantManagerTypes>,
     573              :         effective_request_lsn: Lsn,
     574              :         pages: smallvec::SmallVec<[BatchedGetPageRequest; 1]>,
     575              :     },
     576              :     DbSize {
     577              :         span: Span,
     578              :         timer: SmgrOpTimer,
     579              :         shard: timeline::handle::Handle<TenantManagerTypes>,
     580              :         req: models::PagestreamDbSizeRequest,
     581              :     },
     582              :     GetSlruSegment {
     583              :         span: Span,
     584              :         timer: SmgrOpTimer,
     585              :         shard: timeline::handle::Handle<TenantManagerTypes>,
     586              :         req: models::PagestreamGetSlruSegmentRequest,
     587              :     },
     588              :     RespondError {
     589              :         span: Span,
     590              :         error: BatchedPageStreamError,
     591              :     },
     592              : }
     593              : 
     594              : impl BatchedFeMessage {
     595            0 :     async fn throttle_and_record_start_processing(
     596            0 :         &mut self,
     597            0 :         cancel: &CancellationToken,
     598            0 :     ) -> Result<(), QueryError> {
     599            0 :         let (shard, tokens, timers) = match self {
     600            0 :             BatchedFeMessage::Exists { shard, timer, .. }
     601            0 :             | BatchedFeMessage::Nblocks { shard, timer, .. }
     602            0 :             | BatchedFeMessage::DbSize { shard, timer, .. }
     603            0 :             | BatchedFeMessage::GetSlruSegment { shard, timer, .. } => {
     604            0 :                 (
     605            0 :                     shard,
     606            0 :                     // 1 token is probably under-estimating because these
     607            0 :                     // request handlers typically do several Timeline::get calls.
     608            0 :                     1,
     609            0 :                     itertools::Either::Left(std::iter::once(timer)),
     610            0 :                 )
     611              :             }
     612            0 :             BatchedFeMessage::GetPage { shard, pages, .. } => (
     613            0 :                 shard,
     614            0 :                 pages.len(),
     615            0 :                 itertools::Either::Right(pages.iter_mut().map(|p| &mut p.timer)),
     616            0 :             ),
     617            0 :             BatchedFeMessage::RespondError { .. } => return Ok(()),
     618              :         };
     619            0 :         let throttled = tokio::select! {
     620            0 :             throttled = shard.pagestream_throttle.throttle(tokens) => { throttled }
     621            0 :             _ = cancel.cancelled() => {
     622            0 :                 return Err(QueryError::Shutdown);
     623              :             }
     624              :         };
     625            0 :         for timer in timers {
     626            0 :             timer.observe_throttle_done_execution_starting(&throttled);
     627            0 :         }
     628            0 :         Ok(())
     629            0 :     }
     630              : }
     631              : 
     632              : impl PageServerHandler {
     633            0 :     pub fn new(
     634            0 :         tenant_manager: Arc<TenantManager>,
     635            0 :         auth: Option<Arc<SwappableJwtAuth>>,
     636            0 :         pipelining_config: PageServicePipeliningConfig,
     637            0 :         connection_ctx: RequestContext,
     638            0 :         cancel: CancellationToken,
     639            0 :     ) -> Self {
     640            0 :         PageServerHandler {
     641            0 :             auth,
     642            0 :             claims: None,
     643            0 :             connection_ctx,
     644            0 :             timeline_handles: Some(TimelineHandles::new(tenant_manager)),
     645            0 :             cancel,
     646            0 :             pipelining_config,
     647            0 :         }
     648            0 :     }
     649              : 
     650              :     /// This function always respects cancellation of any timeline in `[Self::shard_timelines]`.  Pass in
     651              :     /// a cancellation token at the next scope up (such as a tenant cancellation token) to ensure we respect
     652              :     /// cancellation if there aren't any timelines in the cache.
     653              :     ///
     654              :     /// If calling from a function that doesn't use the `[Self::shard_timelines]` cache, then pass in the
     655              :     /// timeline cancellation token.
     656            0 :     async fn flush_cancellable<IO>(
     657            0 :         &self,
     658            0 :         pgb: &mut PostgresBackend<IO>,
     659            0 :         cancel: &CancellationToken,
     660            0 :     ) -> Result<(), QueryError>
     661            0 :     where
     662            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
     663            0 :     {
     664            0 :         tokio::select!(
     665            0 :             flush_r = pgb.flush() => {
     666            0 :                 Ok(flush_r?)
     667              :             },
     668            0 :             _ = cancel.cancelled() => {
     669            0 :                 Err(QueryError::Shutdown)
     670              :             }
     671              :         )
     672            0 :     }
     673              : 
     674              :     #[allow(clippy::too_many_arguments)]
     675            0 :     async fn pagestream_read_message<IO>(
     676            0 :         pgb: &mut PostgresBackendReader<IO>,
     677            0 :         tenant_id: TenantId,
     678            0 :         timeline_id: TimelineId,
     679            0 :         timeline_handles: &mut TimelineHandles,
     680            0 :         cancel: &CancellationToken,
     681            0 :         ctx: &RequestContext,
     682            0 :         protocol_version: PagestreamProtocolVersion,
     683            0 :         parent_span: Span,
     684            0 :     ) -> Result<Option<BatchedFeMessage>, QueryError>
     685            0 :     where
     686            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
     687            0 :     {
     688            0 :         let msg = tokio::select! {
     689              :             biased;
     690            0 :             _ = cancel.cancelled() => {
     691            0 :                 return Err(QueryError::Shutdown)
     692              :             }
     693            0 :             msg = pgb.read_message() => { msg }
     694            0 :         };
     695            0 : 
     696            0 :         let received_at = Instant::now();
     697              : 
     698            0 :         let copy_data_bytes = match msg? {
     699            0 :             Some(FeMessage::CopyData(bytes)) => bytes,
     700              :             Some(FeMessage::Terminate) => {
     701            0 :                 return Ok(None);
     702              :             }
     703            0 :             Some(m) => {
     704            0 :                 return Err(QueryError::Other(anyhow::anyhow!(
     705            0 :                     "unexpected message: {m:?} during COPY"
     706            0 :                 )));
     707              :             }
     708              :             None => {
     709            0 :                 return Ok(None);
     710              :             } // client disconnected
     711              :         };
     712            0 :         trace!("query: {copy_data_bytes:?}");
     713              : 
     714            0 :         fail::fail_point!("ps::handle-pagerequest-message");
     715              : 
     716              :         // parse request
     717            0 :         let neon_fe_msg =
     718            0 :             PagestreamFeMessage::parse(&mut copy_data_bytes.reader(), protocol_version)?;
     719              : 
     720            0 :         let batched_msg = match neon_fe_msg {
     721            0 :             PagestreamFeMessage::Exists(req) => {
     722            0 :                 let span = tracing::info_span!(parent: parent_span, "handle_get_rel_exists_request", rel = %req.rel, req_lsn = %req.hdr.request_lsn);
     723            0 :                 let shard = timeline_handles
     724            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
     725            0 :                     .instrument(span.clone()) // sets `shard_id` field
     726            0 :                     .await?;
     727            0 :                 let timer = shard
     728            0 :                     .query_metrics
     729            0 :                     .start_smgr_op(metrics::SmgrQueryType::GetRelExists, received_at);
     730            0 :                 BatchedFeMessage::Exists {
     731            0 :                     span,
     732            0 :                     timer,
     733            0 :                     shard,
     734            0 :                     req,
     735            0 :                 }
     736              :             }
     737            0 :             PagestreamFeMessage::Nblocks(req) => {
     738            0 :                 let span = tracing::info_span!(parent: parent_span, "handle_get_nblocks_request", rel = %req.rel, req_lsn = %req.hdr.request_lsn);
     739            0 :                 let shard = timeline_handles
     740            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
     741            0 :                     .instrument(span.clone()) // sets `shard_id` field
     742            0 :                     .await?;
     743            0 :                 let timer = shard
     744            0 :                     .query_metrics
     745            0 :                     .start_smgr_op(metrics::SmgrQueryType::GetRelSize, received_at);
     746            0 :                 BatchedFeMessage::Nblocks {
     747            0 :                     span,
     748            0 :                     timer,
     749            0 :                     shard,
     750            0 :                     req,
     751            0 :                 }
     752              :             }
     753            0 :             PagestreamFeMessage::DbSize(req) => {
     754            0 :                 let span = tracing::info_span!(parent: parent_span, "handle_db_size_request", dbnode = %req.dbnode, req_lsn = %req.hdr.request_lsn);
     755            0 :                 let shard = timeline_handles
     756            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
     757            0 :                     .instrument(span.clone()) // sets `shard_id` field
     758            0 :                     .await?;
     759            0 :                 let timer = shard
     760            0 :                     .query_metrics
     761            0 :                     .start_smgr_op(metrics::SmgrQueryType::GetDbSize, received_at);
     762            0 :                 BatchedFeMessage::DbSize {
     763            0 :                     span,
     764            0 :                     timer,
     765            0 :                     shard,
     766            0 :                     req,
     767            0 :                 }
     768              :             }
     769            0 :             PagestreamFeMessage::GetSlruSegment(req) => {
     770            0 :                 let span = tracing::info_span!(parent: parent_span, "handle_get_slru_segment_request", kind = %req.kind, segno = %req.segno, req_lsn = %req.hdr.request_lsn);
     771            0 :                 let shard = timeline_handles
     772            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
     773            0 :                     .instrument(span.clone()) // sets `shard_id` field
     774            0 :                     .await?;
     775            0 :                 let timer = shard
     776            0 :                     .query_metrics
     777            0 :                     .start_smgr_op(metrics::SmgrQueryType::GetSlruSegment, received_at);
     778            0 :                 BatchedFeMessage::GetSlruSegment {
     779            0 :                     span,
     780            0 :                     timer,
     781            0 :                     shard,
     782            0 :                     req,
     783            0 :                 }
     784              :             }
     785            0 :             PagestreamFeMessage::GetPage(req) => {
     786            0 :                 let span = tracing::info_span!(parent: parent_span, "handle_get_page_at_lsn_request_batched", req_lsn = %req.hdr.request_lsn);
     787              : 
     788              :                 macro_rules! respond_error {
     789              :                     ($error:expr) => {{
     790              :                         let error = BatchedFeMessage::RespondError {
     791              :                             span,
     792              :                             error: BatchedPageStreamError {
     793              :                                 req: req.hdr,
     794              :                                 err: $error,
     795              :                             },
     796              :                         };
     797              :                         Ok(Some(error))
     798              :                     }};
     799              :                 }
     800              : 
     801            0 :                 let key = rel_block_to_key(req.rel, req.blkno);
     802            0 :                 let shard = match timeline_handles
     803            0 :                     .get(tenant_id, timeline_id, ShardSelector::Page(key))
     804            0 :                     .instrument(span.clone()) // sets `shard_id` field
     805            0 :                     .await
     806              :                 {
     807            0 :                     Ok(tl) => tl,
     808              :                     Err(GetActiveTimelineError::Tenant(GetActiveTenantError::NotFound(_))) => {
     809              :                         // We already know this tenant exists in general, because we resolved it at
     810              :                         // start of connection.  Getting a NotFound here indicates that the shard containing
     811              :                         // the requested page is not present on this node: the client's knowledge of shard->pageserver
     812              :                         // mapping is out of date.
     813              :                         //
     814              :                         // Closing the connection by returning ``::Reconnect` has the side effect of rate-limiting above message, via
     815              :                         // client's reconnect backoff, as well as hopefully prompting the client to load its updated configuration
     816              :                         // and talk to a different pageserver.
     817            0 :                         return respond_error!(PageStreamError::Reconnect(
     818            0 :                             "getpage@lsn request routed to wrong shard".into()
     819            0 :                         ));
     820              :                     }
     821            0 :                     Err(e) => {
     822            0 :                         return respond_error!(e.into());
     823              :                     }
     824              :                 };
     825              : 
     826              :                 // It's important to start the timer before waiting for the LSN
     827              :                 // so that the _started counters are incremented before we do
     828              :                 // any serious waiting, e.g., for LSNs.
     829            0 :                 let timer = shard
     830            0 :                     .query_metrics
     831            0 :                     .start_smgr_op(metrics::SmgrQueryType::GetPageAtLsn, received_at);
     832              : 
     833            0 :                 let effective_request_lsn = match Self::wait_or_get_last_lsn(
     834            0 :                     &shard,
     835            0 :                     req.hdr.request_lsn,
     836            0 :                     req.hdr.not_modified_since,
     837            0 :                     &shard.get_latest_gc_cutoff_lsn(),
     838            0 :                     ctx,
     839            0 :                 )
     840            0 :                 // TODO: if we actually need to wait for lsn here, it delays the entire batch which doesn't need to wait
     841            0 :                 .await
     842              :                 {
     843            0 :                     Ok(lsn) => lsn,
     844            0 :                     Err(e) => {
     845            0 :                         return respond_error!(e);
     846              :                     }
     847              :                 };
     848              :                 BatchedFeMessage::GetPage {
     849            0 :                     span,
     850            0 :                     shard,
     851            0 :                     effective_request_lsn,
     852            0 :                     pages: smallvec::smallvec![BatchedGetPageRequest { req, timer }],
     853              :                 }
     854              :             }
     855              :         };
     856            0 :         Ok(Some(batched_msg))
     857            0 :     }
     858              : 
     859              :     /// Post-condition: `batch` is Some()
     860              :     #[instrument(skip_all, level = tracing::Level::TRACE)]
     861              :     #[allow(clippy::boxed_local)]
     862              :     fn pagestream_do_batch(
     863              :         max_batch_size: NonZeroUsize,
     864              :         batch: &mut Result<BatchedFeMessage, QueryError>,
     865              :         this_msg: Result<BatchedFeMessage, QueryError>,
     866              :     ) -> Result<(), Result<BatchedFeMessage, QueryError>> {
     867              :         debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
     868              : 
     869              :         let this_msg = match this_msg {
     870              :             Ok(this_msg) => this_msg,
     871              :             Err(e) => return Err(Err(e)),
     872              :         };
     873              : 
     874              :         match (&mut *batch, this_msg) {
     875              :             // something batched already, let's see if we can add this message to the batch
     876              :             (
     877              :                 Ok(BatchedFeMessage::GetPage {
     878              :                     span: _,
     879              :                     shard: accum_shard,
     880              :                     pages: ref mut accum_pages,
     881              :                     effective_request_lsn: accum_lsn,
     882              :                 }),
     883              :                 BatchedFeMessage::GetPage {
     884              :                     span: _,
     885              :                     shard: this_shard,
     886              :                     pages: this_pages,
     887              :                     effective_request_lsn: this_lsn,
     888              :                 },
     889            0 :             ) if (|| {
     890            0 :                 assert_eq!(this_pages.len(), 1);
     891            0 :                 if accum_pages.len() >= max_batch_size.get() {
     892            0 :                     trace!(%accum_lsn, %this_lsn, %max_batch_size, "stopping batching because of batch size");
     893            0 :                     assert_eq!(accum_pages.len(), max_batch_size.get());
     894            0 :                     return false;
     895            0 :                 }
     896            0 :                 if (accum_shard.tenant_shard_id, accum_shard.timeline_id)
     897            0 :                     != (this_shard.tenant_shard_id, this_shard.timeline_id)
     898              :                 {
     899            0 :                     trace!(%accum_lsn, %this_lsn, "stopping batching because timeline object mismatch");
     900              :                     // TODO: we _could_ batch & execute each shard seperately (and in parallel).
     901              :                     // But the current logic for keeping responses in order does not support that.
     902            0 :                     return false;
     903            0 :                 }
     904            0 :                 // the vectored get currently only supports a single LSN, so, bounce as soon
     905            0 :                 // as the effective request_lsn changes
     906            0 :                 if *accum_lsn != this_lsn {
     907            0 :                     trace!(%accum_lsn, %this_lsn, "stopping batching because LSN changed");
     908            0 :                     return false;
     909            0 :                 }
     910            0 :                 true
     911              :             })() =>
     912              :             {
     913              :                 // ok to batch
     914              :                 accum_pages.extend(this_pages);
     915              :                 Ok(())
     916              :             }
     917              :             // something batched already but this message is unbatchable
     918              :             (_, this_msg) => {
     919              :                 // by default, don't continue batching
     920              :                 Err(Ok(this_msg))
     921              :             }
     922              :         }
     923              :     }
     924              : 
     925            0 :     #[instrument(level = tracing::Level::DEBUG, skip_all)]
     926              :     async fn pagesteam_handle_batched_message<IO>(
     927              :         &mut self,
     928              :         pgb_writer: &mut PostgresBackend<IO>,
     929              :         batch: BatchedFeMessage,
     930              :         cancel: &CancellationToken,
     931              :         protocol_version: PagestreamProtocolVersion,
     932              :         ctx: &RequestContext,
     933              :     ) -> Result<(), QueryError>
     934              :     where
     935              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
     936              :     {
     937              :         // invoke handler function
     938              :         let (handler_results, span): (
     939              :             Vec<Result<(PagestreamBeMessage, SmgrOpTimer), BatchedPageStreamError>>,
     940              :             _,
     941              :         ) = match batch {
     942              :             BatchedFeMessage::Exists {
     943              :                 span,
     944              :                 timer,
     945              :                 shard,
     946              :                 req,
     947              :             } => {
     948              :                 fail::fail_point!("ps::handle-pagerequest-message::exists");
     949              :                 (
     950              :                     vec![self
     951              :                         .handle_get_rel_exists_request(&shard, &req, ctx)
     952              :                         .instrument(span.clone())
     953              :                         .await
     954            0 :                         .map(|msg| (msg, timer))
     955            0 :                         .map_err(|err| BatchedPageStreamError { err, req: req.hdr })],
     956              :                     span,
     957              :                 )
     958              :             }
     959              :             BatchedFeMessage::Nblocks {
     960              :                 span,
     961              :                 timer,
     962              :                 shard,
     963              :                 req,
     964              :             } => {
     965              :                 fail::fail_point!("ps::handle-pagerequest-message::nblocks");
     966              :                 (
     967              :                     vec![self
     968              :                         .handle_get_nblocks_request(&shard, &req, ctx)
     969              :                         .instrument(span.clone())
     970              :                         .await
     971            0 :                         .map(|msg| (msg, timer))
     972            0 :                         .map_err(|err| BatchedPageStreamError { err, req: req.hdr })],
     973              :                     span,
     974              :                 )
     975              :             }
     976              :             BatchedFeMessage::GetPage {
     977              :                 span,
     978              :                 shard,
     979              :                 effective_request_lsn,
     980              :                 pages,
     981              :             } => {
     982              :                 fail::fail_point!("ps::handle-pagerequest-message::getpage");
     983              :                 (
     984              :                     {
     985              :                         let npages = pages.len();
     986              :                         trace!(npages, "handling getpage request");
     987              :                         let res = self
     988              :                             .handle_get_page_at_lsn_request_batched(
     989              :                                 &shard,
     990              :                                 effective_request_lsn,
     991              :                                 pages,
     992              :                                 ctx,
     993              :                             )
     994              :                             .instrument(span.clone())
     995              :                             .await;
     996              :                         assert_eq!(res.len(), npages);
     997              :                         res
     998              :                     },
     999              :                     span,
    1000              :                 )
    1001              :             }
    1002              :             BatchedFeMessage::DbSize {
    1003              :                 span,
    1004              :                 timer,
    1005              :                 shard,
    1006              :                 req,
    1007              :             } => {
    1008              :                 fail::fail_point!("ps::handle-pagerequest-message::dbsize");
    1009              :                 (
    1010              :                     vec![self
    1011              :                         .handle_db_size_request(&shard, &req, ctx)
    1012              :                         .instrument(span.clone())
    1013              :                         .await
    1014            0 :                         .map(|msg| (msg, timer))
    1015            0 :                         .map_err(|err| BatchedPageStreamError { err, req: req.hdr })],
    1016              :                     span,
    1017              :                 )
    1018              :             }
    1019              :             BatchedFeMessage::GetSlruSegment {
    1020              :                 span,
    1021              :                 timer,
    1022              :                 shard,
    1023              :                 req,
    1024              :             } => {
    1025              :                 fail::fail_point!("ps::handle-pagerequest-message::slrusegment");
    1026              :                 (
    1027              :                     vec![self
    1028              :                         .handle_get_slru_segment_request(&shard, &req, ctx)
    1029              :                         .instrument(span.clone())
    1030              :                         .await
    1031            0 :                         .map(|msg| (msg, timer))
    1032            0 :                         .map_err(|err| BatchedPageStreamError { err, req: req.hdr })],
    1033              :                     span,
    1034              :                 )
    1035              :             }
    1036              :             BatchedFeMessage::RespondError { span, error } => {
    1037              :                 // We've already decided to respond with an error, so we don't need to
    1038              :                 // call the handler.
    1039              :                 (vec![Err(error)], span)
    1040              :             }
    1041              :         };
    1042              : 
    1043              :         // Map handler result to protocol behavior.
    1044              :         // Some handler errors cause exit from pagestream protocol.
    1045              :         // Other handler errors are sent back as an error message and we stay in pagestream protocol.
    1046              :         for handler_result in handler_results {
    1047              :             let (response_msg, timer) = match handler_result {
    1048              :                 Err(e) => match &e.err {
    1049              :                     PageStreamError::Shutdown => {
    1050              :                         // If we fail to fulfil a request during shutdown, which may be _because_ of
    1051              :                         // shutdown, then do not send the error to the client.  Instead just drop the
    1052              :                         // connection.
    1053            0 :                         span.in_scope(|| info!("dropping connection due to shutdown"));
    1054              :                         return Err(QueryError::Shutdown);
    1055              :                     }
    1056              :                     PageStreamError::Reconnect(reason) => {
    1057            0 :                         span.in_scope(|| info!("handler requested reconnect: {reason}"));
    1058              :                         return Err(QueryError::Reconnect);
    1059              :                     }
    1060              :                     PageStreamError::Read(_)
    1061              :                     | PageStreamError::LsnTimeout(_)
    1062              :                     | PageStreamError::NotFound(_)
    1063              :                     | PageStreamError::BadRequest(_) => {
    1064              :                         // print the all details to the log with {:#}, but for the client the
    1065              :                         // error message is enough.  Do not log if shutting down, as the anyhow::Error
    1066              :                         // here includes cancellation which is not an error.
    1067              :                         let full = utils::error::report_compact_sources(&e.err);
    1068            0 :                         span.in_scope(|| {
    1069            0 :                             error!("error reading relation or page version: {full:#}")
    1070            0 :                         });
    1071              :                         (
    1072              :                             PagestreamBeMessage::Error(PagestreamErrorResponse {
    1073              :                                 req: e.req,
    1074              :                                 message: e.err.to_string(),
    1075              :                             }),
    1076              :                             None, // TODO: measure errors
    1077              :                         )
    1078              :                     }
    1079              :                 },
    1080              :                 Ok((response_msg, timer)) => (response_msg, Some(timer)),
    1081              :             };
    1082              : 
    1083              :             //
    1084              :             // marshal & transmit response message
    1085              :             //
    1086              : 
    1087              :             pgb_writer.write_message_noflush(&BeMessage::CopyData(
    1088              :                 &response_msg.serialize(protocol_version),
    1089              :             ))?;
    1090              : 
    1091              :             // We purposefully don't count flush time into the timer.
    1092              :             //
    1093              :             // The reason is that current compute client will not perform protocol processing
    1094              :             // if the postgres backend process is doing things other than `->smgr_read()`.
    1095              :             // This is especially the case for prefetch.
    1096              :             //
    1097              :             // If the compute doesn't read from the connection, eventually TCP will backpressure
    1098              :             // all the way into our flush call below.
    1099              :             //
    1100              :             // The timer's underlying metric is used for a storage-internal latency SLO and
    1101              :             // we don't want to include latency in it that we can't control.
    1102              :             // And as pointed out above, in this case, we don't control the time that flush will take.
    1103              :             let flushing_timer =
    1104            0 :                 timer.map(|timer| timer.observe_smgr_op_completion_and_start_flushing());
    1105              : 
    1106              :             // what we want to do
    1107              :             let flush_fut = pgb_writer.flush();
    1108              :             // metric for how long flushing takes
    1109              :             let flush_fut = match flushing_timer {
    1110              :                 Some(flushing_timer) => {
    1111              :                     futures::future::Either::Left(flushing_timer.measure(flush_fut))
    1112              :                 }
    1113              :                 None => futures::future::Either::Right(flush_fut),
    1114              :             };
    1115              :             // do it while respecting cancellation
    1116            0 :             let _: () = async move {
    1117            0 :                 tokio::select! {
    1118              :                     biased;
    1119            0 :                     _ = cancel.cancelled() => {
    1120              :                         // We were requested to shut down.
    1121            0 :                         info!("shutdown request received in page handler");
    1122            0 :                         return Err(QueryError::Shutdown)
    1123              :                     }
    1124            0 :                     res = flush_fut => {
    1125            0 :                         res?;
    1126              :                     }
    1127              :                 }
    1128            0 :                 Ok(())
    1129            0 :             }
    1130              :             // and log the info! line inside the request span
    1131              :             .instrument(span.clone())
    1132              :             .await?;
    1133              :         }
    1134              :         Ok(())
    1135              :     }
    1136              : 
    1137              :     /// Pagestream sub-protocol handler.
    1138              :     ///
    1139              :     /// It is a simple request-response protocol inside a COPYBOTH session.
    1140              :     ///
    1141              :     /// # Coding Discipline
    1142              :     ///
    1143              :     /// Coding discipline within this function: all interaction with the `pgb` connection
    1144              :     /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
    1145              :     /// This is so that we can shutdown page_service quickly.
    1146              :     #[instrument(skip_all)]
    1147              :     async fn handle_pagerequests<IO>(
    1148              :         &mut self,
    1149              :         pgb: &mut PostgresBackend<IO>,
    1150              :         tenant_id: TenantId,
    1151              :         timeline_id: TimelineId,
    1152              :         protocol_version: PagestreamProtocolVersion,
    1153              :         ctx: RequestContext,
    1154              :     ) -> Result<(), QueryError>
    1155              :     where
    1156              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1157              :     {
    1158              :         debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    1159              : 
    1160              :         // switch client to COPYBOTH
    1161              :         pgb.write_message_noflush(&BeMessage::CopyBothResponse)?;
    1162              :         tokio::select! {
    1163              :             biased;
    1164              :             _ = self.cancel.cancelled() => {
    1165              :                 return Err(QueryError::Shutdown)
    1166              :             }
    1167              :             res = pgb.flush() => {
    1168              :                 res?;
    1169              :             }
    1170              :         }
    1171              : 
    1172              :         let pgb_reader = pgb
    1173              :             .split()
    1174              :             .context("implementation error: split pgb into reader and writer")?;
    1175              : 
    1176              :         let timeline_handles = self
    1177              :             .timeline_handles
    1178              :             .take()
    1179              :             .expect("implementation error: timeline_handles should not be locked");
    1180              : 
    1181              :         let request_span = info_span!("request", shard_id = tracing::field::Empty);
    1182              :         let ((pgb_reader, timeline_handles), result) = match self.pipelining_config.clone() {
    1183              :             PageServicePipeliningConfig::Pipelined(pipelining_config) => {
    1184              :                 self.handle_pagerequests_pipelined(
    1185              :                     pgb,
    1186              :                     pgb_reader,
    1187              :                     tenant_id,
    1188              :                     timeline_id,
    1189              :                     timeline_handles,
    1190              :                     request_span,
    1191              :                     pipelining_config,
    1192              :                     protocol_version,
    1193              :                     &ctx,
    1194              :                 )
    1195              :                 .await
    1196              :             }
    1197              :             PageServicePipeliningConfig::Serial => {
    1198              :                 self.handle_pagerequests_serial(
    1199              :                     pgb,
    1200              :                     pgb_reader,
    1201              :                     tenant_id,
    1202              :                     timeline_id,
    1203              :                     timeline_handles,
    1204              :                     request_span,
    1205              :                     protocol_version,
    1206              :                     &ctx,
    1207              :                 )
    1208              :                 .await
    1209              :             }
    1210              :         };
    1211              : 
    1212              :         debug!("pagestream subprotocol shut down cleanly");
    1213              : 
    1214              :         pgb.unsplit(pgb_reader)
    1215              :             .context("implementation error: unsplit pgb")?;
    1216              : 
    1217              :         let replaced = self.timeline_handles.replace(timeline_handles);
    1218              :         assert!(replaced.is_none());
    1219              : 
    1220              :         result
    1221              :     }
    1222              : 
    1223              :     #[allow(clippy::too_many_arguments)]
    1224            0 :     async fn handle_pagerequests_serial<IO>(
    1225            0 :         &mut self,
    1226            0 :         pgb_writer: &mut PostgresBackend<IO>,
    1227            0 :         mut pgb_reader: PostgresBackendReader<IO>,
    1228            0 :         tenant_id: TenantId,
    1229            0 :         timeline_id: TimelineId,
    1230            0 :         mut timeline_handles: TimelineHandles,
    1231            0 :         request_span: Span,
    1232            0 :         protocol_version: PagestreamProtocolVersion,
    1233            0 :         ctx: &RequestContext,
    1234            0 :     ) -> (
    1235            0 :         (PostgresBackendReader<IO>, TimelineHandles),
    1236            0 :         Result<(), QueryError>,
    1237            0 :     )
    1238            0 :     where
    1239            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1240            0 :     {
    1241            0 :         let cancel = self.cancel.clone();
    1242            0 :         let err = loop {
    1243            0 :             let msg = Self::pagestream_read_message(
    1244            0 :                 &mut pgb_reader,
    1245            0 :                 tenant_id,
    1246            0 :                 timeline_id,
    1247            0 :                 &mut timeline_handles,
    1248            0 :                 &cancel,
    1249            0 :                 ctx,
    1250            0 :                 protocol_version,
    1251            0 :                 request_span.clone(),
    1252            0 :             )
    1253            0 :             .await;
    1254            0 :             let msg = match msg {
    1255            0 :                 Ok(msg) => msg,
    1256            0 :                 Err(e) => break e,
    1257              :             };
    1258            0 :             let mut msg = match msg {
    1259            0 :                 Some(msg) => msg,
    1260              :                 None => {
    1261            0 :                     debug!("pagestream subprotocol end observed");
    1262            0 :                     return ((pgb_reader, timeline_handles), Ok(()));
    1263              :                 }
    1264              :             };
    1265              : 
    1266            0 :             if let Err(cancelled) = msg.throttle_and_record_start_processing(&self.cancel).await {
    1267            0 :                 break cancelled;
    1268            0 :             }
    1269              : 
    1270            0 :             let err = self
    1271            0 :                 .pagesteam_handle_batched_message(pgb_writer, msg, &cancel, protocol_version, ctx)
    1272            0 :                 .await;
    1273            0 :             match err {
    1274            0 :                 Ok(()) => {}
    1275            0 :                 Err(e) => break e,
    1276              :             }
    1277              :         };
    1278            0 :         ((pgb_reader, timeline_handles), Err(err))
    1279            0 :     }
    1280              : 
    1281              :     /// # Cancel-Safety
    1282              :     ///
    1283              :     /// May leak tokio tasks if not polled to completion.
    1284              :     #[allow(clippy::too_many_arguments)]
    1285            0 :     async fn handle_pagerequests_pipelined<IO>(
    1286            0 :         &mut self,
    1287            0 :         pgb_writer: &mut PostgresBackend<IO>,
    1288            0 :         pgb_reader: PostgresBackendReader<IO>,
    1289            0 :         tenant_id: TenantId,
    1290            0 :         timeline_id: TimelineId,
    1291            0 :         mut timeline_handles: TimelineHandles,
    1292            0 :         request_span: Span,
    1293            0 :         pipelining_config: PageServicePipeliningConfigPipelined,
    1294            0 :         protocol_version: PagestreamProtocolVersion,
    1295            0 :         ctx: &RequestContext,
    1296            0 :     ) -> (
    1297            0 :         (PostgresBackendReader<IO>, TimelineHandles),
    1298            0 :         Result<(), QueryError>,
    1299            0 :     )
    1300            0 :     where
    1301            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1302            0 :     {
    1303            0 :         //
    1304            0 :         // Pipelined pagestream handling consists of
    1305            0 :         // - a Batcher that reads requests off the wire and
    1306            0 :         //   and batches them if possible,
    1307            0 :         // - an Executor that processes the batched requests.
    1308            0 :         //
    1309            0 :         // The batch is built up inside an `spsc_fold` channel,
    1310            0 :         // shared betwen Batcher (Sender) and Executor (Receiver).
    1311            0 :         //
    1312            0 :         // The Batcher continously folds client requests into the batch,
    1313            0 :         // while the Executor can at any time take out what's in the batch
    1314            0 :         // in order to process it.
    1315            0 :         // This means the next batch builds up while the Executor
    1316            0 :         // executes the last batch.
    1317            0 :         //
    1318            0 :         // CANCELLATION
    1319            0 :         //
    1320            0 :         // We run both Batcher and Executor futures to completion before
    1321            0 :         // returning from this function.
    1322            0 :         //
    1323            0 :         // If Executor exits first, it signals cancellation to the Batcher
    1324            0 :         // via a CancellationToken that is child of `self.cancel`.
    1325            0 :         // If Batcher exits first, it signals cancellation to the Executor
    1326            0 :         // by dropping the spsc_fold channel Sender.
    1327            0 :         //
    1328            0 :         // CLEAN SHUTDOWN
    1329            0 :         //
    1330            0 :         // Clean shutdown means that the client ends the COPYBOTH session.
    1331            0 :         // In response to such a client message, the Batcher exits.
    1332            0 :         // The Executor continues to run, draining the spsc_fold channel.
    1333            0 :         // Once drained, the spsc_fold recv will fail with a distinct error
    1334            0 :         // indicating that the sender disconnected.
    1335            0 :         // The Executor exits with Ok(()) in response to that error.
    1336            0 :         //
    1337            0 :         // Server initiated shutdown is not clean shutdown, but instead
    1338            0 :         // is an error Err(QueryError::Shutdown) that is propagated through
    1339            0 :         // error propagation.
    1340            0 :         //
    1341            0 :         // ERROR PROPAGATION
    1342            0 :         //
    1343            0 :         // When the Batcher encounter an error, it sends it as a value
    1344            0 :         // through the spsc_fold channel and exits afterwards.
    1345            0 :         // When the Executor observes such an error in the channel,
    1346            0 :         // it exits returning that error value.
    1347            0 :         //
    1348            0 :         // This design ensures that the Executor stage will still process
    1349            0 :         // the batch that was in flight when the Batcher encountered an error,
    1350            0 :         // thereby beahving identical to a serial implementation.
    1351            0 : 
    1352            0 :         let PageServicePipeliningConfigPipelined {
    1353            0 :             max_batch_size,
    1354            0 :             execution,
    1355            0 :         } = pipelining_config;
    1356              : 
    1357              :         // Macro to _define_ a pipeline stage.
    1358              :         macro_rules! pipeline_stage {
    1359              :             ($name:literal, $cancel:expr, $make_fut:expr) => {{
    1360              :                 let cancel: CancellationToken = $cancel;
    1361              :                 let stage_fut = $make_fut(cancel.clone());
    1362            0 :                 async move {
    1363            0 :                     scopeguard::defer! {
    1364            0 :                         debug!("exiting");
    1365            0 :                     }
    1366            0 :                     timed_after_cancellation(stage_fut, $name, Duration::from_millis(100), &cancel)
    1367            0 :                         .await
    1368            0 :                 }
    1369              :                 .instrument(tracing::info_span!($name))
    1370              :             }};
    1371              :         }
    1372              : 
    1373              :         //
    1374              :         // Batcher
    1375              :         //
    1376              : 
    1377            0 :         let cancel_batcher = self.cancel.child_token();
    1378            0 :         let (mut batch_tx, mut batch_rx) = spsc_fold::channel();
    1379            0 :         let batcher = pipeline_stage!("batcher", cancel_batcher.clone(), move |cancel_batcher| {
    1380            0 :             let ctx = ctx.attached_child();
    1381            0 :             async move {
    1382            0 :                 let mut pgb_reader = pgb_reader;
    1383            0 :                 let mut exit = false;
    1384            0 :                 while !exit {
    1385            0 :                     let read_res = Self::pagestream_read_message(
    1386            0 :                         &mut pgb_reader,
    1387            0 :                         tenant_id,
    1388            0 :                         timeline_id,
    1389            0 :                         &mut timeline_handles,
    1390            0 :                         &cancel_batcher,
    1391            0 :                         &ctx,
    1392            0 :                         protocol_version,
    1393            0 :                         request_span.clone(),
    1394            0 :                     )
    1395            0 :                     .await;
    1396            0 :                     let Some(read_res) = read_res.transpose() else {
    1397            0 :                         debug!("client-initiated shutdown");
    1398            0 :                         break;
    1399              :                     };
    1400            0 :                     exit |= read_res.is_err();
    1401            0 :                     let could_send = batch_tx
    1402            0 :                         .send(read_res, |batch, res| {
    1403            0 :                             Self::pagestream_do_batch(max_batch_size, batch, res)
    1404            0 :                         })
    1405            0 :                         .await;
    1406            0 :                     exit |= could_send.is_err();
    1407              :                 }
    1408            0 :                 (pgb_reader, timeline_handles)
    1409            0 :             }
    1410            0 :         });
    1411              : 
    1412              :         //
    1413              :         // Executor
    1414              :         //
    1415              : 
    1416            0 :         let executor = pipeline_stage!("executor", self.cancel.clone(), move |cancel| {
    1417            0 :             let ctx = ctx.attached_child();
    1418            0 :             async move {
    1419            0 :                 let _cancel_batcher = cancel_batcher.drop_guard();
    1420              :                 loop {
    1421            0 :                     let maybe_batch = batch_rx.recv().await;
    1422            0 :                     let batch = match maybe_batch {
    1423            0 :                         Ok(batch) => batch,
    1424              :                         Err(spsc_fold::RecvError::SenderGone) => {
    1425            0 :                             debug!("upstream gone");
    1426            0 :                             return Ok(());
    1427              :                         }
    1428              :                     };
    1429            0 :                     let mut batch = match batch {
    1430            0 :                         Ok(batch) => batch,
    1431            0 :                         Err(e) => {
    1432            0 :                             return Err(e);
    1433              :                         }
    1434              :                     };
    1435            0 :                     batch
    1436            0 :                         .throttle_and_record_start_processing(&self.cancel)
    1437            0 :                         .await?;
    1438            0 :                     self.pagesteam_handle_batched_message(
    1439            0 :                         pgb_writer,
    1440            0 :                         batch,
    1441            0 :                         &cancel,
    1442            0 :                         protocol_version,
    1443            0 :                         &ctx,
    1444            0 :                     )
    1445            0 :                     .await?;
    1446              :                 }
    1447            0 :             }
    1448            0 :         });
    1449              : 
    1450              :         //
    1451              :         // Execute the stages.
    1452              :         //
    1453              : 
    1454            0 :         match execution {
    1455              :             PageServiceProtocolPipelinedExecutionStrategy::ConcurrentFutures => {
    1456            0 :                 tokio::join!(batcher, executor)
    1457              :             }
    1458              :             PageServiceProtocolPipelinedExecutionStrategy::Tasks => {
    1459              :                 // These tasks are not tracked anywhere.
    1460            0 :                 let read_messages_task = tokio::spawn(batcher);
    1461            0 :                 let (read_messages_task_res, executor_res_) =
    1462            0 :                     tokio::join!(read_messages_task, executor,);
    1463            0 :                 (
    1464            0 :                     read_messages_task_res.expect("propagated panic from read_messages"),
    1465            0 :                     executor_res_,
    1466            0 :                 )
    1467              :             }
    1468              :         }
    1469            0 :     }
    1470              : 
    1471              :     /// Helper function to handle the LSN from client request.
    1472              :     ///
    1473              :     /// Each GetPage (and Exists and Nblocks) request includes information about
    1474              :     /// which version of the page is being requested. The primary compute node
    1475              :     /// will always request the latest page version, by setting 'request_lsn' to
    1476              :     /// the last inserted or flushed WAL position, while a standby will request
    1477              :     /// a version at the LSN that it's currently caught up to.
    1478              :     ///
    1479              :     /// In either case, if the page server hasn't received the WAL up to the
    1480              :     /// requested LSN yet, we will wait for it to arrive. The return value is
    1481              :     /// the LSN that should be used to look up the page versions.
    1482              :     ///
    1483              :     /// In addition to the request LSN, each request carries another LSN,
    1484              :     /// 'not_modified_since', which is a hint to the pageserver that the client
    1485              :     /// knows that the page has not been modified between 'not_modified_since'
    1486              :     /// and the request LSN. This allows skipping the wait, as long as the WAL
    1487              :     /// up to 'not_modified_since' has arrived. If the client doesn't have any
    1488              :     /// information about when the page was modified, it will use
    1489              :     /// not_modified_since == lsn. If the client lies and sends a too low
    1490              :     /// not_modified_hint such that there are in fact later page versions, the
    1491              :     /// behavior is undefined: the pageserver may return any of the page versions
    1492              :     /// or an error.
    1493            0 :     async fn wait_or_get_last_lsn(
    1494            0 :         timeline: &Timeline,
    1495            0 :         request_lsn: Lsn,
    1496            0 :         not_modified_since: Lsn,
    1497            0 :         latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
    1498            0 :         ctx: &RequestContext,
    1499            0 :     ) -> Result<Lsn, PageStreamError> {
    1500            0 :         let last_record_lsn = timeline.get_last_record_lsn();
    1501            0 : 
    1502            0 :         // Sanity check the request
    1503            0 :         if request_lsn < not_modified_since {
    1504            0 :             return Err(PageStreamError::BadRequest(
    1505            0 :                 format!(
    1506            0 :                     "invalid request with request LSN {} and not_modified_since {}",
    1507            0 :                     request_lsn, not_modified_since,
    1508            0 :                 )
    1509            0 :                 .into(),
    1510            0 :             ));
    1511            0 :         }
    1512            0 : 
    1513            0 :         // Check explicitly for INVALID just to get a less scary error message if the request is obviously bogus
    1514            0 :         if request_lsn == Lsn::INVALID {
    1515            0 :             return Err(PageStreamError::BadRequest(
    1516            0 :                 "invalid LSN(0) in request".into(),
    1517            0 :             ));
    1518            0 :         }
    1519            0 : 
    1520            0 :         // Clients should only read from recent LSNs on their timeline, or from locations holding an LSN lease.
    1521            0 :         //
    1522            0 :         // We may have older data available, but we make a best effort to detect this case and return an error,
    1523            0 :         // to distinguish a misbehaving client (asking for old LSN) from a storage issue (data missing at a legitimate LSN).
    1524            0 :         if request_lsn < **latest_gc_cutoff_lsn && !timeline.is_gc_blocked_by_lsn_lease_deadline() {
    1525            0 :             let gc_info = &timeline.gc_info.read().unwrap();
    1526            0 :             if !gc_info.leases.contains_key(&request_lsn) {
    1527            0 :                 return Err(
    1528            0 :                     PageStreamError::BadRequest(format!(
    1529            0 :                         "tried to request a page version that was garbage collected. requested at {} gc cutoff {}",
    1530            0 :                         request_lsn, **latest_gc_cutoff_lsn
    1531            0 :                     ).into())
    1532            0 :                 );
    1533            0 :             }
    1534            0 :         }
    1535              : 
    1536              :         // Wait for WAL up to 'not_modified_since' to arrive, if necessary
    1537            0 :         if not_modified_since > last_record_lsn {
    1538            0 :             timeline
    1539            0 :                 .wait_lsn(
    1540            0 :                     not_modified_since,
    1541            0 :                     crate::tenant::timeline::WaitLsnWaiter::PageService,
    1542            0 :                     ctx,
    1543            0 :                 )
    1544            0 :                 .await?;
    1545              :             // Since we waited for 'not_modified_since' to arrive, that is now the last
    1546              :             // record LSN. (Or close enough for our purposes; the last-record LSN can
    1547              :             // advance immediately after we return anyway)
    1548            0 :             Ok(not_modified_since)
    1549              :         } else {
    1550              :             // It might be better to use max(not_modified_since, latest_gc_cutoff_lsn)
    1551              :             // here instead. That would give the same result, since we know that there
    1552              :             // haven't been any modifications since 'not_modified_since'. Using an older
    1553              :             // LSN might be faster, because that could allow skipping recent layers when
    1554              :             // finding the page. However, we have historically used 'last_record_lsn', so
    1555              :             // stick to that for now.
    1556            0 :             Ok(std::cmp::min(last_record_lsn, request_lsn))
    1557              :         }
    1558            0 :     }
    1559              : 
    1560              :     /// Handles the lsn lease request.
    1561              :     /// If a lease cannot be obtained, the client will receive NULL.
    1562              :     #[instrument(skip_all, fields(shard_id, %lsn))]
    1563              :     async fn handle_make_lsn_lease<IO>(
    1564              :         &mut self,
    1565              :         pgb: &mut PostgresBackend<IO>,
    1566              :         tenant_shard_id: TenantShardId,
    1567              :         timeline_id: TimelineId,
    1568              :         lsn: Lsn,
    1569              :         ctx: &RequestContext,
    1570              :     ) -> Result<(), QueryError>
    1571              :     where
    1572              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
    1573              :     {
    1574              :         let timeline = self
    1575              :             .timeline_handles
    1576              :             .as_mut()
    1577              :             .unwrap()
    1578              :             .get(
    1579              :                 tenant_shard_id.tenant_id,
    1580              :                 timeline_id,
    1581              :                 ShardSelector::Known(tenant_shard_id.to_index()),
    1582              :             )
    1583              :             .await?;
    1584              :         set_tracing_field_shard_id(&timeline);
    1585              : 
    1586              :         let lease = timeline
    1587              :             .renew_lsn_lease(lsn, timeline.get_lsn_lease_length(), ctx)
    1588            0 :             .inspect_err(|e| {
    1589            0 :                 warn!("{e}");
    1590            0 :             })
    1591              :             .ok();
    1592            0 :         let valid_until_str = lease.map(|l| {
    1593            0 :             l.valid_until
    1594            0 :                 .duration_since(SystemTime::UNIX_EPOCH)
    1595            0 :                 .expect("valid_until is earlier than UNIX_EPOCH")
    1596            0 :                 .as_millis()
    1597            0 :                 .to_string()
    1598            0 :         });
    1599            0 :         let bytes = valid_until_str.as_ref().map(|x| x.as_bytes());
    1600              : 
    1601              :         pgb.write_message_noflush(&BeMessage::RowDescription(&[RowDescriptor::text_col(
    1602              :             b"valid_until",
    1603              :         )]))?
    1604              :         .write_message_noflush(&BeMessage::DataRow(&[bytes]))?;
    1605              : 
    1606              :         Ok(())
    1607              :     }
    1608              : 
    1609              :     #[instrument(skip_all, fields(shard_id))]
    1610              :     async fn handle_get_rel_exists_request(
    1611              :         &mut self,
    1612              :         timeline: &Timeline,
    1613              :         req: &PagestreamExistsRequest,
    1614              :         ctx: &RequestContext,
    1615              :     ) -> Result<PagestreamBeMessage, PageStreamError> {
    1616              :         let latest_gc_cutoff_lsn = timeline.get_latest_gc_cutoff_lsn();
    1617              :         let lsn = Self::wait_or_get_last_lsn(
    1618              :             timeline,
    1619              :             req.hdr.request_lsn,
    1620              :             req.hdr.not_modified_since,
    1621              :             &latest_gc_cutoff_lsn,
    1622              :             ctx,
    1623              :         )
    1624              :         .await?;
    1625              : 
    1626              :         let exists = timeline
    1627              :             .get_rel_exists(req.rel, Version::Lsn(lsn), ctx)
    1628              :             .await?;
    1629              : 
    1630              :         Ok(PagestreamBeMessage::Exists(PagestreamExistsResponse {
    1631              :             req: *req,
    1632              :             exists,
    1633              :         }))
    1634              :     }
    1635              : 
    1636              :     #[instrument(skip_all, fields(shard_id))]
    1637              :     async fn handle_get_nblocks_request(
    1638              :         &mut self,
    1639              :         timeline: &Timeline,
    1640              :         req: &PagestreamNblocksRequest,
    1641              :         ctx: &RequestContext,
    1642              :     ) -> Result<PagestreamBeMessage, PageStreamError> {
    1643              :         let latest_gc_cutoff_lsn = timeline.get_latest_gc_cutoff_lsn();
    1644              :         let lsn = Self::wait_or_get_last_lsn(
    1645              :             timeline,
    1646              :             req.hdr.request_lsn,
    1647              :             req.hdr.not_modified_since,
    1648              :             &latest_gc_cutoff_lsn,
    1649              :             ctx,
    1650              :         )
    1651              :         .await?;
    1652              : 
    1653              :         let n_blocks = timeline
    1654              :             .get_rel_size(req.rel, Version::Lsn(lsn), ctx)
    1655              :             .await?;
    1656              : 
    1657              :         Ok(PagestreamBeMessage::Nblocks(PagestreamNblocksResponse {
    1658              :             req: *req,
    1659              :             n_blocks,
    1660              :         }))
    1661              :     }
    1662              : 
    1663              :     #[instrument(skip_all, fields(shard_id))]
    1664              :     async fn handle_db_size_request(
    1665              :         &mut self,
    1666              :         timeline: &Timeline,
    1667              :         req: &PagestreamDbSizeRequest,
    1668              :         ctx: &RequestContext,
    1669              :     ) -> Result<PagestreamBeMessage, PageStreamError> {
    1670              :         let latest_gc_cutoff_lsn = timeline.get_latest_gc_cutoff_lsn();
    1671              :         let lsn = Self::wait_or_get_last_lsn(
    1672              :             timeline,
    1673              :             req.hdr.request_lsn,
    1674              :             req.hdr.not_modified_since,
    1675              :             &latest_gc_cutoff_lsn,
    1676              :             ctx,
    1677              :         )
    1678              :         .await?;
    1679              : 
    1680              :         let total_blocks = timeline
    1681              :             .get_db_size(DEFAULTTABLESPACE_OID, req.dbnode, Version::Lsn(lsn), ctx)
    1682              :             .await?;
    1683              :         let db_size = total_blocks as i64 * BLCKSZ as i64;
    1684              : 
    1685              :         Ok(PagestreamBeMessage::DbSize(PagestreamDbSizeResponse {
    1686              :             req: *req,
    1687              :             db_size,
    1688              :         }))
    1689              :     }
    1690              : 
    1691              :     #[instrument(skip_all)]
    1692              :     async fn handle_get_page_at_lsn_request_batched(
    1693              :         &mut self,
    1694              :         timeline: &Timeline,
    1695              :         effective_lsn: Lsn,
    1696              :         requests: smallvec::SmallVec<[BatchedGetPageRequest; 1]>,
    1697              :         ctx: &RequestContext,
    1698              :     ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer), BatchedPageStreamError>> {
    1699              :         debug_assert_current_span_has_tenant_and_timeline_id();
    1700              : 
    1701              :         timeline
    1702              :             .query_metrics
    1703              :             .observe_getpage_batch_start(requests.len());
    1704              : 
    1705              :         let results = timeline
    1706              :             .get_rel_page_at_lsn_batched(
    1707            0 :                 requests.iter().map(|p| (&p.req.rel, &p.req.blkno)),
    1708              :                 effective_lsn,
    1709              :                 ctx,
    1710              :             )
    1711              :             .await;
    1712              :         assert_eq!(results.len(), requests.len());
    1713              : 
    1714              :         // TODO: avoid creating the new Vec here
    1715              :         Vec::from_iter(
    1716              :             requests
    1717              :                 .into_iter()
    1718              :                 .zip(results.into_iter())
    1719            0 :                 .map(|(req, res)| {
    1720            0 :                     res.map(|page| {
    1721            0 :                         (
    1722            0 :                             PagestreamBeMessage::GetPage(models::PagestreamGetPageResponse {
    1723            0 :                                 req: req.req,
    1724            0 :                                 page,
    1725            0 :                             }),
    1726            0 :                             req.timer,
    1727            0 :                         )
    1728            0 :                     })
    1729            0 :                     .map_err(|e| BatchedPageStreamError {
    1730            0 :                         err: PageStreamError::from(e),
    1731            0 :                         req: req.req.hdr,
    1732            0 :                     })
    1733            0 :                 }),
    1734              :         )
    1735              :     }
    1736              : 
    1737              :     #[instrument(skip_all, fields(shard_id))]
    1738              :     async fn handle_get_slru_segment_request(
    1739              :         &mut self,
    1740              :         timeline: &Timeline,
    1741              :         req: &PagestreamGetSlruSegmentRequest,
    1742              :         ctx: &RequestContext,
    1743              :     ) -> Result<PagestreamBeMessage, PageStreamError> {
    1744              :         let latest_gc_cutoff_lsn = timeline.get_latest_gc_cutoff_lsn();
    1745              :         let lsn = Self::wait_or_get_last_lsn(
    1746              :             timeline,
    1747              :             req.hdr.request_lsn,
    1748              :             req.hdr.not_modified_since,
    1749              :             &latest_gc_cutoff_lsn,
    1750              :             ctx,
    1751              :         )
    1752              :         .await?;
    1753              : 
    1754              :         let kind = SlruKind::from_repr(req.kind)
    1755              :             .ok_or(PageStreamError::BadRequest("invalid SLRU kind".into()))?;
    1756              :         let segment = timeline.get_slru_segment(kind, req.segno, lsn, ctx).await?;
    1757              : 
    1758              :         Ok(PagestreamBeMessage::GetSlruSegment(
    1759              :             PagestreamGetSlruSegmentResponse { req: *req, segment },
    1760              :         ))
    1761              :     }
    1762              : 
    1763              :     /// Note on "fullbackup":
    1764              :     /// Full basebackups should only be used for debugging purposes.
    1765              :     /// Originally, it was introduced to enable breaking storage format changes,
    1766              :     /// but that is not applicable anymore.
    1767              :     ///
    1768              :     /// # Coding Discipline
    1769              :     ///
    1770              :     /// Coding discipline within this function: all interaction with the `pgb` connection
    1771              :     /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
    1772              :     /// This is so that we can shutdown page_service quickly.
    1773              :     ///
    1774              :     /// TODO: wrap the pgb that we pass to the basebackup handler so that it's sensitive
    1775              :     /// to connection cancellation.
    1776              :     #[allow(clippy::too_many_arguments)]
    1777              :     #[instrument(skip_all, fields(shard_id, ?lsn, ?prev_lsn, %full_backup))]
    1778              :     async fn handle_basebackup_request<IO>(
    1779              :         &mut self,
    1780              :         pgb: &mut PostgresBackend<IO>,
    1781              :         tenant_id: TenantId,
    1782              :         timeline_id: TimelineId,
    1783              :         lsn: Option<Lsn>,
    1784              :         prev_lsn: Option<Lsn>,
    1785              :         full_backup: bool,
    1786              :         gzip: bool,
    1787              :         replica: bool,
    1788              :         ctx: &RequestContext,
    1789              :     ) -> Result<(), QueryError>
    1790              :     where
    1791              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
    1792              :     {
    1793            0 :         fn map_basebackup_error(err: BasebackupError) -> QueryError {
    1794            0 :             match err {
    1795            0 :                 BasebackupError::Client(e) => QueryError::Disconnected(ConnectionError::Io(e)),
    1796            0 :                 BasebackupError::Server(e) => QueryError::Other(e),
    1797              :             }
    1798            0 :         }
    1799              : 
    1800              :         let started = std::time::Instant::now();
    1801              : 
    1802              :         let timeline = self
    1803              :             .timeline_handles
    1804              :             .as_mut()
    1805              :             .unwrap()
    1806              :             .get(tenant_id, timeline_id, ShardSelector::Zero)
    1807              :             .await?;
    1808              : 
    1809              :         let latest_gc_cutoff_lsn = timeline.get_latest_gc_cutoff_lsn();
    1810              :         if let Some(lsn) = lsn {
    1811              :             // Backup was requested at a particular LSN. Wait for it to arrive.
    1812              :             info!("waiting for {}", lsn);
    1813              :             timeline
    1814              :                 .wait_lsn(
    1815              :                     lsn,
    1816              :                     crate::tenant::timeline::WaitLsnWaiter::PageService,
    1817              :                     ctx,
    1818              :                 )
    1819              :                 .await?;
    1820              :             timeline
    1821              :                 .check_lsn_is_in_scope(lsn, &latest_gc_cutoff_lsn)
    1822              :                 .context("invalid basebackup lsn")?;
    1823              :         }
    1824              : 
    1825              :         let lsn_awaited_after = started.elapsed();
    1826              : 
    1827              :         // switch client to COPYOUT
    1828              :         pgb.write_message_noflush(&BeMessage::CopyOutResponse)
    1829              :             .map_err(QueryError::Disconnected)?;
    1830              :         self.flush_cancellable(pgb, &self.cancel).await?;
    1831              : 
    1832              :         // Send a tarball of the latest layer on the timeline. Compress if not
    1833              :         // fullbackup. TODO Compress in that case too (tests need to be updated)
    1834              :         if full_backup {
    1835              :             let mut writer = pgb.copyout_writer();
    1836              :             basebackup::send_basebackup_tarball(
    1837              :                 &mut writer,
    1838              :                 &timeline,
    1839              :                 lsn,
    1840              :                 prev_lsn,
    1841              :                 full_backup,
    1842              :                 replica,
    1843              :                 ctx,
    1844              :             )
    1845              :             .await
    1846              :             .map_err(map_basebackup_error)?;
    1847              :         } else {
    1848              :             let mut writer = BufWriter::new(pgb.copyout_writer());
    1849              :             if gzip {
    1850              :                 let mut encoder = GzipEncoder::with_quality(
    1851              :                     &mut writer,
    1852              :                     // NOTE using fast compression because it's on the critical path
    1853              :                     //      for compute startup. For an empty database, we get
    1854              :                     //      <100KB with this method. The Level::Best compression method
    1855              :                     //      gives us <20KB, but maybe we should add basebackup caching
    1856              :                     //      on compute shutdown first.
    1857              :                     async_compression::Level::Fastest,
    1858              :                 );
    1859              :                 basebackup::send_basebackup_tarball(
    1860              :                     &mut encoder,
    1861              :                     &timeline,
    1862              :                     lsn,
    1863              :                     prev_lsn,
    1864              :                     full_backup,
    1865              :                     replica,
    1866              :                     ctx,
    1867              :                 )
    1868              :                 .await
    1869              :                 .map_err(map_basebackup_error)?;
    1870              :                 // shutdown the encoder to ensure the gzip footer is written
    1871              :                 encoder
    1872              :                     .shutdown()
    1873              :                     .await
    1874            0 :                     .map_err(|e| QueryError::Disconnected(ConnectionError::Io(e)))?;
    1875              :             } else {
    1876              :                 basebackup::send_basebackup_tarball(
    1877              :                     &mut writer,
    1878              :                     &timeline,
    1879              :                     lsn,
    1880              :                     prev_lsn,
    1881              :                     full_backup,
    1882              :                     replica,
    1883              :                     ctx,
    1884              :                 )
    1885              :                 .await
    1886              :                 .map_err(map_basebackup_error)?;
    1887              :             }
    1888              :             writer
    1889              :                 .flush()
    1890              :                 .await
    1891            0 :                 .map_err(|e| map_basebackup_error(BasebackupError::Client(e)))?;
    1892              :         }
    1893              : 
    1894              :         pgb.write_message_noflush(&BeMessage::CopyDone)
    1895              :             .map_err(QueryError::Disconnected)?;
    1896              :         self.flush_cancellable(pgb, &timeline.cancel).await?;
    1897              : 
    1898              :         let basebackup_after = started
    1899              :             .elapsed()
    1900              :             .checked_sub(lsn_awaited_after)
    1901              :             .unwrap_or(Duration::ZERO);
    1902              : 
    1903              :         info!(
    1904              :             lsn_await_millis = lsn_awaited_after.as_millis(),
    1905              :             basebackup_millis = basebackup_after.as_millis(),
    1906              :             "basebackup complete"
    1907              :         );
    1908              : 
    1909              :         Ok(())
    1910              :     }
    1911              : 
    1912              :     // when accessing management api supply None as an argument
    1913              :     // when using to authorize tenant pass corresponding tenant id
    1914            0 :     fn check_permission(&self, tenant_id: Option<TenantId>) -> Result<(), QueryError> {
    1915            0 :         if self.auth.is_none() {
    1916              :             // auth is set to Trust, nothing to check so just return ok
    1917            0 :             return Ok(());
    1918            0 :         }
    1919            0 :         // auth is some, just checked above, when auth is some
    1920            0 :         // then claims are always present because of checks during connection init
    1921            0 :         // so this expect won't trigger
    1922            0 :         let claims = self
    1923            0 :             .claims
    1924            0 :             .as_ref()
    1925            0 :             .expect("claims presence already checked");
    1926            0 :         check_permission(claims, tenant_id).map_err(|e| QueryError::Unauthorized(e.0))
    1927            0 :     }
    1928              : }
    1929              : 
    1930              : /// `basebackup tenant timeline [lsn] [--gzip] [--replica]`
    1931              : #[derive(Debug, Clone, Eq, PartialEq)]
    1932              : struct BaseBackupCmd {
    1933              :     tenant_id: TenantId,
    1934              :     timeline_id: TimelineId,
    1935              :     lsn: Option<Lsn>,
    1936              :     gzip: bool,
    1937              :     replica: bool,
    1938              : }
    1939              : 
    1940              : /// `fullbackup tenant timeline [lsn] [prev_lsn]`
    1941              : #[derive(Debug, Clone, Eq, PartialEq)]
    1942              : struct FullBackupCmd {
    1943              :     tenant_id: TenantId,
    1944              :     timeline_id: TimelineId,
    1945              :     lsn: Option<Lsn>,
    1946              :     prev_lsn: Option<Lsn>,
    1947              : }
    1948              : 
    1949              : /// `pagestream_v2 tenant timeline`
    1950              : #[derive(Debug, Clone, Eq, PartialEq)]
    1951              : struct PageStreamCmd {
    1952              :     tenant_id: TenantId,
    1953              :     timeline_id: TimelineId,
    1954              :     protocol_version: PagestreamProtocolVersion,
    1955              : }
    1956              : 
    1957              : /// `lease lsn tenant timeline lsn`
    1958              : #[derive(Debug, Clone, Eq, PartialEq)]
    1959              : struct LeaseLsnCmd {
    1960              :     tenant_shard_id: TenantShardId,
    1961              :     timeline_id: TimelineId,
    1962              :     lsn: Lsn,
    1963              : }
    1964              : 
    1965              : #[derive(Debug, Clone, Eq, PartialEq)]
    1966              : enum PageServiceCmd {
    1967              :     Set,
    1968              :     PageStream(PageStreamCmd),
    1969              :     BaseBackup(BaseBackupCmd),
    1970              :     FullBackup(FullBackupCmd),
    1971              :     LeaseLsn(LeaseLsnCmd),
    1972              : }
    1973              : 
    1974              : impl PageStreamCmd {
    1975            6 :     fn parse(query: &str, protocol_version: PagestreamProtocolVersion) -> anyhow::Result<Self> {
    1976            6 :         let parameters = query.split_whitespace().collect_vec();
    1977            6 :         if parameters.len() != 2 {
    1978            2 :             bail!(
    1979            2 :                 "invalid number of parameters for pagestream command: {}",
    1980            2 :                 query
    1981            2 :             );
    1982            4 :         }
    1983            4 :         let tenant_id = TenantId::from_str(parameters[0])
    1984            4 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    1985            2 :         let timeline_id = TimelineId::from_str(parameters[1])
    1986            2 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    1987            2 :         Ok(Self {
    1988            2 :             tenant_id,
    1989            2 :             timeline_id,
    1990            2 :             protocol_version,
    1991            2 :         })
    1992            6 :     }
    1993              : }
    1994              : 
    1995              : impl FullBackupCmd {
    1996            4 :     fn parse(query: &str) -> anyhow::Result<Self> {
    1997            4 :         let parameters = query.split_whitespace().collect_vec();
    1998            4 :         if parameters.len() < 2 || parameters.len() > 4 {
    1999            0 :             bail!(
    2000            0 :                 "invalid number of parameters for basebackup command: {}",
    2001            0 :                 query
    2002            0 :             );
    2003            4 :         }
    2004            4 :         let tenant_id = TenantId::from_str(parameters[0])
    2005            4 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2006            4 :         let timeline_id = TimelineId::from_str(parameters[1])
    2007            4 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2008              :         // The caller is responsible for providing correct lsn and prev_lsn.
    2009            4 :         let lsn = if let Some(lsn_str) = parameters.get(2) {
    2010              :             Some(
    2011            2 :                 Lsn::from_str(lsn_str)
    2012            2 :                     .with_context(|| format!("Failed to parse Lsn from {lsn_str}"))?,
    2013              :             )
    2014              :         } else {
    2015            2 :             None
    2016              :         };
    2017            4 :         let prev_lsn = if let Some(prev_lsn_str) = parameters.get(3) {
    2018              :             Some(
    2019            2 :                 Lsn::from_str(prev_lsn_str)
    2020            2 :                     .with_context(|| format!("Failed to parse Lsn from {prev_lsn_str}"))?,
    2021              :             )
    2022              :         } else {
    2023            2 :             None
    2024              :         };
    2025            4 :         Ok(Self {
    2026            4 :             tenant_id,
    2027            4 :             timeline_id,
    2028            4 :             lsn,
    2029            4 :             prev_lsn,
    2030            4 :         })
    2031            4 :     }
    2032              : }
    2033              : 
    2034              : impl BaseBackupCmd {
    2035           18 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2036           18 :         let parameters = query.split_whitespace().collect_vec();
    2037           18 :         if parameters.len() < 2 {
    2038            0 :             bail!(
    2039            0 :                 "invalid number of parameters for basebackup command: {}",
    2040            0 :                 query
    2041            0 :             );
    2042           18 :         }
    2043           18 :         let tenant_id = TenantId::from_str(parameters[0])
    2044           18 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2045           18 :         let timeline_id = TimelineId::from_str(parameters[1])
    2046           18 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2047              :         let lsn;
    2048              :         let flags_parse_from;
    2049           18 :         if let Some(maybe_lsn) = parameters.get(2) {
    2050           16 :             if *maybe_lsn == "latest" {
    2051            2 :                 lsn = None;
    2052            2 :                 flags_parse_from = 3;
    2053           14 :             } else if maybe_lsn.starts_with("--") {
    2054           10 :                 lsn = None;
    2055           10 :                 flags_parse_from = 2;
    2056           10 :             } else {
    2057              :                 lsn = Some(
    2058            4 :                     Lsn::from_str(maybe_lsn)
    2059            4 :                         .with_context(|| format!("Failed to parse lsn from {maybe_lsn}"))?,
    2060              :                 );
    2061            4 :                 flags_parse_from = 3;
    2062              :             }
    2063            2 :         } else {
    2064            2 :             lsn = None;
    2065            2 :             flags_parse_from = 2;
    2066            2 :         }
    2067              : 
    2068           18 :         let mut gzip = false;
    2069           18 :         let mut replica = false;
    2070              : 
    2071           22 :         for &param in &parameters[flags_parse_from..] {
    2072           22 :             match param {
    2073           22 :                 "--gzip" => {
    2074           14 :                     if gzip {
    2075            2 :                         bail!("duplicate parameter for basebackup command: {param}")
    2076           12 :                     }
    2077           12 :                     gzip = true
    2078              :                 }
    2079            8 :                 "--replica" => {
    2080            4 :                     if replica {
    2081            0 :                         bail!("duplicate parameter for basebackup command: {param}")
    2082            4 :                     }
    2083            4 :                     replica = true
    2084              :                 }
    2085            4 :                 _ => bail!("invalid parameter for basebackup command: {param}"),
    2086              :             }
    2087              :         }
    2088           12 :         Ok(Self {
    2089           12 :             tenant_id,
    2090           12 :             timeline_id,
    2091           12 :             lsn,
    2092           12 :             gzip,
    2093           12 :             replica,
    2094           12 :         })
    2095           18 :     }
    2096              : }
    2097              : 
    2098              : impl LeaseLsnCmd {
    2099            4 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2100            4 :         let parameters = query.split_whitespace().collect_vec();
    2101            4 :         if parameters.len() != 3 {
    2102            0 :             bail!(
    2103            0 :                 "invalid number of parameters for lease lsn command: {}",
    2104            0 :                 query
    2105            0 :             );
    2106            4 :         }
    2107            4 :         let tenant_shard_id = TenantShardId::from_str(parameters[0])
    2108            4 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2109            4 :         let timeline_id = TimelineId::from_str(parameters[1])
    2110            4 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2111            4 :         let lsn = Lsn::from_str(parameters[2])
    2112            4 :             .with_context(|| format!("Failed to parse lsn from {}", parameters[2]))?;
    2113            4 :         Ok(Self {
    2114            4 :             tenant_shard_id,
    2115            4 :             timeline_id,
    2116            4 :             lsn,
    2117            4 :         })
    2118            4 :     }
    2119              : }
    2120              : 
    2121              : impl PageServiceCmd {
    2122           42 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2123           42 :         let query = query.trim();
    2124           42 :         let Some((cmd, other)) = query.split_once(' ') else {
    2125            4 :             bail!("cannot parse query: {query}")
    2126              :         };
    2127           38 :         match cmd.to_ascii_lowercase().as_str() {
    2128           38 :             "pagestream_v2" => Ok(Self::PageStream(PageStreamCmd::parse(
    2129            6 :                 other,
    2130            6 :                 PagestreamProtocolVersion::V2,
    2131            6 :             )?)),
    2132           32 :             "pagestream_v3" => Ok(Self::PageStream(PageStreamCmd::parse(
    2133            0 :                 other,
    2134            0 :                 PagestreamProtocolVersion::V3,
    2135            0 :             )?)),
    2136           32 :             "basebackup" => Ok(Self::BaseBackup(BaseBackupCmd::parse(other)?)),
    2137           14 :             "fullbackup" => Ok(Self::FullBackup(FullBackupCmd::parse(other)?)),
    2138           10 :             "lease" => {
    2139            6 :                 let Some((cmd2, other)) = other.split_once(' ') else {
    2140            0 :                     bail!("invalid lease command: {cmd}");
    2141              :                 };
    2142            6 :                 let cmd2 = cmd2.to_ascii_lowercase();
    2143            6 :                 if cmd2 == "lsn" {
    2144            4 :                     Ok(Self::LeaseLsn(LeaseLsnCmd::parse(other)?))
    2145              :                 } else {
    2146            2 :                     bail!("invalid lease command: {cmd}");
    2147              :                 }
    2148              :             }
    2149            4 :             "set" => Ok(Self::Set),
    2150            0 :             _ => Err(anyhow::anyhow!("unsupported command {cmd} in {query}")),
    2151              :         }
    2152           42 :     }
    2153              : }
    2154              : 
    2155              : impl<IO> postgres_backend::Handler<IO> for PageServerHandler
    2156              : where
    2157              :     IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    2158              : {
    2159            0 :     fn check_auth_jwt(
    2160            0 :         &mut self,
    2161            0 :         _pgb: &mut PostgresBackend<IO>,
    2162            0 :         jwt_response: &[u8],
    2163            0 :     ) -> Result<(), QueryError> {
    2164              :         // this unwrap is never triggered, because check_auth_jwt only called when auth_type is NeonJWT
    2165              :         // which requires auth to be present
    2166            0 :         let data = self
    2167            0 :             .auth
    2168            0 :             .as_ref()
    2169            0 :             .unwrap()
    2170            0 :             .decode(str::from_utf8(jwt_response).context("jwt response is not UTF-8")?)
    2171            0 :             .map_err(|e| QueryError::Unauthorized(e.0))?;
    2172              : 
    2173            0 :         if matches!(data.claims.scope, Scope::Tenant) && data.claims.tenant_id.is_none() {
    2174            0 :             return Err(QueryError::Unauthorized(
    2175            0 :                 "jwt token scope is Tenant, but tenant id is missing".into(),
    2176            0 :             ));
    2177            0 :         }
    2178            0 : 
    2179            0 :         debug!(
    2180            0 :             "jwt scope check succeeded for scope: {:#?} by tenant id: {:?}",
    2181              :             data.claims.scope, data.claims.tenant_id,
    2182              :         );
    2183              : 
    2184            0 :         self.claims = Some(data.claims);
    2185            0 :         Ok(())
    2186            0 :     }
    2187              : 
    2188            0 :     fn startup(
    2189            0 :         &mut self,
    2190            0 :         _pgb: &mut PostgresBackend<IO>,
    2191            0 :         _sm: &FeStartupPacket,
    2192            0 :     ) -> Result<(), QueryError> {
    2193            0 :         fail::fail_point!("ps::connection-start::startup-packet");
    2194            0 :         Ok(())
    2195            0 :     }
    2196              : 
    2197              :     #[instrument(skip_all, fields(tenant_id, timeline_id))]
    2198              :     async fn process_query(
    2199              :         &mut self,
    2200              :         pgb: &mut PostgresBackend<IO>,
    2201              :         query_string: &str,
    2202              :     ) -> Result<(), QueryError> {
    2203            0 :         fail::fail_point!("simulated-bad-compute-connection", |_| {
    2204            0 :             info!("Hit failpoint for bad connection");
    2205            0 :             Err(QueryError::SimulatedConnectionError)
    2206            0 :         });
    2207              : 
    2208              :         fail::fail_point!("ps::connection-start::process-query");
    2209              : 
    2210              :         let ctx = self.connection_ctx.attached_child();
    2211              :         debug!("process query {query_string}");
    2212              :         let query = PageServiceCmd::parse(query_string)?;
    2213              :         match query {
    2214              :             PageServiceCmd::PageStream(PageStreamCmd {
    2215              :                 tenant_id,
    2216              :                 timeline_id,
    2217              :                 protocol_version,
    2218              :             }) => {
    2219              :                 tracing::Span::current()
    2220              :                     .record("tenant_id", field::display(tenant_id))
    2221              :                     .record("timeline_id", field::display(timeline_id));
    2222              : 
    2223              :                 self.check_permission(Some(tenant_id))?;
    2224              :                 let command_kind = match protocol_version {
    2225              :                     PagestreamProtocolVersion::V2 => ComputeCommandKind::PageStreamV2,
    2226              :                     PagestreamProtocolVersion::V3 => ComputeCommandKind::PageStreamV3,
    2227              :                 };
    2228              :                 COMPUTE_COMMANDS_COUNTERS.for_command(command_kind).inc();
    2229              : 
    2230              :                 self.handle_pagerequests(pgb, tenant_id, timeline_id, protocol_version, ctx)
    2231              :                     .await?;
    2232              :             }
    2233              :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    2234              :                 tenant_id,
    2235              :                 timeline_id,
    2236              :                 lsn,
    2237              :                 gzip,
    2238              :                 replica,
    2239              :             }) => {
    2240              :                 tracing::Span::current()
    2241              :                     .record("tenant_id", field::display(tenant_id))
    2242              :                     .record("timeline_id", field::display(timeline_id));
    2243              : 
    2244              :                 self.check_permission(Some(tenant_id))?;
    2245              : 
    2246              :                 COMPUTE_COMMANDS_COUNTERS
    2247              :                     .for_command(ComputeCommandKind::Basebackup)
    2248              :                     .inc();
    2249              :                 let metric_recording = metrics::BASEBACKUP_QUERY_TIME.start_recording();
    2250            0 :                 let res = async {
    2251            0 :                     self.handle_basebackup_request(
    2252            0 :                         pgb,
    2253            0 :                         tenant_id,
    2254            0 :                         timeline_id,
    2255            0 :                         lsn,
    2256            0 :                         None,
    2257            0 :                         false,
    2258            0 :                         gzip,
    2259            0 :                         replica,
    2260            0 :                         &ctx,
    2261            0 :                     )
    2262            0 :                     .await?;
    2263            0 :                     pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    2264            0 :                     Result::<(), QueryError>::Ok(())
    2265            0 :                 }
    2266              :                 .await;
    2267              :                 metric_recording.observe(&res);
    2268              :                 res?;
    2269              :             }
    2270              :             // same as basebackup, but result includes relational data as well
    2271              :             PageServiceCmd::FullBackup(FullBackupCmd {
    2272              :                 tenant_id,
    2273              :                 timeline_id,
    2274              :                 lsn,
    2275              :                 prev_lsn,
    2276              :             }) => {
    2277              :                 tracing::Span::current()
    2278              :                     .record("tenant_id", field::display(tenant_id))
    2279              :                     .record("timeline_id", field::display(timeline_id));
    2280              : 
    2281              :                 self.check_permission(Some(tenant_id))?;
    2282              : 
    2283              :                 COMPUTE_COMMANDS_COUNTERS
    2284              :                     .for_command(ComputeCommandKind::Fullbackup)
    2285              :                     .inc();
    2286              : 
    2287              :                 // Check that the timeline exists
    2288              :                 self.handle_basebackup_request(
    2289              :                     pgb,
    2290              :                     tenant_id,
    2291              :                     timeline_id,
    2292              :                     lsn,
    2293              :                     prev_lsn,
    2294              :                     true,
    2295              :                     false,
    2296              :                     false,
    2297              :                     &ctx,
    2298              :                 )
    2299              :                 .await?;
    2300              :                 pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    2301              :             }
    2302              :             PageServiceCmd::Set => {
    2303              :                 // important because psycopg2 executes "SET datestyle TO 'ISO'"
    2304              :                 // on connect
    2305              :                 pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    2306              :             }
    2307              :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    2308              :                 tenant_shard_id,
    2309              :                 timeline_id,
    2310              :                 lsn,
    2311              :             }) => {
    2312              :                 tracing::Span::current()
    2313              :                     .record("tenant_id", field::display(tenant_shard_id))
    2314              :                     .record("timeline_id", field::display(timeline_id));
    2315              : 
    2316              :                 self.check_permission(Some(tenant_shard_id.tenant_id))?;
    2317              : 
    2318              :                 COMPUTE_COMMANDS_COUNTERS
    2319              :                     .for_command(ComputeCommandKind::LeaseLsn)
    2320              :                     .inc();
    2321              : 
    2322              :                 match self
    2323              :                     .handle_make_lsn_lease(pgb, tenant_shard_id, timeline_id, lsn, &ctx)
    2324              :                     .await
    2325              :                 {
    2326              :                     Ok(()) => {
    2327              :                         pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?
    2328              :                     }
    2329              :                     Err(e) => {
    2330              :                         error!("error obtaining lsn lease for {lsn}: {e:?}");
    2331              :                         pgb.write_message_noflush(&BeMessage::ErrorResponse(
    2332              :                             &e.to_string(),
    2333              :                             Some(e.pg_error_code()),
    2334              :                         ))?
    2335              :                     }
    2336              :                 };
    2337              :             }
    2338              :         }
    2339              : 
    2340              :         Ok(())
    2341              :     }
    2342              : }
    2343              : 
    2344              : impl From<GetActiveTenantError> for QueryError {
    2345            0 :     fn from(e: GetActiveTenantError) -> Self {
    2346            0 :         match e {
    2347            0 :             GetActiveTenantError::WaitForActiveTimeout { .. } => QueryError::Disconnected(
    2348            0 :                 ConnectionError::Io(io::Error::new(io::ErrorKind::TimedOut, e.to_string())),
    2349            0 :             ),
    2350              :             GetActiveTenantError::Cancelled
    2351              :             | GetActiveTenantError::WillNotBecomeActive(TenantState::Stopping { .. }) => {
    2352            0 :                 QueryError::Shutdown
    2353              :             }
    2354            0 :             e @ GetActiveTenantError::NotFound(_) => QueryError::NotFound(format!("{e}").into()),
    2355            0 :             e => QueryError::Other(anyhow::anyhow!(e)),
    2356              :         }
    2357            0 :     }
    2358              : }
    2359              : 
    2360              : #[derive(Debug, thiserror::Error)]
    2361              : pub(crate) enum GetActiveTimelineError {
    2362              :     #[error(transparent)]
    2363              :     Tenant(GetActiveTenantError),
    2364              :     #[error(transparent)]
    2365              :     Timeline(#[from] GetTimelineError),
    2366              : }
    2367              : 
    2368              : impl From<GetActiveTimelineError> for QueryError {
    2369            0 :     fn from(e: GetActiveTimelineError) -> Self {
    2370            0 :         match e {
    2371            0 :             GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled) => QueryError::Shutdown,
    2372            0 :             GetActiveTimelineError::Tenant(e) => e.into(),
    2373            0 :             GetActiveTimelineError::Timeline(e) => QueryError::NotFound(format!("{e}").into()),
    2374              :         }
    2375            0 :     }
    2376              : }
    2377              : 
    2378            0 : fn set_tracing_field_shard_id(timeline: &Timeline) {
    2379            0 :     debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    2380            0 :     tracing::Span::current().record(
    2381            0 :         "shard_id",
    2382            0 :         tracing::field::display(timeline.tenant_shard_id.shard_slug()),
    2383            0 :     );
    2384            0 :     debug_assert_current_span_has_tenant_and_timeline_id();
    2385            0 : }
    2386              : 
    2387              : struct WaitedForLsn(Lsn);
    2388              : impl From<WaitedForLsn> for Lsn {
    2389            0 :     fn from(WaitedForLsn(lsn): WaitedForLsn) -> Self {
    2390            0 :         lsn
    2391            0 :     }
    2392              : }
    2393              : 
    2394              : #[cfg(test)]
    2395              : mod tests {
    2396              :     use utils::shard::ShardCount;
    2397              : 
    2398              :     use super::*;
    2399              : 
    2400              :     #[test]
    2401            2 :     fn pageservice_cmd_parse() {
    2402            2 :         let tenant_id = TenantId::generate();
    2403            2 :         let timeline_id = TimelineId::generate();
    2404            2 :         let cmd =
    2405            2 :             PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id} {timeline_id}")).unwrap();
    2406            2 :         assert_eq!(
    2407            2 :             cmd,
    2408            2 :             PageServiceCmd::PageStream(PageStreamCmd {
    2409            2 :                 tenant_id,
    2410            2 :                 timeline_id,
    2411            2 :                 protocol_version: PagestreamProtocolVersion::V2,
    2412            2 :             })
    2413            2 :         );
    2414            2 :         let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id}")).unwrap();
    2415            2 :         assert_eq!(
    2416            2 :             cmd,
    2417            2 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    2418            2 :                 tenant_id,
    2419            2 :                 timeline_id,
    2420            2 :                 lsn: None,
    2421            2 :                 gzip: false,
    2422            2 :                 replica: false
    2423            2 :             })
    2424            2 :         );
    2425            2 :         let cmd =
    2426            2 :             PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} --gzip")).unwrap();
    2427            2 :         assert_eq!(
    2428            2 :             cmd,
    2429            2 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    2430            2 :                 tenant_id,
    2431            2 :                 timeline_id,
    2432            2 :                 lsn: None,
    2433            2 :                 gzip: true,
    2434            2 :                 replica: false
    2435            2 :             })
    2436            2 :         );
    2437            2 :         let cmd =
    2438            2 :             PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} latest")).unwrap();
    2439            2 :         assert_eq!(
    2440            2 :             cmd,
    2441            2 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    2442            2 :                 tenant_id,
    2443            2 :                 timeline_id,
    2444            2 :                 lsn: None,
    2445            2 :                 gzip: false,
    2446            2 :                 replica: false
    2447            2 :             })
    2448            2 :         );
    2449            2 :         let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} 0/16ABCDE"))
    2450            2 :             .unwrap();
    2451            2 :         assert_eq!(
    2452            2 :             cmd,
    2453            2 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    2454            2 :                 tenant_id,
    2455            2 :                 timeline_id,
    2456            2 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    2457            2 :                 gzip: false,
    2458            2 :                 replica: false
    2459            2 :             })
    2460            2 :         );
    2461            2 :         let cmd = PageServiceCmd::parse(&format!(
    2462            2 :             "basebackup {tenant_id} {timeline_id} --replica --gzip"
    2463            2 :         ))
    2464            2 :         .unwrap();
    2465            2 :         assert_eq!(
    2466            2 :             cmd,
    2467            2 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    2468            2 :                 tenant_id,
    2469            2 :                 timeline_id,
    2470            2 :                 lsn: None,
    2471            2 :                 gzip: true,
    2472            2 :                 replica: true
    2473            2 :             })
    2474            2 :         );
    2475            2 :         let cmd = PageServiceCmd::parse(&format!(
    2476            2 :             "basebackup {tenant_id} {timeline_id} 0/16ABCDE --replica --gzip"
    2477            2 :         ))
    2478            2 :         .unwrap();
    2479            2 :         assert_eq!(
    2480            2 :             cmd,
    2481            2 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    2482            2 :                 tenant_id,
    2483            2 :                 timeline_id,
    2484            2 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    2485            2 :                 gzip: true,
    2486            2 :                 replica: true
    2487            2 :             })
    2488            2 :         );
    2489            2 :         let cmd = PageServiceCmd::parse(&format!("fullbackup {tenant_id} {timeline_id}")).unwrap();
    2490            2 :         assert_eq!(
    2491            2 :             cmd,
    2492            2 :             PageServiceCmd::FullBackup(FullBackupCmd {
    2493            2 :                 tenant_id,
    2494            2 :                 timeline_id,
    2495            2 :                 lsn: None,
    2496            2 :                 prev_lsn: None
    2497            2 :             })
    2498            2 :         );
    2499            2 :         let cmd = PageServiceCmd::parse(&format!(
    2500            2 :             "fullbackup {tenant_id} {timeline_id} 0/16ABCDE 0/16ABCDF"
    2501            2 :         ))
    2502            2 :         .unwrap();
    2503            2 :         assert_eq!(
    2504            2 :             cmd,
    2505            2 :             PageServiceCmd::FullBackup(FullBackupCmd {
    2506            2 :                 tenant_id,
    2507            2 :                 timeline_id,
    2508            2 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    2509            2 :                 prev_lsn: Some(Lsn::from_str("0/16ABCDF").unwrap()),
    2510            2 :             })
    2511            2 :         );
    2512            2 :         let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    2513            2 :         let cmd = PageServiceCmd::parse(&format!(
    2514            2 :             "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
    2515            2 :         ))
    2516            2 :         .unwrap();
    2517            2 :         assert_eq!(
    2518            2 :             cmd,
    2519            2 :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    2520            2 :                 tenant_shard_id,
    2521            2 :                 timeline_id,
    2522            2 :                 lsn: Lsn::from_str("0/16ABCDE").unwrap(),
    2523            2 :             })
    2524            2 :         );
    2525            2 :         let tenant_shard_id = TenantShardId::split(&tenant_shard_id, ShardCount(8))[1];
    2526            2 :         let cmd = PageServiceCmd::parse(&format!(
    2527            2 :             "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
    2528            2 :         ))
    2529            2 :         .unwrap();
    2530            2 :         assert_eq!(
    2531            2 :             cmd,
    2532            2 :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    2533            2 :                 tenant_shard_id,
    2534            2 :                 timeline_id,
    2535            2 :                 lsn: Lsn::from_str("0/16ABCDE").unwrap(),
    2536            2 :             })
    2537            2 :         );
    2538            2 :         let cmd = PageServiceCmd::parse("set a = b").unwrap();
    2539            2 :         assert_eq!(cmd, PageServiceCmd::Set);
    2540            2 :         let cmd = PageServiceCmd::parse("SET foo").unwrap();
    2541            2 :         assert_eq!(cmd, PageServiceCmd::Set);
    2542            2 :     }
    2543              : 
    2544              :     #[test]
    2545            2 :     fn pageservice_cmd_err_handling() {
    2546            2 :         let tenant_id = TenantId::generate();
    2547            2 :         let timeline_id = TimelineId::generate();
    2548            2 :         let cmd = PageServiceCmd::parse("unknown_command");
    2549            2 :         assert!(cmd.is_err());
    2550            2 :         let cmd = PageServiceCmd::parse("pagestream_v2");
    2551            2 :         assert!(cmd.is_err());
    2552            2 :         let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx"));
    2553            2 :         assert!(cmd.is_err());
    2554            2 :         let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx {timeline_id}xxx"));
    2555            2 :         assert!(cmd.is_err());
    2556            2 :         let cmd = PageServiceCmd::parse(&format!(
    2557            2 :             "basebackup {tenant_id} {timeline_id} --gzip --gzip"
    2558            2 :         ));
    2559            2 :         assert!(cmd.is_err());
    2560            2 :         let cmd = PageServiceCmd::parse(&format!(
    2561            2 :             "basebackup {tenant_id} {timeline_id} --gzip --unknown"
    2562            2 :         ));
    2563            2 :         assert!(cmd.is_err());
    2564            2 :         let cmd = PageServiceCmd::parse(&format!(
    2565            2 :             "basebackup {tenant_id} {timeline_id} --gzip 0/16ABCDE"
    2566            2 :         ));
    2567            2 :         assert!(cmd.is_err());
    2568            2 :         let cmd = PageServiceCmd::parse(&format!("lease {tenant_id} {timeline_id} gzip 0/16ABCDE"));
    2569            2 :         assert!(cmd.is_err());
    2570            2 :     }
    2571              : }
        

Generated by: LCOV version 2.1-beta