LCOV - code coverage report
Current view: top level - pageserver/src - page_service.rs (source / functions) Coverage Total Hit
Test: aca806cab4756d7eb6a304846130f4a73a5d5393.info Lines: 22.7 % 1554 353
Test Date: 2025-04-24 20:31:15 Functions: 8.4 % 119 10

            Line data    Source code
       1              : //! The Page Service listens for client connections and serves their GetPage@LSN
       2              : //! requests.
       3              : 
       4              : use std::borrow::Cow;
       5              : use std::num::NonZeroUsize;
       6              : use std::os::fd::AsRawFd;
       7              : use std::str::FromStr;
       8              : use std::sync::Arc;
       9              : use std::time::{Duration, Instant, SystemTime};
      10              : use std::{io, str};
      11              : 
      12              : use crate::PERF_TRACE_TARGET;
      13              : use anyhow::{Context, bail};
      14              : use async_compression::tokio::write::GzipEncoder;
      15              : use bytes::Buf;
      16              : use futures::FutureExt;
      17              : use itertools::Itertools;
      18              : use jsonwebtoken::TokenData;
      19              : use once_cell::sync::OnceCell;
      20              : use pageserver_api::config::{
      21              :     PageServicePipeliningConfig, PageServicePipeliningConfigPipelined,
      22              :     PageServiceProtocolPipelinedBatchingStrategy, PageServiceProtocolPipelinedExecutionStrategy,
      23              : };
      24              : use pageserver_api::key::rel_block_to_key;
      25              : use pageserver_api::models::{
      26              :     self, PageTraceEvent, PagestreamBeMessage, PagestreamDbSizeRequest, PagestreamDbSizeResponse,
      27              :     PagestreamErrorResponse, PagestreamExistsRequest, PagestreamExistsResponse,
      28              :     PagestreamFeMessage, PagestreamGetPageRequest, PagestreamGetSlruSegmentRequest,
      29              :     PagestreamGetSlruSegmentResponse, PagestreamNblocksRequest, PagestreamNblocksResponse,
      30              :     PagestreamProtocolVersion, PagestreamRequest, TenantState,
      31              : };
      32              : use pageserver_api::reltag::SlruKind;
      33              : use pageserver_api::shard::TenantShardId;
      34              : use postgres_backend::{
      35              :     AuthType, PostgresBackend, PostgresBackendReader, QueryError, is_expected_io_error,
      36              : };
      37              : use postgres_ffi::BLCKSZ;
      38              : use postgres_ffi::pg_constants::DEFAULTTABLESPACE_OID;
      39              : use pq_proto::framed::ConnectionError;
      40              : use pq_proto::{BeMessage, FeMessage, FeStartupPacket, RowDescriptor};
      41              : use strum_macros::IntoStaticStr;
      42              : use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, BufWriter};
      43              : use tokio::task::JoinHandle;
      44              : use tokio_util::sync::CancellationToken;
      45              : use tracing::*;
      46              : use utils::auth::{Claims, Scope, SwappableJwtAuth};
      47              : use utils::failpoint_support;
      48              : use utils::id::{TenantId, TimelineId};
      49              : use utils::logging::log_slow;
      50              : use utils::lsn::Lsn;
      51              : use utils::simple_rcu::RcuReadGuard;
      52              : use utils::sync::gate::{Gate, GateGuard};
      53              : use utils::sync::spsc_fold;
      54              : 
      55              : use crate::auth::check_permission;
      56              : use crate::basebackup::BasebackupError;
      57              : use crate::config::PageServerConf;
      58              : use crate::context::{
      59              :     DownloadBehavior, PerfInstrumentFutureExt, RequestContext, RequestContextBuilder,
      60              : };
      61              : use crate::metrics::{
      62              :     self, COMPUTE_COMMANDS_COUNTERS, ComputeCommandKind, GetPageBatchBreakReason, LIVE_CONNECTIONS,
      63              :     SmgrOpTimer, TimelineMetrics,
      64              : };
      65              : use crate::pgdatadir_mapping::Version;
      66              : use crate::span::{
      67              :     debug_assert_current_span_has_tenant_and_timeline_id,
      68              :     debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id,
      69              : };
      70              : use crate::task_mgr::{self, COMPUTE_REQUEST_RUNTIME, TaskKind};
      71              : use crate::tenant::mgr::{
      72              :     GetActiveTenantError, GetTenantError, ShardResolveResult, ShardSelector, TenantManager,
      73              : };
      74              : use crate::tenant::storage_layer::IoConcurrency;
      75              : use crate::tenant::timeline::{self, WaitLsnError};
      76              : use crate::tenant::{GetTimelineError, PageReconstructError, Timeline};
      77              : use crate::{basebackup, timed_after_cancellation};
      78              : 
      79              : /// How long we may wait for a [`crate::tenant::mgr::TenantSlot::InProgress`]` and/or a [`crate::tenant::TenantShard`] which
      80              : /// is not yet in state [`TenantState::Active`].
      81              : ///
      82              : /// NB: this is a different value than [`crate::http::routes::ACTIVE_TENANT_TIMEOUT`].
      83              : const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(30000);
      84              : 
      85              : /// Threshold at which to log slow GetPage requests.
      86              : const LOG_SLOW_GETPAGE_THRESHOLD: Duration = Duration::from_secs(30);
      87              : 
      88              : ///////////////////////////////////////////////////////////////////////////////
      89              : 
      90              : pub struct Listener {
      91              :     cancel: CancellationToken,
      92              :     /// Cancel the listener task through `listen_cancel` to shut down the listener
      93              :     /// and get a handle on the existing connections.
      94              :     task: JoinHandle<Connections>,
      95              : }
      96              : 
      97              : pub struct Connections {
      98              :     cancel: CancellationToken,
      99              :     tasks: tokio::task::JoinSet<ConnectionHandlerResult>,
     100              :     gate: Gate,
     101              : }
     102              : 
     103            0 : pub fn spawn(
     104            0 :     conf: &'static PageServerConf,
     105            0 :     tenant_manager: Arc<TenantManager>,
     106            0 :     pg_auth: Option<Arc<SwappableJwtAuth>>,
     107            0 :     perf_trace_dispatch: Option<Dispatch>,
     108            0 :     tcp_listener: tokio::net::TcpListener,
     109            0 :     tls_config: Option<Arc<rustls::ServerConfig>>,
     110            0 : ) -> Listener {
     111            0 :     let cancel = CancellationToken::new();
     112            0 :     let libpq_ctx = RequestContext::todo_child(
     113            0 :         TaskKind::LibpqEndpointListener,
     114            0 :         // listener task shouldn't need to download anything. (We will
     115            0 :         // create a separate sub-contexts for each connection, with their
     116            0 :         // own download behavior. This context is used only to listen and
     117            0 :         // accept connections.)
     118            0 :         DownloadBehavior::Error,
     119            0 :     );
     120            0 :     let task = COMPUTE_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
     121            0 :         "libpq listener",
     122            0 :         libpq_listener_main(
     123            0 :             conf,
     124            0 :             tenant_manager,
     125            0 :             pg_auth,
     126            0 :             perf_trace_dispatch,
     127            0 :             tcp_listener,
     128            0 :             conf.pg_auth_type,
     129            0 :             tls_config,
     130            0 :             conf.page_service_pipelining.clone(),
     131            0 :             libpq_ctx,
     132            0 :             cancel.clone(),
     133            0 :         )
     134            0 :         .map(anyhow::Ok),
     135            0 :     ));
     136            0 : 
     137            0 :     Listener { cancel, task }
     138            0 : }
     139              : 
     140              : impl Listener {
     141            0 :     pub async fn stop_accepting(self) -> Connections {
     142            0 :         self.cancel.cancel();
     143            0 :         self.task
     144            0 :             .await
     145            0 :             .expect("unreachable: we wrap the listener task in task_mgr::exit_on_panic_or_error")
     146            0 :     }
     147              : }
     148              : impl Connections {
     149            0 :     pub(crate) async fn shutdown(self) {
     150            0 :         let Self {
     151            0 :             cancel,
     152            0 :             mut tasks,
     153            0 :             gate,
     154            0 :         } = self;
     155            0 :         cancel.cancel();
     156            0 :         while let Some(res) = tasks.join_next().await {
     157            0 :             Self::handle_connection_completion(res);
     158            0 :         }
     159            0 :         gate.close().await;
     160            0 :     }
     161              : 
     162            0 :     fn handle_connection_completion(res: Result<anyhow::Result<()>, tokio::task::JoinError>) {
     163            0 :         match res {
     164            0 :             Ok(Ok(())) => {}
     165            0 :             Ok(Err(e)) => error!("error in page_service connection task: {:?}", e),
     166            0 :             Err(e) => error!("page_service connection task panicked: {:?}", e),
     167              :         }
     168            0 :     }
     169              : }
     170              : 
     171              : ///
     172              : /// Main loop of the page service.
     173              : ///
     174              : /// Listens for connections, and launches a new handler task for each.
     175              : ///
     176              : /// Returns Ok(()) upon cancellation via `cancel`, returning the set of
     177              : /// open connections.
     178              : ///
     179              : #[allow(clippy::too_many_arguments)]
     180            0 : pub async fn libpq_listener_main(
     181            0 :     conf: &'static PageServerConf,
     182            0 :     tenant_manager: Arc<TenantManager>,
     183            0 :     auth: Option<Arc<SwappableJwtAuth>>,
     184            0 :     perf_trace_dispatch: Option<Dispatch>,
     185            0 :     listener: tokio::net::TcpListener,
     186            0 :     auth_type: AuthType,
     187            0 :     tls_config: Option<Arc<rustls::ServerConfig>>,
     188            0 :     pipelining_config: PageServicePipeliningConfig,
     189            0 :     listener_ctx: RequestContext,
     190            0 :     listener_cancel: CancellationToken,
     191            0 : ) -> Connections {
     192            0 :     let connections_cancel = CancellationToken::new();
     193            0 :     let connections_gate = Gate::default();
     194            0 :     let mut connection_handler_tasks = tokio::task::JoinSet::default();
     195              : 
     196              :     loop {
     197            0 :         let gate_guard = match connections_gate.enter() {
     198            0 :             Ok(guard) => guard,
     199            0 :             Err(_) => break,
     200              :         };
     201              : 
     202            0 :         let accepted = tokio::select! {
     203              :             biased;
     204            0 :             _ = listener_cancel.cancelled() => break,
     205            0 :             next = connection_handler_tasks.join_next(), if !connection_handler_tasks.is_empty() => {
     206            0 :                 let res = next.expect("we dont poll while empty");
     207            0 :                 Connections::handle_connection_completion(res);
     208            0 :                 continue;
     209              :             }
     210            0 :             accepted = listener.accept() => accepted,
     211            0 :         };
     212            0 : 
     213            0 :         match accepted {
     214            0 :             Ok((socket, peer_addr)) => {
     215            0 :                 // Connection established. Spawn a new task to handle it.
     216            0 :                 debug!("accepted connection from {}", peer_addr);
     217            0 :                 let local_auth = auth.clone();
     218            0 :                 let connection_ctx = RequestContextBuilder::from(&listener_ctx)
     219            0 :                     .task_kind(TaskKind::PageRequestHandler)
     220            0 :                     .download_behavior(DownloadBehavior::Download)
     221            0 :                     .perf_span_dispatch(perf_trace_dispatch.clone())
     222            0 :                     .detached_child();
     223            0 : 
     224            0 :                 connection_handler_tasks.spawn(page_service_conn_main(
     225            0 :                     conf,
     226            0 :                     tenant_manager.clone(),
     227            0 :                     local_auth,
     228            0 :                     socket,
     229            0 :                     auth_type,
     230            0 :                     tls_config.clone(),
     231            0 :                     pipelining_config.clone(),
     232            0 :                     connection_ctx,
     233            0 :                     connections_cancel.child_token(),
     234            0 :                     gate_guard,
     235            0 :                 ));
     236              :             }
     237            0 :             Err(err) => {
     238            0 :                 // accept() failed. Log the error, and loop back to retry on next connection.
     239            0 :                 error!("accept() failed: {:?}", err);
     240              :             }
     241              :         }
     242              :     }
     243              : 
     244            0 :     debug!("page_service listener loop terminated");
     245              : 
     246            0 :     Connections {
     247            0 :         cancel: connections_cancel,
     248            0 :         tasks: connection_handler_tasks,
     249            0 :         gate: connections_gate,
     250            0 :     }
     251            0 : }
     252              : 
     253              : type ConnectionHandlerResult = anyhow::Result<()>;
     254              : 
     255              : /// Perf root spans start at the per-request level, after shard routing.
     256              : /// This struct carries connection-level information to the root perf span definition.
     257              : #[derive(Clone)]
     258              : struct ConnectionPerfSpanFields {
     259              :     peer_addr: String,
     260              :     application_name: Option<String>,
     261              :     compute_mode: Option<String>,
     262              : }
     263              : 
     264              : #[instrument(skip_all, fields(peer_addr, application_name, compute_mode))]
     265              : #[allow(clippy::too_many_arguments)]
     266              : async fn page_service_conn_main(
     267              :     conf: &'static PageServerConf,
     268              :     tenant_manager: Arc<TenantManager>,
     269              :     auth: Option<Arc<SwappableJwtAuth>>,
     270              :     socket: tokio::net::TcpStream,
     271              :     auth_type: AuthType,
     272              :     tls_config: Option<Arc<rustls::ServerConfig>>,
     273              :     pipelining_config: PageServicePipeliningConfig,
     274              :     connection_ctx: RequestContext,
     275              :     cancel: CancellationToken,
     276              :     gate_guard: GateGuard,
     277              : ) -> ConnectionHandlerResult {
     278              :     let _guard = LIVE_CONNECTIONS
     279              :         .with_label_values(&["page_service"])
     280              :         .guard();
     281              : 
     282              :     socket
     283              :         .set_nodelay(true)
     284              :         .context("could not set TCP_NODELAY")?;
     285              : 
     286              :     let socket_fd = socket.as_raw_fd();
     287              : 
     288              :     let peer_addr = socket.peer_addr().context("get peer address")?;
     289              : 
     290              :     let perf_span_fields = ConnectionPerfSpanFields {
     291              :         peer_addr: peer_addr.to_string(),
     292              :         application_name: None, // filled in later
     293              :         compute_mode: None,     // filled in later
     294              :     };
     295              :     tracing::Span::current().record("peer_addr", field::display(peer_addr));
     296              : 
     297              :     // setup read timeout of 10 minutes. the timeout is rather arbitrary for requirements:
     298              :     // - long enough for most valid compute connections
     299              :     // - less than infinite to stop us from "leaking" connections to long-gone computes
     300              :     //
     301              :     // no write timeout is used, because the kernel is assumed to error writes after some time.
     302              :     let mut socket = tokio_io_timeout::TimeoutReader::new(socket);
     303              : 
     304              :     let default_timeout_ms = 10 * 60 * 1000; // 10 minutes by default
     305            0 :     let socket_timeout_ms = (|| {
     306            0 :         fail::fail_point!("simulated-bad-compute-connection", |avg_timeout_ms| {
     307              :             // Exponential distribution for simulating
     308              :             // poor network conditions, expect about avg_timeout_ms to be around 15
     309              :             // in tests
     310            0 :             if let Some(avg_timeout_ms) = avg_timeout_ms {
     311            0 :                 let avg = avg_timeout_ms.parse::<i64>().unwrap() as f32;
     312            0 :                 let u = rand::random::<f32>();
     313            0 :                 ((1.0 - u).ln() / (-avg)) as u64
     314              :             } else {
     315            0 :                 default_timeout_ms
     316              :             }
     317            0 :         });
     318            0 :         default_timeout_ms
     319              :     })();
     320              : 
     321              :     // A timeout here does not mean the client died, it can happen if it's just idle for
     322              :     // a while: we will tear down this PageServerHandler and instantiate a new one if/when
     323              :     // they reconnect.
     324              :     socket.set_timeout(Some(std::time::Duration::from_millis(socket_timeout_ms)));
     325              :     let socket = Box::pin(socket);
     326              : 
     327              :     fail::fail_point!("ps::connection-start::pre-login");
     328              : 
     329              :     // XXX: pgbackend.run() should take the connection_ctx,
     330              :     // and create a child per-query context when it invokes process_query.
     331              :     // But it's in a shared crate, so, we store connection_ctx inside PageServerHandler
     332              :     // and create the per-query context in process_query ourselves.
     333              :     let mut conn_handler = PageServerHandler::new(
     334              :         conf,
     335              :         tenant_manager,
     336              :         auth,
     337              :         pipelining_config,
     338              :         perf_span_fields,
     339              :         connection_ctx,
     340              :         cancel.clone(),
     341              :         gate_guard,
     342              :     );
     343              :     let pgbackend =
     344              :         PostgresBackend::new_from_io(socket_fd, socket, peer_addr, auth_type, tls_config)?;
     345              : 
     346              :     match pgbackend.run(&mut conn_handler, &cancel).await {
     347              :         Ok(()) => {
     348              :             // we've been requested to shut down
     349              :             Ok(())
     350              :         }
     351              :         Err(QueryError::Disconnected(ConnectionError::Io(io_error))) => {
     352              :             if is_expected_io_error(&io_error) {
     353              :                 info!("Postgres client disconnected ({io_error})");
     354              :                 Ok(())
     355              :             } else {
     356              :                 let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
     357              :                 Err(io_error).context(format!(
     358              :                     "Postgres connection error for tenant_id={:?} client at peer_addr={}",
     359              :                     tenant_id, peer_addr
     360              :                 ))
     361              :             }
     362              :         }
     363              :         other => {
     364              :             let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
     365              :             other.context(format!(
     366              :                 "Postgres query error for tenant_id={:?} client peer_addr={}",
     367              :                 tenant_id, peer_addr
     368              :             ))
     369              :         }
     370              :     }
     371              : }
     372              : 
     373              : struct PageServerHandler {
     374              :     conf: &'static PageServerConf,
     375              :     auth: Option<Arc<SwappableJwtAuth>>,
     376              :     claims: Option<Claims>,
     377              : 
     378              :     /// The context created for the lifetime of the connection
     379              :     /// services by this PageServerHandler.
     380              :     /// For each query received over the connection,
     381              :     /// `process_query` creates a child context from this one.
     382              :     connection_ctx: RequestContext,
     383              : 
     384              :     perf_span_fields: ConnectionPerfSpanFields,
     385              : 
     386              :     cancel: CancellationToken,
     387              : 
     388              :     /// None only while pagestream protocol is being processed.
     389              :     timeline_handles: Option<TimelineHandles>,
     390              : 
     391              :     pipelining_config: PageServicePipeliningConfig,
     392              : 
     393              :     gate_guard: GateGuard,
     394              : }
     395              : 
     396              : struct TimelineHandles {
     397              :     wrapper: TenantManagerWrapper,
     398              :     /// Note on size: the typical size of this map is 1.  The largest size we expect
     399              :     /// to see is the number of shards divided by the number of pageservers (typically < 2),
     400              :     /// or the ratio used when splitting shards (i.e. how many children created from one)
     401              :     /// parent shard, where a "large" number might be ~8.
     402              :     handles: timeline::handle::Cache<TenantManagerTypes>,
     403              : }
     404              : 
     405              : impl TimelineHandles {
     406            0 :     fn new(tenant_manager: Arc<TenantManager>) -> Self {
     407            0 :         Self {
     408            0 :             wrapper: TenantManagerWrapper {
     409            0 :                 tenant_manager,
     410            0 :                 tenant_id: OnceCell::new(),
     411            0 :             },
     412            0 :             handles: Default::default(),
     413            0 :         }
     414            0 :     }
     415            0 :     async fn get(
     416            0 :         &mut self,
     417            0 :         tenant_id: TenantId,
     418            0 :         timeline_id: TimelineId,
     419            0 :         shard_selector: ShardSelector,
     420            0 :     ) -> Result<timeline::handle::Handle<TenantManagerTypes>, GetActiveTimelineError> {
     421            0 :         if *self.wrapper.tenant_id.get_or_init(|| tenant_id) != tenant_id {
     422            0 :             return Err(GetActiveTimelineError::Tenant(
     423            0 :                 GetActiveTenantError::SwitchedTenant,
     424            0 :             ));
     425            0 :         }
     426            0 :         self.handles
     427            0 :             .get(timeline_id, shard_selector, &self.wrapper)
     428            0 :             .await
     429            0 :             .map_err(|e| match e {
     430            0 :                 timeline::handle::GetError::TenantManager(e) => e,
     431              :                 timeline::handle::GetError::PerTimelineStateShutDown => {
     432            0 :                     trace!("per-timeline state shut down");
     433            0 :                     GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown)
     434              :                 }
     435            0 :             })
     436            0 :     }
     437              : 
     438            0 :     fn tenant_id(&self) -> Option<TenantId> {
     439            0 :         self.wrapper.tenant_id.get().copied()
     440            0 :     }
     441              : }
     442              : 
     443              : pub(crate) struct TenantManagerWrapper {
     444              :     tenant_manager: Arc<TenantManager>,
     445              :     // We do not support switching tenant_id on a connection at this point.
     446              :     // We can can add support for this later if needed without changing
     447              :     // the protocol.
     448              :     tenant_id: once_cell::sync::OnceCell<TenantId>,
     449              : }
     450              : 
     451              : #[derive(Debug)]
     452              : pub(crate) struct TenantManagerTypes;
     453              : 
     454              : impl timeline::handle::Types for TenantManagerTypes {
     455              :     type TenantManagerError = GetActiveTimelineError;
     456              :     type TenantManager = TenantManagerWrapper;
     457              :     type Timeline = TenantManagerCacheItem;
     458              : }
     459              : 
     460              : pub(crate) struct TenantManagerCacheItem {
     461              :     pub(crate) timeline: Arc<Timeline>,
     462              :     // allow() for cheap propagation through RequestContext inside a task
     463              :     #[allow(clippy::redundant_allocation)]
     464              :     pub(crate) metrics: Arc<Arc<TimelineMetrics>>,
     465              :     #[allow(dead_code)] // we store it to keep the gate open
     466              :     pub(crate) gate_guard: GateGuard,
     467              : }
     468              : 
     469              : impl std::ops::Deref for TenantManagerCacheItem {
     470              :     type Target = Arc<Timeline>;
     471            0 :     fn deref(&self) -> &Self::Target {
     472            0 :         &self.timeline
     473            0 :     }
     474              : }
     475              : 
     476              : impl timeline::handle::Timeline<TenantManagerTypes> for TenantManagerCacheItem {
     477            0 :     fn shard_timeline_id(&self) -> timeline::handle::ShardTimelineId {
     478            0 :         Timeline::shard_timeline_id(&self.timeline)
     479            0 :     }
     480              : 
     481            0 :     fn per_timeline_state(&self) -> &timeline::handle::PerTimelineState<TenantManagerTypes> {
     482            0 :         &self.timeline.handles
     483            0 :     }
     484              : 
     485            0 :     fn get_shard_identity(&self) -> &pageserver_api::shard::ShardIdentity {
     486            0 :         Timeline::get_shard_identity(&self.timeline)
     487            0 :     }
     488              : }
     489              : 
     490              : impl timeline::handle::TenantManager<TenantManagerTypes> for TenantManagerWrapper {
     491            0 :     async fn resolve(
     492            0 :         &self,
     493            0 :         timeline_id: TimelineId,
     494            0 :         shard_selector: ShardSelector,
     495            0 :     ) -> Result<TenantManagerCacheItem, GetActiveTimelineError> {
     496            0 :         let tenant_id = self.tenant_id.get().expect("we set this in get()");
     497            0 :         let timeout = ACTIVE_TENANT_TIMEOUT;
     498            0 :         let wait_start = Instant::now();
     499            0 :         let deadline = wait_start + timeout;
     500            0 :         let tenant_shard = loop {
     501            0 :             let resolved = self
     502            0 :                 .tenant_manager
     503            0 :                 .resolve_attached_shard(tenant_id, shard_selector);
     504            0 :             match resolved {
     505            0 :                 ShardResolveResult::Found(tenant_shard) => break tenant_shard,
     506              :                 ShardResolveResult::NotFound => {
     507            0 :                     return Err(GetActiveTimelineError::Tenant(
     508            0 :                         GetActiveTenantError::NotFound(GetTenantError::NotFound(*tenant_id)),
     509            0 :                     ));
     510              :                 }
     511            0 :                 ShardResolveResult::InProgress(barrier) => {
     512            0 :                     // We can't authoritatively answer right now: wait for InProgress state
     513            0 :                     // to end, then try again
     514            0 :                     tokio::select! {
     515            0 :                         _  = barrier.wait() => {
     516            0 :                             // The barrier completed: proceed around the loop to try looking up again
     517            0 :                         },
     518            0 :                         _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
     519            0 :                             return Err(GetActiveTimelineError::Tenant(GetActiveTenantError::WaitForActiveTimeout {
     520            0 :                                 latest_state: None,
     521            0 :                                 wait_time: timeout,
     522            0 :                             }));
     523              :                         }
     524              :                     }
     525              :                 }
     526              :             };
     527              :         };
     528              : 
     529            0 :         tracing::debug!("Waiting for tenant to enter active state...");
     530            0 :         tenant_shard
     531            0 :             .wait_to_become_active(deadline.duration_since(Instant::now()))
     532            0 :             .await
     533            0 :             .map_err(GetActiveTimelineError::Tenant)?;
     534              : 
     535            0 :         let timeline = tenant_shard
     536            0 :             .get_timeline(timeline_id, true)
     537            0 :             .map_err(GetActiveTimelineError::Timeline)?;
     538              : 
     539            0 :         let gate_guard = match timeline.gate.enter() {
     540            0 :             Ok(guard) => guard,
     541              :             Err(_) => {
     542            0 :                 return Err(GetActiveTimelineError::Timeline(
     543            0 :                     GetTimelineError::ShuttingDown,
     544            0 :                 ));
     545              :             }
     546              :         };
     547              : 
     548            0 :         let metrics = Arc::new(Arc::clone(&timeline.metrics));
     549            0 : 
     550            0 :         Ok(TenantManagerCacheItem {
     551            0 :             timeline,
     552            0 :             metrics,
     553            0 :             gate_guard,
     554            0 :         })
     555            0 :     }
     556              : }
     557              : 
     558              : #[derive(thiserror::Error, Debug)]
     559              : enum PageStreamError {
     560              :     /// We encountered an error that should prompt the client to reconnect:
     561              :     /// in practice this means we drop the connection without sending a response.
     562              :     #[error("Reconnect required: {0}")]
     563              :     Reconnect(Cow<'static, str>),
     564              : 
     565              :     /// We were instructed to shutdown while processing the query
     566              :     #[error("Shutting down")]
     567              :     Shutdown,
     568              : 
     569              :     /// Something went wrong reading a page: this likely indicates a pageserver bug
     570              :     #[error("Read error")]
     571              :     Read(#[source] PageReconstructError),
     572              : 
     573              :     /// Ran out of time waiting for an LSN
     574              :     #[error("LSN timeout: {0}")]
     575              :     LsnTimeout(WaitLsnError),
     576              : 
     577              :     /// The entity required to serve the request (tenant or timeline) is not found,
     578              :     /// or is not found in a suitable state to serve a request.
     579              :     #[error("Not found: {0}")]
     580              :     NotFound(Cow<'static, str>),
     581              : 
     582              :     /// Request asked for something that doesn't make sense, like an invalid LSN
     583              :     #[error("Bad request: {0}")]
     584              :     BadRequest(Cow<'static, str>),
     585              : }
     586              : 
     587              : impl From<PageReconstructError> for PageStreamError {
     588            0 :     fn from(value: PageReconstructError) -> Self {
     589            0 :         match value {
     590            0 :             PageReconstructError::Cancelled => Self::Shutdown,
     591            0 :             e => Self::Read(e),
     592              :         }
     593            0 :     }
     594              : }
     595              : 
     596              : impl From<GetActiveTimelineError> for PageStreamError {
     597            0 :     fn from(value: GetActiveTimelineError) -> Self {
     598            0 :         match value {
     599              :             GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled)
     600              :             | GetActiveTimelineError::Tenant(GetActiveTenantError::WillNotBecomeActive(
     601              :                 TenantState::Stopping { .. },
     602              :             ))
     603            0 :             | GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown) => Self::Shutdown,
     604            0 :             GetActiveTimelineError::Tenant(e) => Self::NotFound(format!("{e}").into()),
     605            0 :             GetActiveTimelineError::Timeline(e) => Self::NotFound(format!("{e}").into()),
     606              :         }
     607            0 :     }
     608              : }
     609              : 
     610              : impl From<WaitLsnError> for PageStreamError {
     611            0 :     fn from(value: WaitLsnError) -> Self {
     612            0 :         match value {
     613            0 :             e @ WaitLsnError::Timeout(_) => Self::LsnTimeout(e),
     614            0 :             WaitLsnError::Shutdown => Self::Shutdown,
     615            0 :             e @ WaitLsnError::BadState { .. } => Self::Reconnect(format!("{e}").into()),
     616              :         }
     617            0 :     }
     618              : }
     619              : 
     620              : impl From<WaitLsnError> for QueryError {
     621            0 :     fn from(value: WaitLsnError) -> Self {
     622            0 :         match value {
     623            0 :             e @ WaitLsnError::Timeout(_) => Self::Other(anyhow::Error::new(e)),
     624            0 :             WaitLsnError::Shutdown => Self::Shutdown,
     625            0 :             WaitLsnError::BadState { .. } => Self::Reconnect,
     626              :         }
     627            0 :     }
     628              : }
     629              : 
     630              : #[derive(thiserror::Error, Debug)]
     631              : struct BatchedPageStreamError {
     632              :     req: PagestreamRequest,
     633              :     err: PageStreamError,
     634              : }
     635              : 
     636              : impl std::fmt::Display for BatchedPageStreamError {
     637            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     638            0 :         self.err.fmt(f)
     639            0 :     }
     640              : }
     641              : 
     642              : struct BatchedGetPageRequest {
     643              :     req: PagestreamGetPageRequest,
     644              :     timer: SmgrOpTimer,
     645              :     effective_request_lsn: Lsn,
     646              :     ctx: RequestContext,
     647              : }
     648              : 
     649              : #[cfg(feature = "testing")]
     650              : struct BatchedTestRequest {
     651              :     req: models::PagestreamTestRequest,
     652              :     timer: SmgrOpTimer,
     653              : }
     654              : 
     655              : /// NB: we only hold [`timeline::handle::WeakHandle`] inside this enum,
     656              : /// so that we don't keep the [`Timeline::gate`] open while the batch
     657              : /// is being built up inside the [`spsc_fold`] (pagestream pipelining).
     658              : #[derive(IntoStaticStr)]
     659              : enum BatchedFeMessage {
     660              :     Exists {
     661              :         span: Span,
     662              :         timer: SmgrOpTimer,
     663              :         shard: timeline::handle::WeakHandle<TenantManagerTypes>,
     664              :         req: models::PagestreamExistsRequest,
     665              :     },
     666              :     Nblocks {
     667              :         span: Span,
     668              :         timer: SmgrOpTimer,
     669              :         shard: timeline::handle::WeakHandle<TenantManagerTypes>,
     670              :         req: models::PagestreamNblocksRequest,
     671              :     },
     672              :     GetPage {
     673              :         span: Span,
     674              :         shard: timeline::handle::WeakHandle<TenantManagerTypes>,
     675              :         pages: smallvec::SmallVec<[BatchedGetPageRequest; 1]>,
     676              :         batch_break_reason: GetPageBatchBreakReason,
     677              :     },
     678              :     DbSize {
     679              :         span: Span,
     680              :         timer: SmgrOpTimer,
     681              :         shard: timeline::handle::WeakHandle<TenantManagerTypes>,
     682              :         req: models::PagestreamDbSizeRequest,
     683              :     },
     684              :     GetSlruSegment {
     685              :         span: Span,
     686              :         timer: SmgrOpTimer,
     687              :         shard: timeline::handle::WeakHandle<TenantManagerTypes>,
     688              :         req: models::PagestreamGetSlruSegmentRequest,
     689              :     },
     690              :     #[cfg(feature = "testing")]
     691              :     Test {
     692              :         span: Span,
     693              :         shard: timeline::handle::WeakHandle<TenantManagerTypes>,
     694              :         requests: Vec<BatchedTestRequest>,
     695              :     },
     696              :     RespondError {
     697              :         span: Span,
     698              :         error: BatchedPageStreamError,
     699              :     },
     700              : }
     701              : 
     702              : impl BatchedFeMessage {
     703            0 :     fn as_static_str(&self) -> &'static str {
     704            0 :         self.into()
     705            0 :     }
     706              : 
     707            0 :     fn observe_execution_start(&mut self, at: Instant) {
     708            0 :         match self {
     709            0 :             BatchedFeMessage::Exists { timer, .. }
     710            0 :             | BatchedFeMessage::Nblocks { timer, .. }
     711            0 :             | BatchedFeMessage::DbSize { timer, .. }
     712            0 :             | BatchedFeMessage::GetSlruSegment { timer, .. } => {
     713            0 :                 timer.observe_execution_start(at);
     714            0 :             }
     715            0 :             BatchedFeMessage::GetPage { pages, .. } => {
     716            0 :                 for page in pages {
     717            0 :                     page.timer.observe_execution_start(at);
     718            0 :                 }
     719              :             }
     720              :             #[cfg(feature = "testing")]
     721            0 :             BatchedFeMessage::Test { requests, .. } => {
     722            0 :                 for req in requests {
     723            0 :                     req.timer.observe_execution_start(at);
     724            0 :                 }
     725              :             }
     726            0 :             BatchedFeMessage::RespondError { .. } => {}
     727              :         }
     728            0 :     }
     729              : 
     730            0 :     fn should_break_batch(
     731            0 :         &self,
     732            0 :         other: &BatchedFeMessage,
     733            0 :         max_batch_size: NonZeroUsize,
     734            0 :         batching_strategy: PageServiceProtocolPipelinedBatchingStrategy,
     735            0 :     ) -> Option<GetPageBatchBreakReason> {
     736            0 :         match (self, other) {
     737              :             (
     738              :                 BatchedFeMessage::GetPage {
     739            0 :                     shard: accum_shard,
     740            0 :                     pages: accum_pages,
     741            0 :                     ..
     742            0 :                 },
     743            0 :                 BatchedFeMessage::GetPage {
     744            0 :                     shard: this_shard,
     745            0 :                     pages: this_pages,
     746            0 :                     ..
     747            0 :                 },
     748            0 :             ) => {
     749            0 :                 assert_eq!(this_pages.len(), 1);
     750            0 :                 if accum_pages.len() >= max_batch_size.get() {
     751            0 :                     trace!(%max_batch_size, "stopping batching because of batch size");
     752            0 :                     assert_eq!(accum_pages.len(), max_batch_size.get());
     753              : 
     754            0 :                     return Some(GetPageBatchBreakReason::BatchFull);
     755            0 :                 }
     756            0 :                 if !accum_shard.is_same_handle_as(this_shard) {
     757            0 :                     trace!("stopping batching because timeline object mismatch");
     758              :                     // TODO: we _could_ batch & execute each shard seperately (and in parallel).
     759              :                     // But the current logic for keeping responses in order does not support that.
     760              : 
     761            0 :                     return Some(GetPageBatchBreakReason::NonUniformTimeline);
     762            0 :                 }
     763            0 : 
     764            0 :                 match batching_strategy {
     765              :                     PageServiceProtocolPipelinedBatchingStrategy::UniformLsn => {
     766            0 :                         if let Some(last_in_batch) = accum_pages.last() {
     767            0 :                             if last_in_batch.effective_request_lsn
     768            0 :                                 != this_pages[0].effective_request_lsn
     769              :                             {
     770            0 :                                 trace!(
     771              :                                     accum_lsn = %last_in_batch.effective_request_lsn,
     772            0 :                                     this_lsn = %this_pages[0].effective_request_lsn,
     773            0 :                                     "stopping batching because LSN changed"
     774              :                                 );
     775              : 
     776            0 :                                 return Some(GetPageBatchBreakReason::NonUniformLsn);
     777            0 :                             }
     778            0 :                         }
     779              :                     }
     780              :                     PageServiceProtocolPipelinedBatchingStrategy::ScatteredLsn => {
     781              :                         // The read path doesn't curently support serving the same page at different LSNs.
     782              :                         // While technically possible, it's uncertain if the complexity is worth it.
     783              :                         // Break the batch if such a case is encountered.
     784            0 :                         let same_page_different_lsn = accum_pages.iter().any(|batched| {
     785            0 :                             batched.req.rel == this_pages[0].req.rel
     786            0 :                                 && batched.req.blkno == this_pages[0].req.blkno
     787            0 :                                 && batched.effective_request_lsn
     788            0 :                                     != this_pages[0].effective_request_lsn
     789            0 :                         });
     790            0 : 
     791            0 :                         if same_page_different_lsn {
     792            0 :                             trace!(
     793            0 :                                 rel=%this_pages[0].req.rel,
     794            0 :                                 blkno=%this_pages[0].req.blkno,
     795            0 :                                 lsn=%this_pages[0].effective_request_lsn,
     796            0 :                                 "stopping batching because same page was requested at different LSNs"
     797              :                             );
     798              : 
     799            0 :                             return Some(GetPageBatchBreakReason::SamePageAtDifferentLsn);
     800            0 :                         }
     801              :                     }
     802              :                 }
     803              : 
     804            0 :                 None
     805              :             }
     806              :             #[cfg(feature = "testing")]
     807              :             (
     808              :                 BatchedFeMessage::Test {
     809            0 :                     shard: accum_shard,
     810            0 :                     requests: accum_requests,
     811            0 :                     ..
     812            0 :                 },
     813            0 :                 BatchedFeMessage::Test {
     814            0 :                     shard: this_shard,
     815            0 :                     requests: this_requests,
     816            0 :                     ..
     817            0 :                 },
     818            0 :             ) => {
     819            0 :                 assert!(this_requests.len() == 1);
     820            0 :                 if accum_requests.len() >= max_batch_size.get() {
     821            0 :                     trace!(%max_batch_size, "stopping batching because of batch size");
     822            0 :                     assert_eq!(accum_requests.len(), max_batch_size.get());
     823            0 :                     return Some(GetPageBatchBreakReason::BatchFull);
     824            0 :                 }
     825            0 :                 if !accum_shard.is_same_handle_as(this_shard) {
     826            0 :                     trace!("stopping batching because timeline object mismatch");
     827              :                     // TODO: we _could_ batch & execute each shard seperately (and in parallel).
     828              :                     // But the current logic for keeping responses in order does not support that.
     829            0 :                     return Some(GetPageBatchBreakReason::NonUniformTimeline);
     830            0 :                 }
     831            0 :                 let this_batch_key = this_requests[0].req.batch_key;
     832            0 :                 let accum_batch_key = accum_requests[0].req.batch_key;
     833            0 :                 if this_requests[0].req.batch_key != accum_requests[0].req.batch_key {
     834            0 :                     trace!(%accum_batch_key, %this_batch_key, "stopping batching because batch key changed");
     835            0 :                     return Some(GetPageBatchBreakReason::NonUniformKey);
     836            0 :                 }
     837            0 :                 None
     838              :             }
     839            0 :             (_, _) => Some(GetPageBatchBreakReason::NonBatchableRequest),
     840              :         }
     841            0 :     }
     842              : }
     843              : 
     844              : impl PageServerHandler {
     845              :     #[allow(clippy::too_many_arguments)]
     846            0 :     pub fn new(
     847            0 :         conf: &'static PageServerConf,
     848            0 :         tenant_manager: Arc<TenantManager>,
     849            0 :         auth: Option<Arc<SwappableJwtAuth>>,
     850            0 :         pipelining_config: PageServicePipeliningConfig,
     851            0 :         perf_span_fields: ConnectionPerfSpanFields,
     852            0 :         connection_ctx: RequestContext,
     853            0 :         cancel: CancellationToken,
     854            0 :         gate_guard: GateGuard,
     855            0 :     ) -> Self {
     856            0 :         PageServerHandler {
     857            0 :             conf,
     858            0 :             auth,
     859            0 :             claims: None,
     860            0 :             connection_ctx,
     861            0 :             perf_span_fields,
     862            0 :             timeline_handles: Some(TimelineHandles::new(tenant_manager)),
     863            0 :             cancel,
     864            0 :             pipelining_config,
     865            0 :             gate_guard,
     866            0 :         }
     867            0 :     }
     868              : 
     869              :     /// This function always respects cancellation of any timeline in `[Self::shard_timelines]`.  Pass in
     870              :     /// a cancellation token at the next scope up (such as a tenant cancellation token) to ensure we respect
     871              :     /// cancellation if there aren't any timelines in the cache.
     872              :     ///
     873              :     /// If calling from a function that doesn't use the `[Self::shard_timelines]` cache, then pass in the
     874              :     /// timeline cancellation token.
     875            0 :     async fn flush_cancellable<IO>(
     876            0 :         &self,
     877            0 :         pgb: &mut PostgresBackend<IO>,
     878            0 :         cancel: &CancellationToken,
     879            0 :     ) -> Result<(), QueryError>
     880            0 :     where
     881            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
     882            0 :     {
     883            0 :         tokio::select!(
     884            0 :             flush_r = pgb.flush() => {
     885            0 :                 Ok(flush_r?)
     886              :             },
     887            0 :             _ = cancel.cancelled() => {
     888            0 :                 Err(QueryError::Shutdown)
     889              :             }
     890              :         )
     891            0 :     }
     892              : 
     893              :     #[allow(clippy::too_many_arguments)]
     894            0 :     async fn pagestream_read_message<IO>(
     895            0 :         pgb: &mut PostgresBackendReader<IO>,
     896            0 :         tenant_id: TenantId,
     897            0 :         timeline_id: TimelineId,
     898            0 :         timeline_handles: &mut TimelineHandles,
     899            0 :         conn_perf_span_fields: &ConnectionPerfSpanFields,
     900            0 :         cancel: &CancellationToken,
     901            0 :         ctx: &RequestContext,
     902            0 :         protocol_version: PagestreamProtocolVersion,
     903            0 :         parent_span: Span,
     904            0 :     ) -> Result<Option<BatchedFeMessage>, QueryError>
     905            0 :     where
     906            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
     907            0 :     {
     908            0 :         let msg = tokio::select! {
     909              :             biased;
     910            0 :             _ = cancel.cancelled() => {
     911            0 :                 return Err(QueryError::Shutdown)
     912              :             }
     913            0 :             msg = pgb.read_message() => { msg }
     914            0 :         };
     915            0 : 
     916            0 :         let received_at = Instant::now();
     917              : 
     918            0 :         let copy_data_bytes = match msg? {
     919            0 :             Some(FeMessage::CopyData(bytes)) => bytes,
     920              :             Some(FeMessage::Terminate) => {
     921            0 :                 return Ok(None);
     922              :             }
     923            0 :             Some(m) => {
     924            0 :                 return Err(QueryError::Other(anyhow::anyhow!(
     925            0 :                     "unexpected message: {m:?} during COPY"
     926            0 :                 )));
     927              :             }
     928              :             None => {
     929            0 :                 return Ok(None);
     930              :             } // client disconnected
     931              :         };
     932            0 :         trace!("query: {copy_data_bytes:?}");
     933              : 
     934            0 :         fail::fail_point!("ps::handle-pagerequest-message");
     935              : 
     936              :         // parse request
     937            0 :         let neon_fe_msg =
     938            0 :             PagestreamFeMessage::parse(&mut copy_data_bytes.reader(), protocol_version)?;
     939              : 
     940              :         // TODO: turn in to async closure once available to avoid repeating received_at
     941            0 :         async fn record_op_start_and_throttle(
     942            0 :             shard: &timeline::handle::Handle<TenantManagerTypes>,
     943            0 :             op: metrics::SmgrQueryType,
     944            0 :             received_at: Instant,
     945            0 :         ) -> Result<SmgrOpTimer, QueryError> {
     946            0 :             // It's important to start the smgr op metric recorder as early as possible
     947            0 :             // so that the _started counters are incremented before we do
     948            0 :             // any serious waiting, e.g., for throttle, batching, or actual request handling.
     949            0 :             let mut timer = shard.query_metrics.start_smgr_op(op, received_at);
     950            0 :             let now = Instant::now();
     951            0 :             timer.observe_throttle_start(now);
     952            0 :             let throttled = tokio::select! {
     953            0 :                 res = shard.pagestream_throttle.throttle(1, now) => res,
     954            0 :                 _ = shard.cancel.cancelled() => return Err(QueryError::Shutdown),
     955              :             };
     956            0 :             timer.observe_throttle_done(throttled);
     957            0 :             Ok(timer)
     958            0 :         }
     959              : 
     960            0 :         let batched_msg = match neon_fe_msg {
     961            0 :             PagestreamFeMessage::Exists(req) => {
     962            0 :                 let shard = timeline_handles
     963            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
     964            0 :                     .await?;
     965            0 :                 debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
     966            0 :                 let span = tracing::info_span!(parent: &parent_span, "handle_get_rel_exists_request", rel = %req.rel, req_lsn = %req.hdr.request_lsn, shard_id = %shard.tenant_shard_id.shard_slug());
     967            0 :                 let timer = record_op_start_and_throttle(
     968            0 :                     &shard,
     969            0 :                     metrics::SmgrQueryType::GetRelExists,
     970            0 :                     received_at,
     971            0 :                 )
     972            0 :                 .await?;
     973            0 :                 BatchedFeMessage::Exists {
     974            0 :                     span,
     975            0 :                     timer,
     976            0 :                     shard: shard.downgrade(),
     977            0 :                     req,
     978            0 :                 }
     979              :             }
     980            0 :             PagestreamFeMessage::Nblocks(req) => {
     981            0 :                 let shard = timeline_handles
     982            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
     983            0 :                     .await?;
     984            0 :                 let span = tracing::info_span!(parent: &parent_span, "handle_get_nblocks_request", rel = %req.rel, req_lsn = %req.hdr.request_lsn, shard_id = %shard.tenant_shard_id.shard_slug());
     985            0 :                 let timer = record_op_start_and_throttle(
     986            0 :                     &shard,
     987            0 :                     metrics::SmgrQueryType::GetRelSize,
     988            0 :                     received_at,
     989            0 :                 )
     990            0 :                 .await?;
     991            0 :                 BatchedFeMessage::Nblocks {
     992            0 :                     span,
     993            0 :                     timer,
     994            0 :                     shard: shard.downgrade(),
     995            0 :                     req,
     996            0 :                 }
     997              :             }
     998            0 :             PagestreamFeMessage::DbSize(req) => {
     999            0 :                 let shard = timeline_handles
    1000            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
    1001            0 :                     .await?;
    1002            0 :                 let span = tracing::info_span!(parent: &parent_span, "handle_db_size_request", dbnode = %req.dbnode, req_lsn = %req.hdr.request_lsn, shard_id = %shard.tenant_shard_id.shard_slug());
    1003            0 :                 let timer = record_op_start_and_throttle(
    1004            0 :                     &shard,
    1005            0 :                     metrics::SmgrQueryType::GetDbSize,
    1006            0 :                     received_at,
    1007            0 :                 )
    1008            0 :                 .await?;
    1009            0 :                 BatchedFeMessage::DbSize {
    1010            0 :                     span,
    1011            0 :                     timer,
    1012            0 :                     shard: shard.downgrade(),
    1013            0 :                     req,
    1014            0 :                 }
    1015              :             }
    1016            0 :             PagestreamFeMessage::GetSlruSegment(req) => {
    1017            0 :                 let shard = timeline_handles
    1018            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
    1019            0 :                     .await?;
    1020            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, shard_id = %shard.tenant_shard_id.shard_slug());
    1021            0 :                 let timer = record_op_start_and_throttle(
    1022            0 :                     &shard,
    1023            0 :                     metrics::SmgrQueryType::GetSlruSegment,
    1024            0 :                     received_at,
    1025            0 :                 )
    1026            0 :                 .await?;
    1027            0 :                 BatchedFeMessage::GetSlruSegment {
    1028            0 :                     span,
    1029            0 :                     timer,
    1030            0 :                     shard: shard.downgrade(),
    1031            0 :                     req,
    1032            0 :                 }
    1033              :             }
    1034            0 :             PagestreamFeMessage::GetPage(req) => {
    1035              :                 // avoid a somewhat costly Span::record() by constructing the entire span in one go.
    1036              :                 macro_rules! mkspan {
    1037              :                     (before shard routing) => {{
    1038              :                         tracing::info_span!(parent: &parent_span, "handle_get_page_request", rel = %req.rel, blkno = %req.blkno, req_lsn = %req.hdr.request_lsn)
    1039              :                     }};
    1040              :                     ($shard_id:expr) => {{
    1041              :                         tracing::info_span!(parent: &parent_span, "handle_get_page_request", rel = %req.rel, blkno = %req.blkno, req_lsn = %req.hdr.request_lsn, shard_id = %$shard_id)
    1042              :                     }};
    1043              :                 }
    1044              : 
    1045              :                 macro_rules! respond_error {
    1046              :                     ($span:expr, $error:expr) => {{
    1047              :                         let error = BatchedFeMessage::RespondError {
    1048              :                             span: $span,
    1049              :                             error: BatchedPageStreamError {
    1050              :                                 req: req.hdr,
    1051              :                                 err: $error,
    1052              :                             },
    1053              :                         };
    1054              :                         Ok(Some(error))
    1055              :                     }};
    1056              :                 }
    1057              : 
    1058            0 :                 let key = rel_block_to_key(req.rel, req.blkno);
    1059              : 
    1060            0 :                 let res = timeline_handles
    1061            0 :                     .get(tenant_id, timeline_id, ShardSelector::Page(key))
    1062            0 :                     .await;
    1063              : 
    1064            0 :                 let shard = match res {
    1065            0 :                     Ok(tl) => tl,
    1066            0 :                     Err(e) => {
    1067            0 :                         let span = mkspan!(before shard routing);
    1068            0 :                         match e {
    1069              :                             GetActiveTimelineError::Tenant(GetActiveTenantError::NotFound(_)) => {
    1070              :                                 // We already know this tenant exists in general, because we resolved it at
    1071              :                                 // start of connection.  Getting a NotFound here indicates that the shard containing
    1072              :                                 // the requested page is not present on this node: the client's knowledge of shard->pageserver
    1073              :                                 // mapping is out of date.
    1074              :                                 //
    1075              :                                 // Closing the connection by returning ``::Reconnect` has the side effect of rate-limiting above message, via
    1076              :                                 // client's reconnect backoff, as well as hopefully prompting the client to load its updated configuration
    1077              :                                 // and talk to a different pageserver.
    1078            0 :                                 return respond_error!(
    1079            0 :                                     span,
    1080            0 :                                     PageStreamError::Reconnect(
    1081            0 :                                         "getpage@lsn request routed to wrong shard".into()
    1082            0 :                                     )
    1083            0 :                                 );
    1084              :                             }
    1085            0 :                             e => {
    1086            0 :                                 return respond_error!(span, e.into());
    1087              :                             }
    1088              :                         }
    1089              :                     }
    1090              :                 };
    1091              : 
    1092            0 :                 let ctx = if shard.is_get_page_request_sampled() {
    1093            0 :                     RequestContextBuilder::from(ctx)
    1094            0 :                         .root_perf_span(|| {
    1095            0 :                             info_span!(
    1096              :                             target: PERF_TRACE_TARGET,
    1097              :                             "GET_PAGE",
    1098              :                             peer_addr = conn_perf_span_fields.peer_addr,
    1099              :                             application_name = conn_perf_span_fields.application_name,
    1100              :                             compute_mode = conn_perf_span_fields.compute_mode,
    1101              :                             tenant_id = %tenant_id,
    1102            0 :                             shard_id = %shard.get_shard_identity().shard_slug(),
    1103              :                             timeline_id = %timeline_id,
    1104              :                             lsn = %req.hdr.request_lsn,
    1105              :                             request_id = %req.hdr.reqid,
    1106              :                             key = %key,
    1107              :                             )
    1108            0 :                         })
    1109            0 :                         .attached_child()
    1110              :                 } else {
    1111            0 :                     ctx.attached_child()
    1112              :                 };
    1113              : 
    1114              :                 // This ctx travels as part of the BatchedFeMessage through
    1115              :                 // batching into the request handler.
    1116              :                 // The request handler needs to do some per-request work
    1117              :                 // (relsize check) before dispatching the batch as a single
    1118              :                 // get_vectored call to the Timeline.
    1119              :                 // This ctx will be used for the reslize check, whereas the
    1120              :                 // get_vectored call will be a different ctx with separate
    1121              :                 // perf span.
    1122            0 :                 let ctx = ctx.with_scope_page_service_pagestream(&shard);
    1123              : 
    1124              :                 // Similar game for this `span`: we funnel it through so that
    1125              :                 // request handler log messages contain the request-specific fields.
    1126            0 :                 let span = mkspan!(shard.tenant_shard_id.shard_slug());
    1127              : 
    1128            0 :                 let timer = record_op_start_and_throttle(
    1129            0 :                     &shard,
    1130            0 :                     metrics::SmgrQueryType::GetPageAtLsn,
    1131            0 :                     received_at,
    1132            0 :                 )
    1133            0 :                 .maybe_perf_instrument(&ctx, |current_perf_span| {
    1134            0 :                     info_span!(
    1135              :                         target: PERF_TRACE_TARGET,
    1136            0 :                         parent: current_perf_span,
    1137              :                         "THROTTLE",
    1138              :                     )
    1139            0 :                 })
    1140            0 :                 .await?;
    1141              : 
    1142              :                 // We're holding the Handle
    1143            0 :                 let effective_request_lsn = match Self::effective_request_lsn(
    1144            0 :                     &shard,
    1145            0 :                     shard.get_last_record_lsn(),
    1146            0 :                     req.hdr.request_lsn,
    1147            0 :                     req.hdr.not_modified_since,
    1148            0 :                     &shard.get_applied_gc_cutoff_lsn(),
    1149            0 :                 ) {
    1150            0 :                     Ok(lsn) => lsn,
    1151            0 :                     Err(e) => {
    1152            0 :                         return respond_error!(span, e);
    1153              :                     }
    1154              :                 };
    1155              : 
    1156              :                 BatchedFeMessage::GetPage {
    1157            0 :                     span,
    1158            0 :                     shard: shard.downgrade(),
    1159            0 :                     pages: smallvec::smallvec![BatchedGetPageRequest {
    1160            0 :                         req,
    1161            0 :                         timer,
    1162            0 :                         effective_request_lsn,
    1163            0 :                         ctx,
    1164            0 :                     }],
    1165              :                     // The executor grabs the batch when it becomes idle.
    1166              :                     // Hence, [`GetPageBatchBreakReason::ExecutorSteal`] is the
    1167              :                     // default reason for breaking the batch.
    1168            0 :                     batch_break_reason: GetPageBatchBreakReason::ExecutorSteal,
    1169              :                 }
    1170              :             }
    1171              :             #[cfg(feature = "testing")]
    1172            0 :             PagestreamFeMessage::Test(req) => {
    1173            0 :                 let shard = timeline_handles
    1174            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
    1175            0 :                     .await?;
    1176            0 :                 let span = tracing::info_span!(parent: &parent_span, "handle_test_request", shard_id = %shard.tenant_shard_id.shard_slug());
    1177            0 :                 let timer =
    1178            0 :                     record_op_start_and_throttle(&shard, metrics::SmgrQueryType::Test, received_at)
    1179            0 :                         .await?;
    1180            0 :                 BatchedFeMessage::Test {
    1181            0 :                     span,
    1182            0 :                     shard: shard.downgrade(),
    1183            0 :                     requests: vec![BatchedTestRequest { req, timer }],
    1184            0 :                 }
    1185              :             }
    1186              :         };
    1187            0 :         Ok(Some(batched_msg))
    1188            0 :     }
    1189              : 
    1190              :     /// Post-condition: `batch` is Some()
    1191              :     #[instrument(skip_all, level = tracing::Level::TRACE)]
    1192              :     #[allow(clippy::boxed_local)]
    1193              :     fn pagestream_do_batch(
    1194              :         batching_strategy: PageServiceProtocolPipelinedBatchingStrategy,
    1195              :         max_batch_size: NonZeroUsize,
    1196              :         batch: &mut Result<BatchedFeMessage, QueryError>,
    1197              :         this_msg: Result<BatchedFeMessage, QueryError>,
    1198              :     ) -> Result<(), Result<BatchedFeMessage, QueryError>> {
    1199              :         debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    1200              : 
    1201              :         let this_msg = match this_msg {
    1202              :             Ok(this_msg) => this_msg,
    1203              :             Err(e) => return Err(Err(e)),
    1204              :         };
    1205              : 
    1206              :         let eligible_batch = match batch {
    1207              :             Ok(b) => b,
    1208              :             Err(_) => {
    1209              :                 return Err(Ok(this_msg));
    1210              :             }
    1211              :         };
    1212              : 
    1213              :         let batch_break =
    1214              :             eligible_batch.should_break_batch(&this_msg, max_batch_size, batching_strategy);
    1215              : 
    1216              :         match batch_break {
    1217              :             Some(reason) => {
    1218              :                 if let BatchedFeMessage::GetPage {
    1219              :                     batch_break_reason, ..
    1220              :                 } = eligible_batch
    1221              :                 {
    1222              :                     *batch_break_reason = reason;
    1223              :                 }
    1224              : 
    1225              :                 Err(Ok(this_msg))
    1226              :             }
    1227              :             None => {
    1228              :                 // ok to batch
    1229              :                 match (eligible_batch, this_msg) {
    1230              :                     (
    1231              :                         BatchedFeMessage::GetPage {
    1232              :                             pages: accum_pages, ..
    1233              :                         },
    1234              :                         BatchedFeMessage::GetPage {
    1235              :                             pages: this_pages, ..
    1236              :                         },
    1237              :                     ) => {
    1238              :                         accum_pages.extend(this_pages);
    1239              :                         Ok(())
    1240              :                     }
    1241              :                     #[cfg(feature = "testing")]
    1242              :                     (
    1243              :                         BatchedFeMessage::Test {
    1244              :                             requests: accum_requests,
    1245              :                             ..
    1246              :                         },
    1247              :                         BatchedFeMessage::Test {
    1248              :                             requests: this_requests,
    1249              :                             ..
    1250              :                         },
    1251              :                     ) => {
    1252              :                         accum_requests.extend(this_requests);
    1253              :                         Ok(())
    1254              :                     }
    1255              :                     // Shape guaranteed by [`BatchedFeMessage::should_break_batch`]
    1256              :                     _ => unreachable!(),
    1257              :                 }
    1258              :             }
    1259              :         }
    1260              :     }
    1261              : 
    1262            0 :     #[instrument(level = tracing::Level::DEBUG, skip_all)]
    1263              :     async fn pagesteam_handle_batched_message<IO>(
    1264              :         &mut self,
    1265              :         pgb_writer: &mut PostgresBackend<IO>,
    1266              :         batch: BatchedFeMessage,
    1267              :         io_concurrency: IoConcurrency,
    1268              :         cancel: &CancellationToken,
    1269              :         protocol_version: PagestreamProtocolVersion,
    1270              :         ctx: &RequestContext,
    1271              :     ) -> Result<(), QueryError>
    1272              :     where
    1273              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
    1274              :     {
    1275              :         let started_at = Instant::now();
    1276              :         let batch = {
    1277              :             let mut batch = batch;
    1278              :             batch.observe_execution_start(started_at);
    1279              :             batch
    1280              :         };
    1281              : 
    1282              :         // Dispatch the batch to the appropriate request handler.
    1283              :         let log_slow_name = batch.as_static_str();
    1284              :         let (mut handler_results, span) = {
    1285              :             // TODO: we unfortunately have to pin the future on the heap, since GetPage futures are huge and
    1286              :             // won't fit on the stack.
    1287              :             let mut boxpinned =
    1288              :                 Box::pin(self.pagestream_dispatch_batched_message(batch, io_concurrency, ctx));
    1289              :             log_slow(
    1290              :                 log_slow_name,
    1291              :                 LOG_SLOW_GETPAGE_THRESHOLD,
    1292              :                 boxpinned.as_mut(),
    1293              :             )
    1294              :             .await?
    1295              :         };
    1296              : 
    1297              :         // We purposefully don't count flush time into the smgr operation timer.
    1298              :         //
    1299              :         // The reason is that current compute client will not perform protocol processing
    1300              :         // if the postgres backend process is doing things other than `->smgr_read()`.
    1301              :         // This is especially the case for prefetch.
    1302              :         //
    1303              :         // If the compute doesn't read from the connection, eventually TCP will backpressure
    1304              :         // all the way into our flush call below.
    1305              :         //
    1306              :         // The timer's underlying metric is used for a storage-internal latency SLO and
    1307              :         // we don't want to include latency in it that we can't control.
    1308              :         // And as pointed out above, in this case, we don't control the time that flush will take.
    1309              :         //
    1310              :         // We put each response in the batch onto the wire in a separate pgb_writer.flush()
    1311              :         // call, which (all unmeasured) adds syscall overhead but reduces time to first byte
    1312              :         // and avoids building up a "giant" contiguous userspace buffer to hold the entire response.
    1313              :         // TODO: vectored socket IO would be great, but pgb_writer doesn't support that.
    1314              :         let flush_timers = {
    1315              :             let flushing_start_time = Instant::now();
    1316              :             let mut flush_timers = Vec::with_capacity(handler_results.len());
    1317              :             for handler_result in &mut handler_results {
    1318              :                 let flush_timer = match handler_result {
    1319              :                     Ok((_, timer)) => Some(
    1320              :                         timer
    1321              :                             .observe_execution_end(flushing_start_time)
    1322              :                             .expect("we are the first caller"),
    1323              :                     ),
    1324              :                     Err(_) => {
    1325              :                         // TODO: measure errors
    1326              :                         None
    1327              :                     }
    1328              :                 };
    1329              :                 flush_timers.push(flush_timer);
    1330              :             }
    1331              :             assert_eq!(flush_timers.len(), handler_results.len());
    1332              :             flush_timers
    1333              :         };
    1334              : 
    1335              :         // Map handler result to protocol behavior.
    1336              :         // Some handler errors cause exit from pagestream protocol.
    1337              :         // Other handler errors are sent back as an error message and we stay in pagestream protocol.
    1338              :         for (handler_result, flushing_timer) in handler_results.into_iter().zip(flush_timers) {
    1339              :             let response_msg = match handler_result {
    1340              :                 Err(e) => match &e.err {
    1341              :                     PageStreamError::Shutdown => {
    1342              :                         // If we fail to fulfil a request during shutdown, which may be _because_ of
    1343              :                         // shutdown, then do not send the error to the client.  Instead just drop the
    1344              :                         // connection.
    1345            0 :                         span.in_scope(|| info!("dropping connection due to shutdown"));
    1346              :                         return Err(QueryError::Shutdown);
    1347              :                     }
    1348              :                     PageStreamError::Reconnect(reason) => {
    1349            0 :                         span.in_scope(|| info!("handler requested reconnect: {reason}"));
    1350              :                         return Err(QueryError::Reconnect);
    1351              :                     }
    1352              :                     PageStreamError::Read(_)
    1353              :                     | PageStreamError::LsnTimeout(_)
    1354              :                     | PageStreamError::NotFound(_)
    1355              :                     | PageStreamError::BadRequest(_) => {
    1356              :                         // print the all details to the log with {:#}, but for the client the
    1357              :                         // error message is enough.  Do not log if shutting down, as the anyhow::Error
    1358              :                         // here includes cancellation which is not an error.
    1359              :                         let full = utils::error::report_compact_sources(&e.err);
    1360            0 :                         span.in_scope(|| {
    1361            0 :                             error!("error reading relation or page version: {full:#}")
    1362            0 :                         });
    1363              : 
    1364              :                         PagestreamBeMessage::Error(PagestreamErrorResponse {
    1365              :                             req: e.req,
    1366              :                             message: e.err.to_string(),
    1367              :                         })
    1368              :                     }
    1369              :                 },
    1370              :                 Ok((response_msg, _op_timer_already_observed)) => response_msg,
    1371              :             };
    1372              : 
    1373              :             //
    1374              :             // marshal & transmit response message
    1375              :             //
    1376              : 
    1377              :             pgb_writer.write_message_noflush(&BeMessage::CopyData(
    1378              :                 &response_msg.serialize(protocol_version),
    1379              :             ))?;
    1380              : 
    1381              :             failpoint_support::sleep_millis_async!("before-pagestream-msg-flush", cancel);
    1382              : 
    1383              :             // what we want to do
    1384              :             let socket_fd = pgb_writer.socket_fd;
    1385              :             let flush_fut = pgb_writer.flush();
    1386              :             // metric for how long flushing takes
    1387              :             let flush_fut = match flushing_timer {
    1388              :                 Some(flushing_timer) => futures::future::Either::Left(flushing_timer.measure(
    1389              :                     Instant::now(),
    1390              :                     flush_fut,
    1391              :                     socket_fd,
    1392              :                 )),
    1393              :                 None => futures::future::Either::Right(flush_fut),
    1394              :             };
    1395              :             // do it while respecting cancellation
    1396            0 :             let _: () = async move {
    1397            0 :                 tokio::select! {
    1398              :                     biased;
    1399            0 :                     _ = cancel.cancelled() => {
    1400              :                         // We were requested to shut down.
    1401            0 :                         info!("shutdown request received in page handler");
    1402            0 :                         return Err(QueryError::Shutdown)
    1403              :                     }
    1404            0 :                     res = flush_fut => {
    1405            0 :                         res?;
    1406              :                     }
    1407              :                 }
    1408            0 :                 Ok(())
    1409            0 :             }
    1410              :             .await?;
    1411              :         }
    1412              :         Ok(())
    1413              :     }
    1414              : 
    1415              :     /// Helper which dispatches a batched message to the appropriate handler.
    1416              :     /// Returns a vec of results, along with the extracted trace span.
    1417            0 :     async fn pagestream_dispatch_batched_message(
    1418            0 :         &mut self,
    1419            0 :         batch: BatchedFeMessage,
    1420            0 :         io_concurrency: IoConcurrency,
    1421            0 :         ctx: &RequestContext,
    1422            0 :     ) -> Result<
    1423            0 :         (
    1424            0 :             Vec<Result<(PagestreamBeMessage, SmgrOpTimer), BatchedPageStreamError>>,
    1425            0 :             Span,
    1426            0 :         ),
    1427            0 :         QueryError,
    1428            0 :     > {
    1429              :         macro_rules! upgrade_handle_and_set_context {
    1430              :             ($shard:ident) => {{
    1431              :                 let weak_handle = &$shard;
    1432              :                 let handle = weak_handle.upgrade()?;
    1433              :                 let ctx = ctx.with_scope_page_service_pagestream(&handle);
    1434              :                 (handle, ctx)
    1435              :             }};
    1436              :         }
    1437            0 :         Ok(match batch {
    1438              :             BatchedFeMessage::Exists {
    1439            0 :                 span,
    1440            0 :                 timer,
    1441            0 :                 shard,
    1442            0 :                 req,
    1443            0 :             } => {
    1444            0 :                 fail::fail_point!("ps::handle-pagerequest-message::exists");
    1445            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1446              :                 (
    1447            0 :                     vec![
    1448            0 :                         self.handle_get_rel_exists_request(&shard, &req, &ctx)
    1449            0 :                             .instrument(span.clone())
    1450            0 :                             .await
    1451            0 :                             .map(|msg| (msg, timer))
    1452            0 :                             .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
    1453            0 :                     ],
    1454            0 :                     span,
    1455              :                 )
    1456              :             }
    1457              :             BatchedFeMessage::Nblocks {
    1458            0 :                 span,
    1459            0 :                 timer,
    1460            0 :                 shard,
    1461            0 :                 req,
    1462            0 :             } => {
    1463            0 :                 fail::fail_point!("ps::handle-pagerequest-message::nblocks");
    1464            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1465              :                 (
    1466            0 :                     vec![
    1467            0 :                         self.handle_get_nblocks_request(&shard, &req, &ctx)
    1468            0 :                             .instrument(span.clone())
    1469            0 :                             .await
    1470            0 :                             .map(|msg| (msg, timer))
    1471            0 :                             .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
    1472            0 :                     ],
    1473            0 :                     span,
    1474              :                 )
    1475              :             }
    1476              :             BatchedFeMessage::GetPage {
    1477            0 :                 span,
    1478            0 :                 shard,
    1479            0 :                 pages,
    1480            0 :                 batch_break_reason,
    1481            0 :             } => {
    1482            0 :                 fail::fail_point!("ps::handle-pagerequest-message::getpage");
    1483            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1484              :                 (
    1485              :                     {
    1486            0 :                         let npages = pages.len();
    1487            0 :                         trace!(npages, "handling getpage request");
    1488            0 :                         let res = self
    1489            0 :                             .handle_get_page_at_lsn_request_batched(
    1490            0 :                                 &shard,
    1491            0 :                                 pages,
    1492            0 :                                 io_concurrency,
    1493            0 :                                 batch_break_reason,
    1494            0 :                                 &ctx,
    1495            0 :                             )
    1496            0 :                             .instrument(span.clone())
    1497            0 :                             .await;
    1498            0 :                         assert_eq!(res.len(), npages);
    1499            0 :                         res
    1500            0 :                     },
    1501            0 :                     span,
    1502              :                 )
    1503              :             }
    1504              :             BatchedFeMessage::DbSize {
    1505            0 :                 span,
    1506            0 :                 timer,
    1507            0 :                 shard,
    1508            0 :                 req,
    1509            0 :             } => {
    1510            0 :                 fail::fail_point!("ps::handle-pagerequest-message::dbsize");
    1511            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1512              :                 (
    1513            0 :                     vec![
    1514            0 :                         self.handle_db_size_request(&shard, &req, &ctx)
    1515            0 :                             .instrument(span.clone())
    1516            0 :                             .await
    1517            0 :                             .map(|msg| (msg, timer))
    1518            0 :                             .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
    1519            0 :                     ],
    1520            0 :                     span,
    1521              :                 )
    1522              :             }
    1523              :             BatchedFeMessage::GetSlruSegment {
    1524            0 :                 span,
    1525            0 :                 timer,
    1526            0 :                 shard,
    1527            0 :                 req,
    1528            0 :             } => {
    1529            0 :                 fail::fail_point!("ps::handle-pagerequest-message::slrusegment");
    1530            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1531              :                 (
    1532            0 :                     vec![
    1533            0 :                         self.handle_get_slru_segment_request(&shard, &req, &ctx)
    1534            0 :                             .instrument(span.clone())
    1535            0 :                             .await
    1536            0 :                             .map(|msg| (msg, timer))
    1537            0 :                             .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
    1538            0 :                     ],
    1539            0 :                     span,
    1540              :                 )
    1541              :             }
    1542              :             #[cfg(feature = "testing")]
    1543              :             BatchedFeMessage::Test {
    1544            0 :                 span,
    1545            0 :                 shard,
    1546            0 :                 requests,
    1547            0 :             } => {
    1548            0 :                 fail::fail_point!("ps::handle-pagerequest-message::test");
    1549            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1550              :                 (
    1551              :                     {
    1552            0 :                         let npages = requests.len();
    1553            0 :                         trace!(npages, "handling getpage request");
    1554            0 :                         let res = self
    1555            0 :                             .handle_test_request_batch(&shard, requests, &ctx)
    1556            0 :                             .instrument(span.clone())
    1557            0 :                             .await;
    1558            0 :                         assert_eq!(res.len(), npages);
    1559            0 :                         res
    1560            0 :                     },
    1561            0 :                     span,
    1562              :                 )
    1563              :             }
    1564            0 :             BatchedFeMessage::RespondError { span, error } => {
    1565            0 :                 // We've already decided to respond with an error, so we don't need to
    1566            0 :                 // call the handler.
    1567            0 :                 (vec![Err(error)], span)
    1568              :             }
    1569              :         })
    1570            0 :     }
    1571              : 
    1572              :     /// Pagestream sub-protocol handler.
    1573              :     ///
    1574              :     /// It is a simple request-response protocol inside a COPYBOTH session.
    1575              :     ///
    1576              :     /// # Coding Discipline
    1577              :     ///
    1578              :     /// Coding discipline within this function: all interaction with the `pgb` connection
    1579              :     /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
    1580              :     /// This is so that we can shutdown page_service quickly.
    1581              :     #[instrument(skip_all)]
    1582              :     async fn handle_pagerequests<IO>(
    1583              :         &mut self,
    1584              :         pgb: &mut PostgresBackend<IO>,
    1585              :         tenant_id: TenantId,
    1586              :         timeline_id: TimelineId,
    1587              :         protocol_version: PagestreamProtocolVersion,
    1588              :         ctx: RequestContext,
    1589              :     ) -> Result<(), QueryError>
    1590              :     where
    1591              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1592              :     {
    1593              :         debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    1594              : 
    1595              :         // switch client to COPYBOTH
    1596              :         pgb.write_message_noflush(&BeMessage::CopyBothResponse)?;
    1597              :         tokio::select! {
    1598              :             biased;
    1599              :             _ = self.cancel.cancelled() => {
    1600              :                 return Err(QueryError::Shutdown)
    1601              :             }
    1602              :             res = pgb.flush() => {
    1603              :                 res?;
    1604              :             }
    1605              :         }
    1606              : 
    1607              :         let io_concurrency = IoConcurrency::spawn_from_conf(
    1608              :             self.conf,
    1609              :             match self.gate_guard.try_clone() {
    1610              :                 Ok(guard) => guard,
    1611              :                 Err(_) => {
    1612              :                     info!("shutdown request received in page handler");
    1613              :                     return Err(QueryError::Shutdown);
    1614              :                 }
    1615              :             },
    1616              :         );
    1617              : 
    1618              :         let pgb_reader = pgb
    1619              :             .split()
    1620              :             .context("implementation error: split pgb into reader and writer")?;
    1621              : 
    1622              :         let timeline_handles = self
    1623              :             .timeline_handles
    1624              :             .take()
    1625              :             .expect("implementation error: timeline_handles should not be locked");
    1626              : 
    1627              :         let request_span = info_span!("request");
    1628              :         let ((pgb_reader, timeline_handles), result) = match self.pipelining_config.clone() {
    1629              :             PageServicePipeliningConfig::Pipelined(pipelining_config) => {
    1630              :                 self.handle_pagerequests_pipelined(
    1631              :                     pgb,
    1632              :                     pgb_reader,
    1633              :                     tenant_id,
    1634              :                     timeline_id,
    1635              :                     timeline_handles,
    1636              :                     request_span,
    1637              :                     pipelining_config,
    1638              :                     protocol_version,
    1639              :                     io_concurrency,
    1640              :                     &ctx,
    1641              :                 )
    1642              :                 .await
    1643              :             }
    1644              :             PageServicePipeliningConfig::Serial => {
    1645              :                 self.handle_pagerequests_serial(
    1646              :                     pgb,
    1647              :                     pgb_reader,
    1648              :                     tenant_id,
    1649              :                     timeline_id,
    1650              :                     timeline_handles,
    1651              :                     request_span,
    1652              :                     protocol_version,
    1653              :                     io_concurrency,
    1654              :                     &ctx,
    1655              :                 )
    1656              :                 .await
    1657              :             }
    1658              :         };
    1659              : 
    1660              :         debug!("pagestream subprotocol shut down cleanly");
    1661              : 
    1662              :         pgb.unsplit(pgb_reader)
    1663              :             .context("implementation error: unsplit pgb")?;
    1664              : 
    1665              :         let replaced = self.timeline_handles.replace(timeline_handles);
    1666              :         assert!(replaced.is_none());
    1667              : 
    1668              :         result
    1669              :     }
    1670              : 
    1671              :     #[allow(clippy::too_many_arguments)]
    1672            0 :     async fn handle_pagerequests_serial<IO>(
    1673            0 :         &mut self,
    1674            0 :         pgb_writer: &mut PostgresBackend<IO>,
    1675            0 :         mut pgb_reader: PostgresBackendReader<IO>,
    1676            0 :         tenant_id: TenantId,
    1677            0 :         timeline_id: TimelineId,
    1678            0 :         mut timeline_handles: TimelineHandles,
    1679            0 :         request_span: Span,
    1680            0 :         protocol_version: PagestreamProtocolVersion,
    1681            0 :         io_concurrency: IoConcurrency,
    1682            0 :         ctx: &RequestContext,
    1683            0 :     ) -> (
    1684            0 :         (PostgresBackendReader<IO>, TimelineHandles),
    1685            0 :         Result<(), QueryError>,
    1686            0 :     )
    1687            0 :     where
    1688            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1689            0 :     {
    1690            0 :         let cancel = self.cancel.clone();
    1691              : 
    1692            0 :         let err = loop {
    1693            0 :             let msg = Self::pagestream_read_message(
    1694            0 :                 &mut pgb_reader,
    1695            0 :                 tenant_id,
    1696            0 :                 timeline_id,
    1697            0 :                 &mut timeline_handles,
    1698            0 :                 &self.perf_span_fields,
    1699            0 :                 &cancel,
    1700            0 :                 ctx,
    1701            0 :                 protocol_version,
    1702            0 :                 request_span.clone(),
    1703            0 :             )
    1704            0 :             .await;
    1705            0 :             let msg = match msg {
    1706            0 :                 Ok(msg) => msg,
    1707            0 :                 Err(e) => break e,
    1708              :             };
    1709            0 :             let msg = match msg {
    1710            0 :                 Some(msg) => msg,
    1711              :                 None => {
    1712            0 :                     debug!("pagestream subprotocol end observed");
    1713            0 :                     return ((pgb_reader, timeline_handles), Ok(()));
    1714              :                 }
    1715              :             };
    1716              : 
    1717            0 :             let result = self
    1718            0 :                 .pagesteam_handle_batched_message(
    1719            0 :                     pgb_writer,
    1720            0 :                     msg,
    1721            0 :                     io_concurrency.clone(),
    1722            0 :                     &cancel,
    1723            0 :                     protocol_version,
    1724            0 :                     ctx,
    1725            0 :                 )
    1726            0 :                 .await;
    1727            0 :             match result {
    1728            0 :                 Ok(()) => {}
    1729            0 :                 Err(e) => break e,
    1730              :             }
    1731              :         };
    1732            0 :         ((pgb_reader, timeline_handles), Err(err))
    1733            0 :     }
    1734              : 
    1735              :     /// # Cancel-Safety
    1736              :     ///
    1737              :     /// May leak tokio tasks if not polled to completion.
    1738              :     #[allow(clippy::too_many_arguments)]
    1739            0 :     async fn handle_pagerequests_pipelined<IO>(
    1740            0 :         &mut self,
    1741            0 :         pgb_writer: &mut PostgresBackend<IO>,
    1742            0 :         pgb_reader: PostgresBackendReader<IO>,
    1743            0 :         tenant_id: TenantId,
    1744            0 :         timeline_id: TimelineId,
    1745            0 :         mut timeline_handles: TimelineHandles,
    1746            0 :         request_span: Span,
    1747            0 :         pipelining_config: PageServicePipeliningConfigPipelined,
    1748            0 :         protocol_version: PagestreamProtocolVersion,
    1749            0 :         io_concurrency: IoConcurrency,
    1750            0 :         ctx: &RequestContext,
    1751            0 :     ) -> (
    1752            0 :         (PostgresBackendReader<IO>, TimelineHandles),
    1753            0 :         Result<(), QueryError>,
    1754            0 :     )
    1755            0 :     where
    1756            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1757            0 :     {
    1758            0 :         //
    1759            0 :         // Pipelined pagestream handling consists of
    1760            0 :         // - a Batcher that reads requests off the wire and
    1761            0 :         //   and batches them if possible,
    1762            0 :         // - an Executor that processes the batched requests.
    1763            0 :         //
    1764            0 :         // The batch is built up inside an `spsc_fold` channel,
    1765            0 :         // shared betwen Batcher (Sender) and Executor (Receiver).
    1766            0 :         //
    1767            0 :         // The Batcher continously folds client requests into the batch,
    1768            0 :         // while the Executor can at any time take out what's in the batch
    1769            0 :         // in order to process it.
    1770            0 :         // This means the next batch builds up while the Executor
    1771            0 :         // executes the last batch.
    1772            0 :         //
    1773            0 :         // CANCELLATION
    1774            0 :         //
    1775            0 :         // We run both Batcher and Executor futures to completion before
    1776            0 :         // returning from this function.
    1777            0 :         //
    1778            0 :         // If Executor exits first, it signals cancellation to the Batcher
    1779            0 :         // via a CancellationToken that is child of `self.cancel`.
    1780            0 :         // If Batcher exits first, it signals cancellation to the Executor
    1781            0 :         // by dropping the spsc_fold channel Sender.
    1782            0 :         //
    1783            0 :         // CLEAN SHUTDOWN
    1784            0 :         //
    1785            0 :         // Clean shutdown means that the client ends the COPYBOTH session.
    1786            0 :         // In response to such a client message, the Batcher exits.
    1787            0 :         // The Executor continues to run, draining the spsc_fold channel.
    1788            0 :         // Once drained, the spsc_fold recv will fail with a distinct error
    1789            0 :         // indicating that the sender disconnected.
    1790            0 :         // The Executor exits with Ok(()) in response to that error.
    1791            0 :         //
    1792            0 :         // Server initiated shutdown is not clean shutdown, but instead
    1793            0 :         // is an error Err(QueryError::Shutdown) that is propagated through
    1794            0 :         // error propagation.
    1795            0 :         //
    1796            0 :         // ERROR PROPAGATION
    1797            0 :         //
    1798            0 :         // When the Batcher encounter an error, it sends it as a value
    1799            0 :         // through the spsc_fold channel and exits afterwards.
    1800            0 :         // When the Executor observes such an error in the channel,
    1801            0 :         // it exits returning that error value.
    1802            0 :         //
    1803            0 :         // This design ensures that the Executor stage will still process
    1804            0 :         // the batch that was in flight when the Batcher encountered an error,
    1805            0 :         // thereby beahving identical to a serial implementation.
    1806            0 : 
    1807            0 :         let PageServicePipeliningConfigPipelined {
    1808            0 :             max_batch_size,
    1809            0 :             execution,
    1810            0 :             batching: batching_strategy,
    1811            0 :         } = pipelining_config;
    1812              : 
    1813              :         // Macro to _define_ a pipeline stage.
    1814              :         macro_rules! pipeline_stage {
    1815              :             ($name:literal, $cancel:expr, $make_fut:expr) => {{
    1816              :                 let cancel: CancellationToken = $cancel;
    1817              :                 let stage_fut = $make_fut(cancel.clone());
    1818            0 :                 async move {
    1819            0 :                     scopeguard::defer! {
    1820            0 :                         debug!("exiting");
    1821            0 :                     }
    1822            0 :                     timed_after_cancellation(stage_fut, $name, Duration::from_millis(100), &cancel)
    1823            0 :                         .await
    1824            0 :                 }
    1825              :                 .instrument(tracing::info_span!($name))
    1826              :             }};
    1827              :         }
    1828              : 
    1829              :         //
    1830              :         // Batcher
    1831              :         //
    1832              : 
    1833            0 :         let perf_span_fields = self.perf_span_fields.clone();
    1834            0 : 
    1835            0 :         let cancel_batcher = self.cancel.child_token();
    1836            0 :         let (mut batch_tx, mut batch_rx) = spsc_fold::channel();
    1837            0 :         let batcher = pipeline_stage!("batcher", cancel_batcher.clone(), move |cancel_batcher| {
    1838            0 :             let ctx = ctx.attached_child();
    1839            0 :             async move {
    1840            0 :                 let mut pgb_reader = pgb_reader;
    1841            0 :                 let mut exit = false;
    1842            0 :                 while !exit {
    1843            0 :                     let read_res = Self::pagestream_read_message(
    1844            0 :                         &mut pgb_reader,
    1845            0 :                         tenant_id,
    1846            0 :                         timeline_id,
    1847            0 :                         &mut timeline_handles,
    1848            0 :                         &perf_span_fields,
    1849            0 :                         &cancel_batcher,
    1850            0 :                         &ctx,
    1851            0 :                         protocol_version,
    1852            0 :                         request_span.clone(),
    1853            0 :                     )
    1854            0 :                     .await;
    1855            0 :                     let Some(read_res) = read_res.transpose() else {
    1856            0 :                         debug!("client-initiated shutdown");
    1857            0 :                         break;
    1858              :                     };
    1859            0 :                     exit |= read_res.is_err();
    1860            0 :                     let could_send = batch_tx
    1861            0 :                         .send(read_res, |batch, res| {
    1862            0 :                             Self::pagestream_do_batch(batching_strategy, max_batch_size, batch, res)
    1863            0 :                         })
    1864            0 :                         .await;
    1865            0 :                     exit |= could_send.is_err();
    1866              :                 }
    1867            0 :                 (pgb_reader, timeline_handles)
    1868            0 :             }
    1869            0 :         });
    1870              : 
    1871              :         //
    1872              :         // Executor
    1873              :         //
    1874              : 
    1875            0 :         let executor = pipeline_stage!("executor", self.cancel.clone(), move |cancel| {
    1876            0 :             let ctx = ctx.attached_child();
    1877            0 :             async move {
    1878            0 :                 let _cancel_batcher = cancel_batcher.drop_guard();
    1879              :                 loop {
    1880            0 :                     let maybe_batch = batch_rx.recv().await;
    1881            0 :                     let batch = match maybe_batch {
    1882            0 :                         Ok(batch) => batch,
    1883              :                         Err(spsc_fold::RecvError::SenderGone) => {
    1884            0 :                             debug!("upstream gone");
    1885            0 :                             return Ok(());
    1886              :                         }
    1887              :                     };
    1888            0 :                     let batch = match batch {
    1889            0 :                         Ok(batch) => batch,
    1890            0 :                         Err(e) => {
    1891            0 :                             return Err(e);
    1892              :                         }
    1893              :                     };
    1894            0 :                     self.pagesteam_handle_batched_message(
    1895            0 :                         pgb_writer,
    1896            0 :                         batch,
    1897            0 :                         io_concurrency.clone(),
    1898            0 :                         &cancel,
    1899            0 :                         protocol_version,
    1900            0 :                         &ctx,
    1901            0 :                     )
    1902            0 :                     .await?;
    1903              :                 }
    1904            0 :             }
    1905            0 :         });
    1906              : 
    1907              :         //
    1908              :         // Execute the stages.
    1909              :         //
    1910              : 
    1911            0 :         match execution {
    1912              :             PageServiceProtocolPipelinedExecutionStrategy::ConcurrentFutures => {
    1913            0 :                 tokio::join!(batcher, executor)
    1914              :             }
    1915              :             PageServiceProtocolPipelinedExecutionStrategy::Tasks => {
    1916              :                 // These tasks are not tracked anywhere.
    1917            0 :                 let read_messages_task = tokio::spawn(batcher);
    1918            0 :                 let (read_messages_task_res, executor_res_) =
    1919            0 :                     tokio::join!(read_messages_task, executor,);
    1920            0 :                 (
    1921            0 :                     read_messages_task_res.expect("propagated panic from read_messages"),
    1922            0 :                     executor_res_,
    1923            0 :                 )
    1924              :             }
    1925              :         }
    1926            0 :     }
    1927              : 
    1928              :     /// Helper function to handle the LSN from client request.
    1929              :     ///
    1930              :     /// Each GetPage (and Exists and Nblocks) request includes information about
    1931              :     /// which version of the page is being requested. The primary compute node
    1932              :     /// will always request the latest page version, by setting 'request_lsn' to
    1933              :     /// the last inserted or flushed WAL position, while a standby will request
    1934              :     /// a version at the LSN that it's currently caught up to.
    1935              :     ///
    1936              :     /// In either case, if the page server hasn't received the WAL up to the
    1937              :     /// requested LSN yet, we will wait for it to arrive. The return value is
    1938              :     /// the LSN that should be used to look up the page versions.
    1939              :     ///
    1940              :     /// In addition to the request LSN, each request carries another LSN,
    1941              :     /// 'not_modified_since', which is a hint to the pageserver that the client
    1942              :     /// knows that the page has not been modified between 'not_modified_since'
    1943              :     /// and the request LSN. This allows skipping the wait, as long as the WAL
    1944              :     /// up to 'not_modified_since' has arrived. If the client doesn't have any
    1945              :     /// information about when the page was modified, it will use
    1946              :     /// not_modified_since == lsn. If the client lies and sends a too low
    1947              :     /// not_modified_hint such that there are in fact later page versions, the
    1948              :     /// behavior is undefined: the pageserver may return any of the page versions
    1949              :     /// or an error.
    1950            0 :     async fn wait_or_get_last_lsn(
    1951            0 :         timeline: &Timeline,
    1952            0 :         request_lsn: Lsn,
    1953            0 :         not_modified_since: Lsn,
    1954            0 :         latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
    1955            0 :         ctx: &RequestContext,
    1956            0 :     ) -> Result<Lsn, PageStreamError> {
    1957            0 :         let last_record_lsn = timeline.get_last_record_lsn();
    1958            0 :         let effective_request_lsn = Self::effective_request_lsn(
    1959            0 :             timeline,
    1960            0 :             last_record_lsn,
    1961            0 :             request_lsn,
    1962            0 :             not_modified_since,
    1963            0 :             latest_gc_cutoff_lsn,
    1964            0 :         )?;
    1965              : 
    1966            0 :         if effective_request_lsn > last_record_lsn {
    1967            0 :             timeline
    1968            0 :                 .wait_lsn(
    1969            0 :                     not_modified_since,
    1970            0 :                     crate::tenant::timeline::WaitLsnWaiter::PageService,
    1971            0 :                     timeline::WaitLsnTimeout::Default,
    1972            0 :                     ctx,
    1973            0 :                 )
    1974            0 :                 .await?;
    1975              : 
    1976              :             // Since we waited for 'effective_request_lsn' to arrive, that is now the last
    1977              :             // record LSN. (Or close enough for our purposes; the last-record LSN can
    1978              :             // advance immediately after we return anyway)
    1979            0 :         }
    1980              : 
    1981            0 :         Ok(effective_request_lsn)
    1982            0 :     }
    1983              : 
    1984            0 :     fn effective_request_lsn(
    1985            0 :         timeline: &Timeline,
    1986            0 :         last_record_lsn: Lsn,
    1987            0 :         request_lsn: Lsn,
    1988            0 :         not_modified_since: Lsn,
    1989            0 :         latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
    1990            0 :     ) -> Result<Lsn, PageStreamError> {
    1991            0 :         // Sanity check the request
    1992            0 :         if request_lsn < not_modified_since {
    1993            0 :             return Err(PageStreamError::BadRequest(
    1994            0 :                 format!(
    1995            0 :                     "invalid request with request LSN {} and not_modified_since {}",
    1996            0 :                     request_lsn, not_modified_since,
    1997            0 :                 )
    1998            0 :                 .into(),
    1999            0 :             ));
    2000            0 :         }
    2001            0 : 
    2002            0 :         // Check explicitly for INVALID just to get a less scary error message if the request is obviously bogus
    2003            0 :         if request_lsn == Lsn::INVALID {
    2004            0 :             return Err(PageStreamError::BadRequest(
    2005            0 :                 "invalid LSN(0) in request".into(),
    2006            0 :             ));
    2007            0 :         }
    2008            0 : 
    2009            0 :         // Clients should only read from recent LSNs on their timeline, or from locations holding an LSN lease.
    2010            0 :         //
    2011            0 :         // We may have older data available, but we make a best effort to detect this case and return an error,
    2012            0 :         // to distinguish a misbehaving client (asking for old LSN) from a storage issue (data missing at a legitimate LSN).
    2013            0 :         if request_lsn < **latest_gc_cutoff_lsn && !timeline.is_gc_blocked_by_lsn_lease_deadline() {
    2014            0 :             let gc_info = &timeline.gc_info.read().unwrap();
    2015            0 :             if !gc_info.lsn_covered_by_lease(request_lsn) {
    2016            0 :                 return Err(
    2017            0 :                     PageStreamError::BadRequest(format!(
    2018            0 :                         "tried to request a page version that was garbage collected. requested at {} gc cutoff {}",
    2019            0 :                         request_lsn, **latest_gc_cutoff_lsn
    2020            0 :                     ).into())
    2021            0 :                 );
    2022            0 :             }
    2023            0 :         }
    2024              : 
    2025            0 :         if not_modified_since > last_record_lsn {
    2026            0 :             Ok(not_modified_since)
    2027              :         } else {
    2028              :             // It might be better to use max(not_modified_since, latest_gc_cutoff_lsn)
    2029              :             // here instead. That would give the same result, since we know that there
    2030              :             // haven't been any modifications since 'not_modified_since'. Using an older
    2031              :             // LSN might be faster, because that could allow skipping recent layers when
    2032              :             // finding the page. However, we have historically used 'last_record_lsn', so
    2033              :             // stick to that for now.
    2034            0 :             Ok(std::cmp::min(last_record_lsn, request_lsn))
    2035              :         }
    2036            0 :     }
    2037              : 
    2038              :     /// Handles the lsn lease request.
    2039              :     /// If a lease cannot be obtained, the client will receive NULL.
    2040              :     #[instrument(skip_all, fields(shard_id, %lsn))]
    2041              :     async fn handle_make_lsn_lease<IO>(
    2042              :         &mut self,
    2043              :         pgb: &mut PostgresBackend<IO>,
    2044              :         tenant_shard_id: TenantShardId,
    2045              :         timeline_id: TimelineId,
    2046              :         lsn: Lsn,
    2047              :         ctx: &RequestContext,
    2048              :     ) -> Result<(), QueryError>
    2049              :     where
    2050              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
    2051              :     {
    2052              :         let timeline = self
    2053              :             .timeline_handles
    2054              :             .as_mut()
    2055              :             .unwrap()
    2056              :             .get(
    2057              :                 tenant_shard_id.tenant_id,
    2058              :                 timeline_id,
    2059              :                 ShardSelector::Known(tenant_shard_id.to_index()),
    2060              :             )
    2061              :             .await?;
    2062              :         set_tracing_field_shard_id(&timeline);
    2063              : 
    2064              :         let lease = timeline
    2065              :             .renew_lsn_lease(lsn, timeline.get_lsn_lease_length(), ctx)
    2066            0 :             .inspect_err(|e| {
    2067            0 :                 warn!("{e}");
    2068            0 :             })
    2069              :             .ok();
    2070            0 :         let valid_until_str = lease.map(|l| {
    2071            0 :             l.valid_until
    2072            0 :                 .duration_since(SystemTime::UNIX_EPOCH)
    2073            0 :                 .expect("valid_until is earlier than UNIX_EPOCH")
    2074            0 :                 .as_millis()
    2075            0 :                 .to_string()
    2076            0 :         });
    2077              : 
    2078              :         info!(
    2079              :             "acquired lease for {} until {}",
    2080              :             lsn,
    2081              :             valid_until_str.as_deref().unwrap_or("<unknown>")
    2082              :         );
    2083              : 
    2084            0 :         let bytes = valid_until_str.as_ref().map(|x| x.as_bytes());
    2085              : 
    2086              :         pgb.write_message_noflush(&BeMessage::RowDescription(&[RowDescriptor::text_col(
    2087              :             b"valid_until",
    2088              :         )]))?
    2089              :         .write_message_noflush(&BeMessage::DataRow(&[bytes]))?;
    2090              : 
    2091              :         Ok(())
    2092              :     }
    2093              : 
    2094              :     #[instrument(skip_all, fields(shard_id))]
    2095              :     async fn handle_get_rel_exists_request(
    2096              :         &mut self,
    2097              :         timeline: &Timeline,
    2098              :         req: &PagestreamExistsRequest,
    2099              :         ctx: &RequestContext,
    2100              :     ) -> Result<PagestreamBeMessage, PageStreamError> {
    2101              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2102              :         let lsn = Self::wait_or_get_last_lsn(
    2103              :             timeline,
    2104              :             req.hdr.request_lsn,
    2105              :             req.hdr.not_modified_since,
    2106              :             &latest_gc_cutoff_lsn,
    2107              :             ctx,
    2108              :         )
    2109              :         .await?;
    2110              : 
    2111              :         let exists = timeline
    2112              :             .get_rel_exists(req.rel, Version::Lsn(lsn), ctx)
    2113              :             .await?;
    2114              : 
    2115              :         Ok(PagestreamBeMessage::Exists(PagestreamExistsResponse {
    2116              :             req: *req,
    2117              :             exists,
    2118              :         }))
    2119              :     }
    2120              : 
    2121              :     #[instrument(skip_all, fields(shard_id))]
    2122              :     async fn handle_get_nblocks_request(
    2123              :         &mut self,
    2124              :         timeline: &Timeline,
    2125              :         req: &PagestreamNblocksRequest,
    2126              :         ctx: &RequestContext,
    2127              :     ) -> Result<PagestreamBeMessage, PageStreamError> {
    2128              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2129              :         let lsn = Self::wait_or_get_last_lsn(
    2130              :             timeline,
    2131              :             req.hdr.request_lsn,
    2132              :             req.hdr.not_modified_since,
    2133              :             &latest_gc_cutoff_lsn,
    2134              :             ctx,
    2135              :         )
    2136              :         .await?;
    2137              : 
    2138              :         let n_blocks = timeline
    2139              :             .get_rel_size(req.rel, Version::Lsn(lsn), ctx)
    2140              :             .await?;
    2141              : 
    2142              :         Ok(PagestreamBeMessage::Nblocks(PagestreamNblocksResponse {
    2143              :             req: *req,
    2144              :             n_blocks,
    2145              :         }))
    2146              :     }
    2147              : 
    2148              :     #[instrument(skip_all, fields(shard_id))]
    2149              :     async fn handle_db_size_request(
    2150              :         &mut self,
    2151              :         timeline: &Timeline,
    2152              :         req: &PagestreamDbSizeRequest,
    2153              :         ctx: &RequestContext,
    2154              :     ) -> Result<PagestreamBeMessage, PageStreamError> {
    2155              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2156              :         let lsn = Self::wait_or_get_last_lsn(
    2157              :             timeline,
    2158              :             req.hdr.request_lsn,
    2159              :             req.hdr.not_modified_since,
    2160              :             &latest_gc_cutoff_lsn,
    2161              :             ctx,
    2162              :         )
    2163              :         .await?;
    2164              : 
    2165              :         let total_blocks = timeline
    2166              :             .get_db_size(DEFAULTTABLESPACE_OID, req.dbnode, Version::Lsn(lsn), ctx)
    2167              :             .await?;
    2168              :         let db_size = total_blocks as i64 * BLCKSZ as i64;
    2169              : 
    2170              :         Ok(PagestreamBeMessage::DbSize(PagestreamDbSizeResponse {
    2171              :             req: *req,
    2172              :             db_size,
    2173              :         }))
    2174              :     }
    2175              : 
    2176              :     #[instrument(skip_all)]
    2177              :     async fn handle_get_page_at_lsn_request_batched(
    2178              :         &mut self,
    2179              :         timeline: &Timeline,
    2180              :         requests: smallvec::SmallVec<[BatchedGetPageRequest; 1]>,
    2181              :         io_concurrency: IoConcurrency,
    2182              :         batch_break_reason: GetPageBatchBreakReason,
    2183              :         ctx: &RequestContext,
    2184              :     ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer), BatchedPageStreamError>> {
    2185              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2186              : 
    2187              :         timeline
    2188              :             .query_metrics
    2189              :             .observe_getpage_batch_start(requests.len(), batch_break_reason);
    2190              : 
    2191              :         // If a page trace is running, submit an event for this request.
    2192              :         if let Some(page_trace) = timeline.page_trace.load().as_ref() {
    2193              :             let time = SystemTime::now();
    2194              :             for batch in &requests {
    2195              :                 let key = rel_block_to_key(batch.req.rel, batch.req.blkno).to_compact();
    2196              :                 // Ignore error (trace buffer may be full or tracer may have disconnected).
    2197              :                 _ = page_trace.try_send(PageTraceEvent {
    2198              :                     key,
    2199              :                     effective_lsn: batch.effective_request_lsn,
    2200              :                     time,
    2201              :                 });
    2202              :             }
    2203              :         }
    2204              : 
    2205              :         // If any request in the batch needs to wait for LSN, then do so now.
    2206              :         let mut perf_instrument = false;
    2207              :         let max_effective_lsn = requests
    2208              :             .iter()
    2209            0 :             .map(|req| {
    2210            0 :                 if req.ctx.has_perf_span() {
    2211            0 :                     perf_instrument = true;
    2212            0 :                 }
    2213              : 
    2214            0 :                 req.effective_request_lsn
    2215            0 :             })
    2216              :             .max()
    2217              :             .expect("batch is never empty");
    2218              : 
    2219              :         let ctx = match perf_instrument {
    2220              :             true => RequestContextBuilder::from(ctx)
    2221            0 :                 .root_perf_span(|| {
    2222            0 :                     info_span!(
    2223              :                         target: PERF_TRACE_TARGET,
    2224              :                         "GET_VECTORED",
    2225              :                         tenant_id = %timeline.tenant_shard_id.tenant_id,
    2226              :                         timeline_id = %timeline.timeline_id,
    2227            0 :                         shard = %timeline.tenant_shard_id.shard_slug(),
    2228              :                         %max_effective_lsn
    2229              :                     )
    2230            0 :                 })
    2231              :                 .attached_child(),
    2232              :             false => ctx.attached_child(),
    2233              :         };
    2234              : 
    2235              :         let last_record_lsn = timeline.get_last_record_lsn();
    2236              :         if max_effective_lsn > last_record_lsn {
    2237              :             if let Err(e) = timeline
    2238              :                 .wait_lsn(
    2239              :                     max_effective_lsn,
    2240              :                     crate::tenant::timeline::WaitLsnWaiter::PageService,
    2241              :                     timeline::WaitLsnTimeout::Default,
    2242              :                     &ctx,
    2243              :                 )
    2244            0 :                 .maybe_perf_instrument(&ctx, |current_perf_span| {
    2245            0 :                     info_span!(
    2246              :                         target: PERF_TRACE_TARGET,
    2247            0 :                         parent: current_perf_span,
    2248              :                         "WAIT_LSN",
    2249              :                     )
    2250            0 :                 })
    2251              :                 .await
    2252              :             {
    2253            0 :                 return Vec::from_iter(requests.into_iter().map(|req| {
    2254            0 :                     Err(BatchedPageStreamError {
    2255            0 :                         err: PageStreamError::from(e.clone()),
    2256            0 :                         req: req.req.hdr,
    2257            0 :                     })
    2258            0 :                 }));
    2259              :             }
    2260              :         }
    2261              : 
    2262              :         let results = timeline
    2263              :             .get_rel_page_at_lsn_batched(
    2264            0 :                 requests.iter().map(|p| {
    2265            0 :                     (
    2266            0 :                         &p.req.rel,
    2267            0 :                         &p.req.blkno,
    2268            0 :                         p.effective_request_lsn,
    2269            0 :                         p.ctx.attached_child(),
    2270            0 :                     )
    2271            0 :                 }),
    2272              :                 io_concurrency,
    2273              :                 &ctx,
    2274              :             )
    2275              :             .await;
    2276              :         assert_eq!(results.len(), requests.len());
    2277              : 
    2278              :         // TODO: avoid creating the new Vec here
    2279              :         Vec::from_iter(
    2280              :             requests
    2281              :                 .into_iter()
    2282              :                 .zip(results.into_iter())
    2283            0 :                 .map(|(req, res)| {
    2284            0 :                     res.map(|page| {
    2285            0 :                         (
    2286            0 :                             PagestreamBeMessage::GetPage(models::PagestreamGetPageResponse {
    2287            0 :                                 req: req.req,
    2288            0 :                                 page,
    2289            0 :                             }),
    2290            0 :                             req.timer,
    2291            0 :                         )
    2292            0 :                     })
    2293            0 :                     .map_err(|e| BatchedPageStreamError {
    2294            0 :                         err: PageStreamError::from(e),
    2295            0 :                         req: req.req.hdr,
    2296            0 :                     })
    2297            0 :                 }),
    2298              :         )
    2299              :     }
    2300              : 
    2301              :     #[instrument(skip_all, fields(shard_id))]
    2302              :     async fn handle_get_slru_segment_request(
    2303              :         &mut self,
    2304              :         timeline: &Timeline,
    2305              :         req: &PagestreamGetSlruSegmentRequest,
    2306              :         ctx: &RequestContext,
    2307              :     ) -> Result<PagestreamBeMessage, PageStreamError> {
    2308              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2309              :         let lsn = Self::wait_or_get_last_lsn(
    2310              :             timeline,
    2311              :             req.hdr.request_lsn,
    2312              :             req.hdr.not_modified_since,
    2313              :             &latest_gc_cutoff_lsn,
    2314              :             ctx,
    2315              :         )
    2316              :         .await?;
    2317              : 
    2318              :         let kind = SlruKind::from_repr(req.kind)
    2319              :             .ok_or(PageStreamError::BadRequest("invalid SLRU kind".into()))?;
    2320              :         let segment = timeline.get_slru_segment(kind, req.segno, lsn, ctx).await?;
    2321              : 
    2322              :         Ok(PagestreamBeMessage::GetSlruSegment(
    2323              :             PagestreamGetSlruSegmentResponse { req: *req, segment },
    2324              :         ))
    2325              :     }
    2326              : 
    2327              :     // NB: this impl mimics what we do for batched getpage requests.
    2328              :     #[cfg(feature = "testing")]
    2329              :     #[instrument(skip_all, fields(shard_id))]
    2330              :     async fn handle_test_request_batch(
    2331              :         &mut self,
    2332              :         timeline: &Timeline,
    2333              :         requests: Vec<BatchedTestRequest>,
    2334              :         _ctx: &RequestContext,
    2335              :     ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer), BatchedPageStreamError>> {
    2336              :         // real requests would do something with the timeline
    2337              :         let mut results = Vec::with_capacity(requests.len());
    2338              :         for _req in requests.iter() {
    2339              :             tokio::task::yield_now().await;
    2340              : 
    2341              :             results.push({
    2342              :                 if timeline.cancel.is_cancelled() {
    2343              :                     Err(PageReconstructError::Cancelled)
    2344              :                 } else {
    2345              :                     Ok(())
    2346              :                 }
    2347              :             });
    2348              :         }
    2349              : 
    2350              :         // TODO: avoid creating the new Vec here
    2351              :         Vec::from_iter(
    2352              :             requests
    2353              :                 .into_iter()
    2354              :                 .zip(results.into_iter())
    2355            0 :                 .map(|(req, res)| {
    2356            0 :                     res.map(|()| {
    2357            0 :                         (
    2358            0 :                             PagestreamBeMessage::Test(models::PagestreamTestResponse {
    2359            0 :                                 req: req.req.clone(),
    2360            0 :                             }),
    2361            0 :                             req.timer,
    2362            0 :                         )
    2363            0 :                     })
    2364            0 :                     .map_err(|e| BatchedPageStreamError {
    2365            0 :                         err: PageStreamError::from(e),
    2366            0 :                         req: req.req.hdr,
    2367            0 :                     })
    2368            0 :                 }),
    2369              :         )
    2370              :     }
    2371              : 
    2372              :     /// Note on "fullbackup":
    2373              :     /// Full basebackups should only be used for debugging purposes.
    2374              :     /// Originally, it was introduced to enable breaking storage format changes,
    2375              :     /// but that is not applicable anymore.
    2376              :     ///
    2377              :     /// # Coding Discipline
    2378              :     ///
    2379              :     /// Coding discipline within this function: all interaction with the `pgb` connection
    2380              :     /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
    2381              :     /// This is so that we can shutdown page_service quickly.
    2382              :     ///
    2383              :     /// TODO: wrap the pgb that we pass to the basebackup handler so that it's sensitive
    2384              :     /// to connection cancellation.
    2385              :     #[allow(clippy::too_many_arguments)]
    2386              :     #[instrument(skip_all, fields(shard_id, ?lsn, ?prev_lsn, %full_backup))]
    2387              :     async fn handle_basebackup_request<IO>(
    2388              :         &mut self,
    2389              :         pgb: &mut PostgresBackend<IO>,
    2390              :         tenant_id: TenantId,
    2391              :         timeline_id: TimelineId,
    2392              :         lsn: Option<Lsn>,
    2393              :         prev_lsn: Option<Lsn>,
    2394              :         full_backup: bool,
    2395              :         gzip: bool,
    2396              :         replica: bool,
    2397              :         ctx: &RequestContext,
    2398              :     ) -> Result<(), QueryError>
    2399              :     where
    2400              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
    2401              :     {
    2402            0 :         fn map_basebackup_error(err: BasebackupError) -> QueryError {
    2403            0 :             match err {
    2404              :                 // TODO: passthrough the error site to the final error message?
    2405            0 :                 BasebackupError::Client(e, _) => QueryError::Disconnected(ConnectionError::Io(e)),
    2406            0 :                 BasebackupError::Server(e) => QueryError::Other(e),
    2407            0 :                 BasebackupError::Shutdown => QueryError::Shutdown,
    2408              :             }
    2409            0 :         }
    2410              : 
    2411              :         let started = std::time::Instant::now();
    2412              : 
    2413              :         let timeline = self
    2414              :             .timeline_handles
    2415              :             .as_mut()
    2416              :             .unwrap()
    2417              :             .get(tenant_id, timeline_id, ShardSelector::Zero)
    2418              :             .await?;
    2419              :         set_tracing_field_shard_id(&timeline);
    2420              :         let ctx = ctx.with_scope_timeline(&timeline);
    2421              : 
    2422              :         if timeline.is_archived() == Some(true) {
    2423              :             tracing::info!(
    2424              :                 "timeline {tenant_id}/{timeline_id} is archived, but got basebackup request for it."
    2425              :             );
    2426              :             return Err(QueryError::NotFound("timeline is archived".into()));
    2427              :         }
    2428              : 
    2429              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2430              :         if let Some(lsn) = lsn {
    2431              :             // Backup was requested at a particular LSN. Wait for it to arrive.
    2432              :             info!("waiting for {}", lsn);
    2433              :             timeline
    2434              :                 .wait_lsn(
    2435              :                     lsn,
    2436              :                     crate::tenant::timeline::WaitLsnWaiter::PageService,
    2437              :                     crate::tenant::timeline::WaitLsnTimeout::Default,
    2438              :                     &ctx,
    2439              :                 )
    2440              :                 .await?;
    2441              :             timeline
    2442              :                 .check_lsn_is_in_scope(lsn, &latest_gc_cutoff_lsn)
    2443              :                 .context("invalid basebackup lsn")?;
    2444              :         }
    2445              : 
    2446              :         let lsn_awaited_after = started.elapsed();
    2447              : 
    2448              :         // switch client to COPYOUT
    2449              :         pgb.write_message_noflush(&BeMessage::CopyOutResponse)
    2450              :             .map_err(QueryError::Disconnected)?;
    2451              :         self.flush_cancellable(pgb, &self.cancel).await?;
    2452              : 
    2453              :         // Send a tarball of the latest layer on the timeline. Compress if not
    2454              :         // fullbackup. TODO Compress in that case too (tests need to be updated)
    2455              :         if full_backup {
    2456              :             let mut writer = pgb.copyout_writer();
    2457              :             basebackup::send_basebackup_tarball(
    2458              :                 &mut writer,
    2459              :                 &timeline,
    2460              :                 lsn,
    2461              :                 prev_lsn,
    2462              :                 full_backup,
    2463              :                 replica,
    2464              :                 &ctx,
    2465              :             )
    2466              :             .await
    2467              :             .map_err(map_basebackup_error)?;
    2468              :         } else {
    2469              :             let mut writer = BufWriter::new(pgb.copyout_writer());
    2470              :             if gzip {
    2471              :                 let mut encoder = GzipEncoder::with_quality(
    2472              :                     &mut writer,
    2473              :                     // NOTE using fast compression because it's on the critical path
    2474              :                     //      for compute startup. For an empty database, we get
    2475              :                     //      <100KB with this method. The Level::Best compression method
    2476              :                     //      gives us <20KB, but maybe we should add basebackup caching
    2477              :                     //      on compute shutdown first.
    2478              :                     async_compression::Level::Fastest,
    2479              :                 );
    2480              :                 basebackup::send_basebackup_tarball(
    2481              :                     &mut encoder,
    2482              :                     &timeline,
    2483              :                     lsn,
    2484              :                     prev_lsn,
    2485              :                     full_backup,
    2486              :                     replica,
    2487              :                     &ctx,
    2488              :                 )
    2489              :                 .await
    2490              :                 .map_err(map_basebackup_error)?;
    2491              :                 // shutdown the encoder to ensure the gzip footer is written
    2492              :                 encoder
    2493              :                     .shutdown()
    2494              :                     .await
    2495            0 :                     .map_err(|e| QueryError::Disconnected(ConnectionError::Io(e)))?;
    2496              :             } else {
    2497              :                 basebackup::send_basebackup_tarball(
    2498              :                     &mut writer,
    2499              :                     &timeline,
    2500              :                     lsn,
    2501              :                     prev_lsn,
    2502              :                     full_backup,
    2503              :                     replica,
    2504              :                     &ctx,
    2505              :                 )
    2506              :                 .await
    2507              :                 .map_err(map_basebackup_error)?;
    2508              :             }
    2509            0 :             writer.flush().await.map_err(|e| {
    2510            0 :                 map_basebackup_error(BasebackupError::Client(
    2511            0 :                     e,
    2512            0 :                     "handle_basebackup_request,flush",
    2513            0 :                 ))
    2514            0 :             })?;
    2515              :         }
    2516              : 
    2517              :         pgb.write_message_noflush(&BeMessage::CopyDone)
    2518              :             .map_err(QueryError::Disconnected)?;
    2519              :         self.flush_cancellable(pgb, &timeline.cancel).await?;
    2520              : 
    2521              :         let basebackup_after = started
    2522              :             .elapsed()
    2523              :             .checked_sub(lsn_awaited_after)
    2524              :             .unwrap_or(Duration::ZERO);
    2525              : 
    2526              :         info!(
    2527              :             lsn_await_millis = lsn_awaited_after.as_millis(),
    2528              :             basebackup_millis = basebackup_after.as_millis(),
    2529              :             "basebackup complete"
    2530              :         );
    2531              : 
    2532              :         Ok(())
    2533              :     }
    2534              : 
    2535              :     // when accessing management api supply None as an argument
    2536              :     // when using to authorize tenant pass corresponding tenant id
    2537            0 :     fn check_permission(&self, tenant_id: Option<TenantId>) -> Result<(), QueryError> {
    2538            0 :         if self.auth.is_none() {
    2539              :             // auth is set to Trust, nothing to check so just return ok
    2540            0 :             return Ok(());
    2541            0 :         }
    2542            0 :         // auth is some, just checked above, when auth is some
    2543            0 :         // then claims are always present because of checks during connection init
    2544            0 :         // so this expect won't trigger
    2545            0 :         let claims = self
    2546            0 :             .claims
    2547            0 :             .as_ref()
    2548            0 :             .expect("claims presence already checked");
    2549            0 :         check_permission(claims, tenant_id).map_err(|e| QueryError::Unauthorized(e.0))
    2550            0 :     }
    2551              : }
    2552              : 
    2553              : /// `basebackup tenant timeline [lsn] [--gzip] [--replica]`
    2554              : #[derive(Debug, Clone, Eq, PartialEq)]
    2555              : struct BaseBackupCmd {
    2556              :     tenant_id: TenantId,
    2557              :     timeline_id: TimelineId,
    2558              :     lsn: Option<Lsn>,
    2559              :     gzip: bool,
    2560              :     replica: bool,
    2561              : }
    2562              : 
    2563              : /// `fullbackup tenant timeline [lsn] [prev_lsn]`
    2564              : #[derive(Debug, Clone, Eq, PartialEq)]
    2565              : struct FullBackupCmd {
    2566              :     tenant_id: TenantId,
    2567              :     timeline_id: TimelineId,
    2568              :     lsn: Option<Lsn>,
    2569              :     prev_lsn: Option<Lsn>,
    2570              : }
    2571              : 
    2572              : /// `pagestream_v2 tenant timeline`
    2573              : #[derive(Debug, Clone, Eq, PartialEq)]
    2574              : struct PageStreamCmd {
    2575              :     tenant_id: TenantId,
    2576              :     timeline_id: TimelineId,
    2577              :     protocol_version: PagestreamProtocolVersion,
    2578              : }
    2579              : 
    2580              : /// `lease lsn tenant timeline lsn`
    2581              : #[derive(Debug, Clone, Eq, PartialEq)]
    2582              : struct LeaseLsnCmd {
    2583              :     tenant_shard_id: TenantShardId,
    2584              :     timeline_id: TimelineId,
    2585              :     lsn: Lsn,
    2586              : }
    2587              : 
    2588              : #[derive(Debug, Clone, Eq, PartialEq)]
    2589              : enum PageServiceCmd {
    2590              :     Set,
    2591              :     PageStream(PageStreamCmd),
    2592              :     BaseBackup(BaseBackupCmd),
    2593              :     FullBackup(FullBackupCmd),
    2594              :     LeaseLsn(LeaseLsnCmd),
    2595              : }
    2596              : 
    2597              : impl PageStreamCmd {
    2598           36 :     fn parse(query: &str, protocol_version: PagestreamProtocolVersion) -> anyhow::Result<Self> {
    2599           36 :         let parameters = query.split_whitespace().collect_vec();
    2600           36 :         if parameters.len() != 2 {
    2601           12 :             bail!(
    2602           12 :                 "invalid number of parameters for pagestream command: {}",
    2603           12 :                 query
    2604           12 :             );
    2605           24 :         }
    2606           24 :         let tenant_id = TenantId::from_str(parameters[0])
    2607           24 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2608           12 :         let timeline_id = TimelineId::from_str(parameters[1])
    2609           12 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2610           12 :         Ok(Self {
    2611           12 :             tenant_id,
    2612           12 :             timeline_id,
    2613           12 :             protocol_version,
    2614           12 :         })
    2615           36 :     }
    2616              : }
    2617              : 
    2618              : impl FullBackupCmd {
    2619           24 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2620           24 :         let parameters = query.split_whitespace().collect_vec();
    2621           24 :         if parameters.len() < 2 || parameters.len() > 4 {
    2622            0 :             bail!(
    2623            0 :                 "invalid number of parameters for basebackup command: {}",
    2624            0 :                 query
    2625            0 :             );
    2626           24 :         }
    2627           24 :         let tenant_id = TenantId::from_str(parameters[0])
    2628           24 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2629           24 :         let timeline_id = TimelineId::from_str(parameters[1])
    2630           24 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2631              :         // The caller is responsible for providing correct lsn and prev_lsn.
    2632           24 :         let lsn = if let Some(lsn_str) = parameters.get(2) {
    2633              :             Some(
    2634           12 :                 Lsn::from_str(lsn_str)
    2635           12 :                     .with_context(|| format!("Failed to parse Lsn from {lsn_str}"))?,
    2636              :             )
    2637              :         } else {
    2638           12 :             None
    2639              :         };
    2640           24 :         let prev_lsn = if let Some(prev_lsn_str) = parameters.get(3) {
    2641              :             Some(
    2642           12 :                 Lsn::from_str(prev_lsn_str)
    2643           12 :                     .with_context(|| format!("Failed to parse Lsn from {prev_lsn_str}"))?,
    2644              :             )
    2645              :         } else {
    2646           12 :             None
    2647              :         };
    2648           24 :         Ok(Self {
    2649           24 :             tenant_id,
    2650           24 :             timeline_id,
    2651           24 :             lsn,
    2652           24 :             prev_lsn,
    2653           24 :         })
    2654           24 :     }
    2655              : }
    2656              : 
    2657              : impl BaseBackupCmd {
    2658          108 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2659          108 :         let parameters = query.split_whitespace().collect_vec();
    2660          108 :         if parameters.len() < 2 {
    2661            0 :             bail!(
    2662            0 :                 "invalid number of parameters for basebackup command: {}",
    2663            0 :                 query
    2664            0 :             );
    2665          108 :         }
    2666          108 :         let tenant_id = TenantId::from_str(parameters[0])
    2667          108 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2668          108 :         let timeline_id = TimelineId::from_str(parameters[1])
    2669          108 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2670              :         let lsn;
    2671              :         let flags_parse_from;
    2672          108 :         if let Some(maybe_lsn) = parameters.get(2) {
    2673           96 :             if *maybe_lsn == "latest" {
    2674           12 :                 lsn = None;
    2675           12 :                 flags_parse_from = 3;
    2676           84 :             } else if maybe_lsn.starts_with("--") {
    2677           60 :                 lsn = None;
    2678           60 :                 flags_parse_from = 2;
    2679           60 :             } else {
    2680              :                 lsn = Some(
    2681           24 :                     Lsn::from_str(maybe_lsn)
    2682           24 :                         .with_context(|| format!("Failed to parse lsn from {maybe_lsn}"))?,
    2683              :                 );
    2684           24 :                 flags_parse_from = 3;
    2685              :             }
    2686           12 :         } else {
    2687           12 :             lsn = None;
    2688           12 :             flags_parse_from = 2;
    2689           12 :         }
    2690              : 
    2691          108 :         let mut gzip = false;
    2692          108 :         let mut replica = false;
    2693              : 
    2694          132 :         for &param in &parameters[flags_parse_from..] {
    2695          132 :             match param {
    2696          132 :                 "--gzip" => {
    2697           84 :                     if gzip {
    2698           12 :                         bail!("duplicate parameter for basebackup command: {param}")
    2699           72 :                     }
    2700           72 :                     gzip = true
    2701              :                 }
    2702           48 :                 "--replica" => {
    2703           24 :                     if replica {
    2704            0 :                         bail!("duplicate parameter for basebackup command: {param}")
    2705           24 :                     }
    2706           24 :                     replica = true
    2707              :                 }
    2708           24 :                 _ => bail!("invalid parameter for basebackup command: {param}"),
    2709              :             }
    2710              :         }
    2711           72 :         Ok(Self {
    2712           72 :             tenant_id,
    2713           72 :             timeline_id,
    2714           72 :             lsn,
    2715           72 :             gzip,
    2716           72 :             replica,
    2717           72 :         })
    2718          108 :     }
    2719              : }
    2720              : 
    2721              : impl LeaseLsnCmd {
    2722           24 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2723           24 :         let parameters = query.split_whitespace().collect_vec();
    2724           24 :         if parameters.len() != 3 {
    2725            0 :             bail!(
    2726            0 :                 "invalid number of parameters for lease lsn command: {}",
    2727            0 :                 query
    2728            0 :             );
    2729           24 :         }
    2730           24 :         let tenant_shard_id = TenantShardId::from_str(parameters[0])
    2731           24 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2732           24 :         let timeline_id = TimelineId::from_str(parameters[1])
    2733           24 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2734           24 :         let lsn = Lsn::from_str(parameters[2])
    2735           24 :             .with_context(|| format!("Failed to parse lsn from {}", parameters[2]))?;
    2736           24 :         Ok(Self {
    2737           24 :             tenant_shard_id,
    2738           24 :             timeline_id,
    2739           24 :             lsn,
    2740           24 :         })
    2741           24 :     }
    2742              : }
    2743              : 
    2744              : impl PageServiceCmd {
    2745          252 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2746          252 :         let query = query.trim();
    2747          252 :         let Some((cmd, other)) = query.split_once(' ') else {
    2748           24 :             bail!("cannot parse query: {query}")
    2749              :         };
    2750          228 :         match cmd.to_ascii_lowercase().as_str() {
    2751          228 :             "pagestream_v2" => Ok(Self::PageStream(PageStreamCmd::parse(
    2752           36 :                 other,
    2753           36 :                 PagestreamProtocolVersion::V2,
    2754           36 :             )?)),
    2755          192 :             "pagestream_v3" => Ok(Self::PageStream(PageStreamCmd::parse(
    2756            0 :                 other,
    2757            0 :                 PagestreamProtocolVersion::V3,
    2758            0 :             )?)),
    2759          192 :             "basebackup" => Ok(Self::BaseBackup(BaseBackupCmd::parse(other)?)),
    2760           84 :             "fullbackup" => Ok(Self::FullBackup(FullBackupCmd::parse(other)?)),
    2761           60 :             "lease" => {
    2762           36 :                 let Some((cmd2, other)) = other.split_once(' ') else {
    2763            0 :                     bail!("invalid lease command: {cmd}");
    2764              :                 };
    2765           36 :                 let cmd2 = cmd2.to_ascii_lowercase();
    2766           36 :                 if cmd2 == "lsn" {
    2767           24 :                     Ok(Self::LeaseLsn(LeaseLsnCmd::parse(other)?))
    2768              :                 } else {
    2769           12 :                     bail!("invalid lease command: {cmd}");
    2770              :                 }
    2771              :             }
    2772           24 :             "set" => Ok(Self::Set),
    2773            0 :             _ => Err(anyhow::anyhow!("unsupported command {cmd} in {query}")),
    2774              :         }
    2775          252 :     }
    2776              : }
    2777              : 
    2778              : /// Parse the startup options from the postgres wire protocol startup packet.
    2779              : ///
    2780              : /// It takes a sequence of `-c option=X` or `-coption=X`. It parses the options string
    2781              : /// by best effort and returns all the options parsed (key-value pairs) and a bool indicating
    2782              : /// whether all options are successfully parsed. There could be duplicates in the options
    2783              : /// if the caller passed such parameters.
    2784           84 : fn parse_options(options: &str) -> (Vec<(String, String)>, bool) {
    2785           84 :     let mut parsing_config = false;
    2786           84 :     let mut has_error = false;
    2787           84 :     let mut config = Vec::new();
    2788          192 :     for item in options.split_whitespace() {
    2789          192 :         if item == "-c" {
    2790          108 :             if !parsing_config {
    2791           96 :                 parsing_config = true;
    2792           96 :             } else {
    2793              :                 // "-c" followed with another "-c"
    2794           12 :                 tracing::warn!("failed to parse the startup options: {options}");
    2795           12 :                 has_error = true;
    2796           12 :                 break;
    2797              :             }
    2798           84 :         } else if item.starts_with("-c") || parsing_config {
    2799           84 :             let Some((mut key, value)) = item.split_once('=') else {
    2800              :                 // "-c" followed with an invalid option
    2801           12 :                 tracing::warn!("failed to parse the startup options: {options}");
    2802           12 :                 has_error = true;
    2803           12 :                 break;
    2804              :             };
    2805           72 :             if !parsing_config {
    2806              :                 // Parse "-coptions=X"
    2807           12 :                 let Some(stripped_key) = key.strip_prefix("-c") else {
    2808            0 :                     tracing::warn!("failed to parse the startup options: {options}");
    2809            0 :                     has_error = true;
    2810            0 :                     break;
    2811              :                 };
    2812           12 :                 key = stripped_key;
    2813           60 :             }
    2814           72 :             config.push((key.to_string(), value.to_string()));
    2815           72 :             parsing_config = false;
    2816              :         } else {
    2817            0 :             tracing::warn!("failed to parse the startup options: {options}");
    2818            0 :             has_error = true;
    2819            0 :             break;
    2820              :         }
    2821              :     }
    2822           84 :     if parsing_config {
    2823              :         // "-c" without the option
    2824           36 :         tracing::warn!("failed to parse the startup options: {options}");
    2825           36 :         has_error = true;
    2826           48 :     }
    2827           84 :     (config, has_error)
    2828           84 : }
    2829              : 
    2830              : impl<IO> postgres_backend::Handler<IO> for PageServerHandler
    2831              : where
    2832              :     IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    2833              : {
    2834            0 :     fn check_auth_jwt(
    2835            0 :         &mut self,
    2836            0 :         _pgb: &mut PostgresBackend<IO>,
    2837            0 :         jwt_response: &[u8],
    2838            0 :     ) -> Result<(), QueryError> {
    2839              :         // this unwrap is never triggered, because check_auth_jwt only called when auth_type is NeonJWT
    2840              :         // which requires auth to be present
    2841            0 :         let data: TokenData<Claims> = self
    2842            0 :             .auth
    2843            0 :             .as_ref()
    2844            0 :             .unwrap()
    2845            0 :             .decode(str::from_utf8(jwt_response).context("jwt response is not UTF-8")?)
    2846            0 :             .map_err(|e| QueryError::Unauthorized(e.0))?;
    2847              : 
    2848            0 :         if matches!(data.claims.scope, Scope::Tenant) && data.claims.tenant_id.is_none() {
    2849            0 :             return Err(QueryError::Unauthorized(
    2850            0 :                 "jwt token scope is Tenant, but tenant id is missing".into(),
    2851            0 :             ));
    2852            0 :         }
    2853            0 : 
    2854            0 :         debug!(
    2855            0 :             "jwt scope check succeeded for scope: {:#?} by tenant id: {:?}",
    2856              :             data.claims.scope, data.claims.tenant_id,
    2857              :         );
    2858              : 
    2859            0 :         self.claims = Some(data.claims);
    2860            0 :         Ok(())
    2861            0 :     }
    2862              : 
    2863            0 :     fn startup(
    2864            0 :         &mut self,
    2865            0 :         _pgb: &mut PostgresBackend<IO>,
    2866            0 :         sm: &FeStartupPacket,
    2867            0 :     ) -> Result<(), QueryError> {
    2868            0 :         fail::fail_point!("ps::connection-start::startup-packet");
    2869              : 
    2870            0 :         if let FeStartupPacket::StartupMessage { params, .. } = sm {
    2871            0 :             if let Some(app_name) = params.get("application_name") {
    2872            0 :                 self.perf_span_fields.application_name = Some(app_name.to_string());
    2873            0 :                 Span::current().record("application_name", field::display(app_name));
    2874            0 :             }
    2875            0 :             if let Some(options) = params.get("options") {
    2876            0 :                 let (config, _) = parse_options(options);
    2877            0 :                 for (key, value) in config {
    2878            0 :                     if key == "neon.compute_mode" {
    2879            0 :                         self.perf_span_fields.compute_mode = Some(value.clone());
    2880            0 :                         Span::current().record("compute_mode", field::display(value));
    2881            0 :                     }
    2882              :                 }
    2883            0 :             }
    2884            0 :         };
    2885              : 
    2886            0 :         Ok(())
    2887            0 :     }
    2888              : 
    2889              :     #[instrument(skip_all, fields(tenant_id, timeline_id))]
    2890              :     async fn process_query(
    2891              :         &mut self,
    2892              :         pgb: &mut PostgresBackend<IO>,
    2893              :         query_string: &str,
    2894              :     ) -> Result<(), QueryError> {
    2895            0 :         fail::fail_point!("simulated-bad-compute-connection", |_| {
    2896            0 :             info!("Hit failpoint for bad connection");
    2897            0 :             Err(QueryError::SimulatedConnectionError)
    2898            0 :         });
    2899              : 
    2900              :         fail::fail_point!("ps::connection-start::process-query");
    2901              : 
    2902              :         let ctx = self.connection_ctx.attached_child();
    2903              :         debug!("process query {query_string}");
    2904              :         let query = PageServiceCmd::parse(query_string)?;
    2905              :         match query {
    2906              :             PageServiceCmd::PageStream(PageStreamCmd {
    2907              :                 tenant_id,
    2908              :                 timeline_id,
    2909              :                 protocol_version,
    2910              :             }) => {
    2911              :                 tracing::Span::current()
    2912              :                     .record("tenant_id", field::display(tenant_id))
    2913              :                     .record("timeline_id", field::display(timeline_id));
    2914              : 
    2915              :                 self.check_permission(Some(tenant_id))?;
    2916              :                 let command_kind = match protocol_version {
    2917              :                     PagestreamProtocolVersion::V2 => ComputeCommandKind::PageStreamV2,
    2918              :                     PagestreamProtocolVersion::V3 => ComputeCommandKind::PageStreamV3,
    2919              :                 };
    2920              :                 COMPUTE_COMMANDS_COUNTERS.for_command(command_kind).inc();
    2921              : 
    2922              :                 self.handle_pagerequests(pgb, tenant_id, timeline_id, protocol_version, ctx)
    2923              :                     .await?;
    2924              :             }
    2925              :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    2926              :                 tenant_id,
    2927              :                 timeline_id,
    2928              :                 lsn,
    2929              :                 gzip,
    2930              :                 replica,
    2931              :             }) => {
    2932              :                 tracing::Span::current()
    2933              :                     .record("tenant_id", field::display(tenant_id))
    2934              :                     .record("timeline_id", field::display(timeline_id));
    2935              : 
    2936              :                 self.check_permission(Some(tenant_id))?;
    2937              : 
    2938              :                 COMPUTE_COMMANDS_COUNTERS
    2939              :                     .for_command(ComputeCommandKind::Basebackup)
    2940              :                     .inc();
    2941              :                 let metric_recording = metrics::BASEBACKUP_QUERY_TIME.start_recording();
    2942            0 :                 let res = async {
    2943            0 :                     self.handle_basebackup_request(
    2944            0 :                         pgb,
    2945            0 :                         tenant_id,
    2946            0 :                         timeline_id,
    2947            0 :                         lsn,
    2948            0 :                         None,
    2949            0 :                         false,
    2950            0 :                         gzip,
    2951            0 :                         replica,
    2952            0 :                         &ctx,
    2953            0 :                     )
    2954            0 :                     .await?;
    2955            0 :                     pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    2956            0 :                     Result::<(), QueryError>::Ok(())
    2957            0 :                 }
    2958              :                 .await;
    2959              :                 metric_recording.observe(&res);
    2960              :                 res?;
    2961              :             }
    2962              :             // same as basebackup, but result includes relational data as well
    2963              :             PageServiceCmd::FullBackup(FullBackupCmd {
    2964              :                 tenant_id,
    2965              :                 timeline_id,
    2966              :                 lsn,
    2967              :                 prev_lsn,
    2968              :             }) => {
    2969              :                 tracing::Span::current()
    2970              :                     .record("tenant_id", field::display(tenant_id))
    2971              :                     .record("timeline_id", field::display(timeline_id));
    2972              : 
    2973              :                 self.check_permission(Some(tenant_id))?;
    2974              : 
    2975              :                 COMPUTE_COMMANDS_COUNTERS
    2976              :                     .for_command(ComputeCommandKind::Fullbackup)
    2977              :                     .inc();
    2978              : 
    2979              :                 // Check that the timeline exists
    2980              :                 self.handle_basebackup_request(
    2981              :                     pgb,
    2982              :                     tenant_id,
    2983              :                     timeline_id,
    2984              :                     lsn,
    2985              :                     prev_lsn,
    2986              :                     true,
    2987              :                     false,
    2988              :                     false,
    2989              :                     &ctx,
    2990              :                 )
    2991              :                 .await?;
    2992              :                 pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    2993              :             }
    2994              :             PageServiceCmd::Set => {
    2995              :                 // important because psycopg2 executes "SET datestyle TO 'ISO'"
    2996              :                 // on connect
    2997              :                 // TODO: allow setting options, i.e., application_name/compute_mode via SET commands
    2998              :                 pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    2999              :             }
    3000              :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    3001              :                 tenant_shard_id,
    3002              :                 timeline_id,
    3003              :                 lsn,
    3004              :             }) => {
    3005              :                 tracing::Span::current()
    3006              :                     .record("tenant_id", field::display(tenant_shard_id))
    3007              :                     .record("timeline_id", field::display(timeline_id));
    3008              : 
    3009              :                 self.check_permission(Some(tenant_shard_id.tenant_id))?;
    3010              : 
    3011              :                 COMPUTE_COMMANDS_COUNTERS
    3012              :                     .for_command(ComputeCommandKind::LeaseLsn)
    3013              :                     .inc();
    3014              : 
    3015              :                 match self
    3016              :                     .handle_make_lsn_lease(pgb, tenant_shard_id, timeline_id, lsn, &ctx)
    3017              :                     .await
    3018              :                 {
    3019              :                     Ok(()) => {
    3020              :                         pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?
    3021              :                     }
    3022              :                     Err(e) => {
    3023              :                         error!("error obtaining lsn lease for {lsn}: {e:?}");
    3024              :                         pgb.write_message_noflush(&BeMessage::ErrorResponse(
    3025              :                             &e.to_string(),
    3026              :                             Some(e.pg_error_code()),
    3027              :                         ))?
    3028              :                     }
    3029              :                 };
    3030              :             }
    3031              :         }
    3032              : 
    3033              :         Ok(())
    3034              :     }
    3035              : }
    3036              : 
    3037              : impl From<GetActiveTenantError> for QueryError {
    3038            0 :     fn from(e: GetActiveTenantError) -> Self {
    3039            0 :         match e {
    3040            0 :             GetActiveTenantError::WaitForActiveTimeout { .. } => QueryError::Disconnected(
    3041            0 :                 ConnectionError::Io(io::Error::new(io::ErrorKind::TimedOut, e.to_string())),
    3042            0 :             ),
    3043              :             GetActiveTenantError::Cancelled
    3044              :             | GetActiveTenantError::WillNotBecomeActive(TenantState::Stopping { .. }) => {
    3045            0 :                 QueryError::Shutdown
    3046              :             }
    3047            0 :             e @ GetActiveTenantError::NotFound(_) => QueryError::NotFound(format!("{e}").into()),
    3048            0 :             e => QueryError::Other(anyhow::anyhow!(e)),
    3049              :         }
    3050            0 :     }
    3051              : }
    3052              : 
    3053              : #[derive(Debug, thiserror::Error)]
    3054              : pub(crate) enum GetActiveTimelineError {
    3055              :     #[error(transparent)]
    3056              :     Tenant(GetActiveTenantError),
    3057              :     #[error(transparent)]
    3058              :     Timeline(#[from] GetTimelineError),
    3059              : }
    3060              : 
    3061              : impl From<GetActiveTimelineError> for QueryError {
    3062            0 :     fn from(e: GetActiveTimelineError) -> Self {
    3063            0 :         match e {
    3064            0 :             GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled) => QueryError::Shutdown,
    3065            0 :             GetActiveTimelineError::Tenant(e) => e.into(),
    3066            0 :             GetActiveTimelineError::Timeline(e) => QueryError::NotFound(format!("{e}").into()),
    3067              :         }
    3068            0 :     }
    3069              : }
    3070              : 
    3071              : impl From<crate::tenant::timeline::handle::HandleUpgradeError> for QueryError {
    3072            0 :     fn from(e: crate::tenant::timeline::handle::HandleUpgradeError) -> Self {
    3073            0 :         match e {
    3074            0 :             crate::tenant::timeline::handle::HandleUpgradeError::ShutDown => QueryError::Shutdown,
    3075            0 :         }
    3076            0 :     }
    3077              : }
    3078              : 
    3079            0 : fn set_tracing_field_shard_id(timeline: &Timeline) {
    3080            0 :     debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    3081            0 :     tracing::Span::current().record(
    3082            0 :         "shard_id",
    3083            0 :         tracing::field::display(timeline.tenant_shard_id.shard_slug()),
    3084            0 :     );
    3085            0 :     debug_assert_current_span_has_tenant_and_timeline_id();
    3086            0 : }
    3087              : 
    3088              : struct WaitedForLsn(Lsn);
    3089              : impl From<WaitedForLsn> for Lsn {
    3090            0 :     fn from(WaitedForLsn(lsn): WaitedForLsn) -> Self {
    3091            0 :         lsn
    3092            0 :     }
    3093              : }
    3094              : 
    3095              : #[cfg(test)]
    3096              : mod tests {
    3097              :     use utils::shard::ShardCount;
    3098              : 
    3099              :     use super::*;
    3100              : 
    3101              :     #[test]
    3102           12 :     fn pageservice_cmd_parse() {
    3103           12 :         let tenant_id = TenantId::generate();
    3104           12 :         let timeline_id = TimelineId::generate();
    3105           12 :         let cmd =
    3106           12 :             PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id} {timeline_id}")).unwrap();
    3107           12 :         assert_eq!(
    3108           12 :             cmd,
    3109           12 :             PageServiceCmd::PageStream(PageStreamCmd {
    3110           12 :                 tenant_id,
    3111           12 :                 timeline_id,
    3112           12 :                 protocol_version: PagestreamProtocolVersion::V2,
    3113           12 :             })
    3114           12 :         );
    3115           12 :         let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id}")).unwrap();
    3116           12 :         assert_eq!(
    3117           12 :             cmd,
    3118           12 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    3119           12 :                 tenant_id,
    3120           12 :                 timeline_id,
    3121           12 :                 lsn: None,
    3122           12 :                 gzip: false,
    3123           12 :                 replica: false
    3124           12 :             })
    3125           12 :         );
    3126           12 :         let cmd =
    3127           12 :             PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} --gzip")).unwrap();
    3128           12 :         assert_eq!(
    3129           12 :             cmd,
    3130           12 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    3131           12 :                 tenant_id,
    3132           12 :                 timeline_id,
    3133           12 :                 lsn: None,
    3134           12 :                 gzip: true,
    3135           12 :                 replica: false
    3136           12 :             })
    3137           12 :         );
    3138           12 :         let cmd =
    3139           12 :             PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} latest")).unwrap();
    3140           12 :         assert_eq!(
    3141           12 :             cmd,
    3142           12 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    3143           12 :                 tenant_id,
    3144           12 :                 timeline_id,
    3145           12 :                 lsn: None,
    3146           12 :                 gzip: false,
    3147           12 :                 replica: false
    3148           12 :             })
    3149           12 :         );
    3150           12 :         let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} 0/16ABCDE"))
    3151           12 :             .unwrap();
    3152           12 :         assert_eq!(
    3153           12 :             cmd,
    3154           12 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    3155           12 :                 tenant_id,
    3156           12 :                 timeline_id,
    3157           12 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    3158           12 :                 gzip: false,
    3159           12 :                 replica: false
    3160           12 :             })
    3161           12 :         );
    3162           12 :         let cmd = PageServiceCmd::parse(&format!(
    3163           12 :             "basebackup {tenant_id} {timeline_id} --replica --gzip"
    3164           12 :         ))
    3165           12 :         .unwrap();
    3166           12 :         assert_eq!(
    3167           12 :             cmd,
    3168           12 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    3169           12 :                 tenant_id,
    3170           12 :                 timeline_id,
    3171           12 :                 lsn: None,
    3172           12 :                 gzip: true,
    3173           12 :                 replica: true
    3174           12 :             })
    3175           12 :         );
    3176           12 :         let cmd = PageServiceCmd::parse(&format!(
    3177           12 :             "basebackup {tenant_id} {timeline_id} 0/16ABCDE --replica --gzip"
    3178           12 :         ))
    3179           12 :         .unwrap();
    3180           12 :         assert_eq!(
    3181           12 :             cmd,
    3182           12 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    3183           12 :                 tenant_id,
    3184           12 :                 timeline_id,
    3185           12 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    3186           12 :                 gzip: true,
    3187           12 :                 replica: true
    3188           12 :             })
    3189           12 :         );
    3190           12 :         let cmd = PageServiceCmd::parse(&format!("fullbackup {tenant_id} {timeline_id}")).unwrap();
    3191           12 :         assert_eq!(
    3192           12 :             cmd,
    3193           12 :             PageServiceCmd::FullBackup(FullBackupCmd {
    3194           12 :                 tenant_id,
    3195           12 :                 timeline_id,
    3196           12 :                 lsn: None,
    3197           12 :                 prev_lsn: None
    3198           12 :             })
    3199           12 :         );
    3200           12 :         let cmd = PageServiceCmd::parse(&format!(
    3201           12 :             "fullbackup {tenant_id} {timeline_id} 0/16ABCDE 0/16ABCDF"
    3202           12 :         ))
    3203           12 :         .unwrap();
    3204           12 :         assert_eq!(
    3205           12 :             cmd,
    3206           12 :             PageServiceCmd::FullBackup(FullBackupCmd {
    3207           12 :                 tenant_id,
    3208           12 :                 timeline_id,
    3209           12 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    3210           12 :                 prev_lsn: Some(Lsn::from_str("0/16ABCDF").unwrap()),
    3211           12 :             })
    3212           12 :         );
    3213           12 :         let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    3214           12 :         let cmd = PageServiceCmd::parse(&format!(
    3215           12 :             "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
    3216           12 :         ))
    3217           12 :         .unwrap();
    3218           12 :         assert_eq!(
    3219           12 :             cmd,
    3220           12 :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    3221           12 :                 tenant_shard_id,
    3222           12 :                 timeline_id,
    3223           12 :                 lsn: Lsn::from_str("0/16ABCDE").unwrap(),
    3224           12 :             })
    3225           12 :         );
    3226           12 :         let tenant_shard_id = TenantShardId::split(&tenant_shard_id, ShardCount(8))[1];
    3227           12 :         let cmd = PageServiceCmd::parse(&format!(
    3228           12 :             "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
    3229           12 :         ))
    3230           12 :         .unwrap();
    3231           12 :         assert_eq!(
    3232           12 :             cmd,
    3233           12 :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    3234           12 :                 tenant_shard_id,
    3235           12 :                 timeline_id,
    3236           12 :                 lsn: Lsn::from_str("0/16ABCDE").unwrap(),
    3237           12 :             })
    3238           12 :         );
    3239           12 :         let cmd = PageServiceCmd::parse("set a = b").unwrap();
    3240           12 :         assert_eq!(cmd, PageServiceCmd::Set);
    3241           12 :         let cmd = PageServiceCmd::parse("SET foo").unwrap();
    3242           12 :         assert_eq!(cmd, PageServiceCmd::Set);
    3243           12 :     }
    3244              : 
    3245              :     #[test]
    3246           12 :     fn pageservice_cmd_err_handling() {
    3247           12 :         let tenant_id = TenantId::generate();
    3248           12 :         let timeline_id = TimelineId::generate();
    3249           12 :         let cmd = PageServiceCmd::parse("unknown_command");
    3250           12 :         assert!(cmd.is_err());
    3251           12 :         let cmd = PageServiceCmd::parse("pagestream_v2");
    3252           12 :         assert!(cmd.is_err());
    3253           12 :         let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx"));
    3254           12 :         assert!(cmd.is_err());
    3255           12 :         let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx {timeline_id}xxx"));
    3256           12 :         assert!(cmd.is_err());
    3257           12 :         let cmd = PageServiceCmd::parse(&format!(
    3258           12 :             "basebackup {tenant_id} {timeline_id} --gzip --gzip"
    3259           12 :         ));
    3260           12 :         assert!(cmd.is_err());
    3261           12 :         let cmd = PageServiceCmd::parse(&format!(
    3262           12 :             "basebackup {tenant_id} {timeline_id} --gzip --unknown"
    3263           12 :         ));
    3264           12 :         assert!(cmd.is_err());
    3265           12 :         let cmd = PageServiceCmd::parse(&format!(
    3266           12 :             "basebackup {tenant_id} {timeline_id} --gzip 0/16ABCDE"
    3267           12 :         ));
    3268           12 :         assert!(cmd.is_err());
    3269           12 :         let cmd = PageServiceCmd::parse(&format!("lease {tenant_id} {timeline_id} gzip 0/16ABCDE"));
    3270           12 :         assert!(cmd.is_err());
    3271           12 :     }
    3272              : 
    3273              :     #[test]
    3274           12 :     fn test_parse_options() {
    3275           12 :         let (config, has_error) = parse_options(" -c neon.compute_mode=primary ");
    3276           12 :         assert!(!has_error);
    3277           12 :         assert_eq!(
    3278           12 :             config,
    3279           12 :             vec![("neon.compute_mode".to_string(), "primary".to_string())]
    3280           12 :         );
    3281              : 
    3282           12 :         let (config, has_error) = parse_options(" -c neon.compute_mode=primary -c foo=bar ");
    3283           12 :         assert!(!has_error);
    3284           12 :         assert_eq!(
    3285           12 :             config,
    3286           12 :             vec![
    3287           12 :                 ("neon.compute_mode".to_string(), "primary".to_string()),
    3288           12 :                 ("foo".to_string(), "bar".to_string()),
    3289           12 :             ]
    3290           12 :         );
    3291              : 
    3292           12 :         let (config, has_error) = parse_options(" -c neon.compute_mode=primary -cfoo=bar");
    3293           12 :         assert!(!has_error);
    3294           12 :         assert_eq!(
    3295           12 :             config,
    3296           12 :             vec![
    3297           12 :                 ("neon.compute_mode".to_string(), "primary".to_string()),
    3298           12 :                 ("foo".to_string(), "bar".to_string()),
    3299           12 :             ]
    3300           12 :         );
    3301              : 
    3302           12 :         let (_, has_error) = parse_options("-c");
    3303           12 :         assert!(has_error);
    3304              : 
    3305           12 :         let (_, has_error) = parse_options("-c foo=bar -c -c");
    3306           12 :         assert!(has_error);
    3307              : 
    3308           12 :         let (_, has_error) = parse_options("    ");
    3309           12 :         assert!(!has_error);
    3310              : 
    3311           12 :         let (_, has_error) = parse_options(" -c neon.compute_mode");
    3312           12 :         assert!(has_error);
    3313           12 :     }
    3314              : }
        

Generated by: LCOV version 2.1-beta