LCOV - code coverage report
Current view: top level - pageserver/src - page_service.rs (source / functions) Coverage Total Hit
Test: 9e3a1ccbd88185d44390421f76c05f0bf588f617.info Lines: 17.1 % 1876 321
Test Date: 2025-07-29 14:19:29 Functions: 5.0 % 202 10

            Line data    Source code
       1              : //! The Page Service listens for client connections and serves their GetPage@LSN
       2              : //! requests.
       3              : 
       4              : use std::any::Any;
       5              : use std::borrow::Cow;
       6              : use std::num::NonZeroUsize;
       7              : use std::os::fd::AsRawFd;
       8              : use std::pin::Pin;
       9              : use std::str::FromStr;
      10              : use std::sync::Arc;
      11              : use std::task::{Context, Poll};
      12              : use std::time::{Duration, Instant, SystemTime};
      13              : use std::{io, str};
      14              : 
      15              : use anyhow::{Context as _, bail};
      16              : use bytes::{Buf as _, BufMut as _, BytesMut};
      17              : use chrono::Utc;
      18              : use futures::future::BoxFuture;
      19              : use futures::{FutureExt, Stream};
      20              : use itertools::Itertools;
      21              : use jsonwebtoken::TokenData;
      22              : use once_cell::sync::OnceCell;
      23              : use pageserver_api::config::{
      24              :     GetVectoredConcurrentIo, PageServicePipeliningConfig, PageServicePipeliningConfigPipelined,
      25              :     PageServiceProtocolPipelinedBatchingStrategy, PageServiceProtocolPipelinedExecutionStrategy,
      26              : };
      27              : use pageserver_api::key::rel_block_to_key;
      28              : use pageserver_api::models::{PageTraceEvent, TenantState};
      29              : use pageserver_api::pagestream_api::{
      30              :     self, PagestreamBeMessage, PagestreamDbSizeRequest, PagestreamDbSizeResponse,
      31              :     PagestreamErrorResponse, PagestreamExistsRequest, PagestreamExistsResponse,
      32              :     PagestreamFeMessage, PagestreamGetPageRequest, PagestreamGetSlruSegmentRequest,
      33              :     PagestreamGetSlruSegmentResponse, PagestreamNblocksRequest, PagestreamNblocksResponse,
      34              :     PagestreamProtocolVersion, PagestreamRequest,
      35              : };
      36              : use pageserver_api::reltag::SlruKind;
      37              : use pageserver_api::shard::TenantShardId;
      38              : use pageserver_page_api as page_api;
      39              : use pageserver_page_api::proto;
      40              : use postgres_backend::{
      41              :     AuthType, PostgresBackend, PostgresBackendReader, QueryError, is_expected_io_error,
      42              : };
      43              : use postgres_ffi::BLCKSZ;
      44              : use postgres_ffi_types::constants::DEFAULTTABLESPACE_OID;
      45              : use pq_proto::framed::ConnectionError;
      46              : use pq_proto::{BeMessage, FeMessage, FeStartupPacket, RowDescriptor};
      47              : use smallvec::{SmallVec, smallvec};
      48              : use strum_macros::IntoStaticStr;
      49              : use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _, BufWriter};
      50              : use tokio::task::JoinHandle;
      51              : use tokio_util::sync::CancellationToken;
      52              : use tonic::service::Interceptor as _;
      53              : use tonic::transport::server::TcpConnectInfo;
      54              : use tracing::*;
      55              : use utils::auth::{Claims, Scope, SwappableJwtAuth};
      56              : use utils::id::{TenantId, TenantTimelineId, TimelineId};
      57              : use utils::logging::log_slow;
      58              : use utils::lsn::Lsn;
      59              : use utils::shard::ShardIndex;
      60              : use utils::simple_rcu::RcuReadGuard;
      61              : use utils::sync::gate::{Gate, GateGuard};
      62              : use utils::sync::spsc_fold;
      63              : use utils::{failpoint_support, span_record};
      64              : 
      65              : use crate::auth::check_permission;
      66              : use crate::basebackup::{self, BasebackupError};
      67              : use crate::config::PageServerConf;
      68              : use crate::context::{
      69              :     DownloadBehavior, PerfInstrumentFutureExt, RequestContext, RequestContextBuilder,
      70              : };
      71              : use crate::feature_resolver::FeatureResolver;
      72              : use crate::metrics::{
      73              :     self, COMPUTE_COMMANDS_COUNTERS, ComputeCommandKind, GetPageBatchBreakReason, LIVE_CONNECTIONS,
      74              :     MISROUTED_PAGESTREAM_REQUESTS, PAGESTREAM_HANDLER_RESULTS_TOTAL, SmgrOpTimer, TimelineMetrics,
      75              : };
      76              : use crate::pgdatadir_mapping::{LsnRange, Version};
      77              : use crate::span::{
      78              :     debug_assert_current_span_has_tenant_and_timeline_id,
      79              :     debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id,
      80              : };
      81              : use crate::task_mgr::{self, COMPUTE_REQUEST_RUNTIME, TaskKind};
      82              : use crate::tenant::mgr::{
      83              :     GetActiveTenantError, GetTenantError, ShardResolveResult, ShardSelector, TenantManager,
      84              : };
      85              : use crate::tenant::storage_layer::IoConcurrency;
      86              : use crate::tenant::timeline::handle::{Handle, HandleUpgradeError, WeakHandle};
      87              : use crate::tenant::timeline::{self, WaitLsnError, WaitLsnTimeout, WaitLsnWaiter};
      88              : use crate::tenant::{GetTimelineError, PageReconstructError, Timeline};
      89              : use crate::{CancellableTask, PERF_TRACE_TARGET, timed_after_cancellation};
      90              : 
      91              : /// How long we may wait for a [`crate::tenant::mgr::TenantSlot::InProgress`]` and/or a [`crate::tenant::TenantShard`] which
      92              : /// is not yet in state [`TenantState::Active`].
      93              : ///
      94              : /// NB: this is a different value than [`crate::http::routes::ACTIVE_TENANT_TIMEOUT`].
      95              : /// HADRON: reduced timeout and we will retry in Cache::get().
      96              : const ACTIVE_TENANT_TIMEOUT: Duration = Duration::from_millis(5000);
      97              : 
      98              : /// Threshold at which to log slow GetPage requests.
      99              : const LOG_SLOW_GETPAGE_THRESHOLD: Duration = Duration::from_secs(30);
     100              : 
     101              : /// The idle time before sending TCP keepalive probes for gRPC connections. The
     102              : /// interval and timeout between each probe is configured via sysctl. This
     103              : /// allows detecting dead connections sooner.
     104              : const GRPC_TCP_KEEPALIVE_TIME: Duration = Duration::from_secs(60);
     105              : 
     106              : /// Whether to enable TCP nodelay for gRPC connections. This disables Nagle's
     107              : /// algorithm, which can cause latency spikes for small messages.
     108              : const GRPC_TCP_NODELAY: bool = true;
     109              : 
     110              : /// The interval between HTTP2 keepalive pings. This allows shutting down server
     111              : /// tasks when clients are unresponsive.
     112              : const GRPC_HTTP2_KEEPALIVE_INTERVAL: Duration = Duration::from_secs(30);
     113              : 
     114              : /// The timeout for HTTP2 keepalive pings. Should be <= GRPC_KEEPALIVE_INTERVAL.
     115              : const GRPC_HTTP2_KEEPALIVE_TIMEOUT: Duration = Duration::from_secs(20);
     116              : 
     117              : /// Number of concurrent gRPC streams per TCP connection. We expect something
     118              : /// like 8 GetPage streams per connections, plus any unary requests.
     119              : const GRPC_MAX_CONCURRENT_STREAMS: u32 = 256;
     120              : 
     121              : ///////////////////////////////////////////////////////////////////////////////
     122              : 
     123              : pub struct Listener {
     124              :     cancel: CancellationToken,
     125              :     /// Cancel the listener task through `listen_cancel` to shut down the listener
     126              :     /// and get a handle on the existing connections.
     127              :     task: JoinHandle<Connections>,
     128              : }
     129              : 
     130              : pub struct Connections {
     131              :     cancel: CancellationToken,
     132              :     tasks: tokio::task::JoinSet<ConnectionHandlerResult>,
     133              :     gate: Gate,
     134              : }
     135              : 
     136            0 : pub fn spawn(
     137            0 :     conf: &'static PageServerConf,
     138            0 :     tenant_manager: Arc<TenantManager>,
     139            0 :     pg_auth: Option<Arc<SwappableJwtAuth>>,
     140            0 :     perf_trace_dispatch: Option<Dispatch>,
     141            0 :     tcp_listener: tokio::net::TcpListener,
     142            0 :     tls_config: Option<Arc<rustls::ServerConfig>>,
     143            0 :     feature_resolver: FeatureResolver,
     144            0 : ) -> Listener {
     145            0 :     let cancel = CancellationToken::new();
     146            0 :     let libpq_ctx = RequestContext::todo_child(
     147            0 :         TaskKind::LibpqEndpointListener,
     148              :         // listener task shouldn't need to download anything. (We will
     149              :         // create a separate sub-contexts for each connection, with their
     150              :         // own download behavior. This context is used only to listen and
     151              :         // accept connections.)
     152            0 :         DownloadBehavior::Error,
     153              :     );
     154            0 :     let task = COMPUTE_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
     155            0 :         "libpq listener",
     156            0 :         libpq_listener_main(
     157            0 :             conf,
     158            0 :             tenant_manager,
     159            0 :             pg_auth,
     160            0 :             perf_trace_dispatch,
     161            0 :             tcp_listener,
     162            0 :             conf.pg_auth_type,
     163            0 :             tls_config,
     164            0 :             conf.page_service_pipelining.clone(),
     165            0 :             feature_resolver,
     166            0 :             libpq_ctx,
     167            0 :             cancel.clone(),
     168            0 :         )
     169            0 :         .map(anyhow::Ok),
     170            0 :     ));
     171              : 
     172            0 :     Listener { cancel, task }
     173            0 : }
     174              : 
     175              : impl Listener {
     176            0 :     pub async fn stop_accepting(self) -> Connections {
     177            0 :         self.cancel.cancel();
     178            0 :         self.task
     179            0 :             .await
     180            0 :             .expect("unreachable: we wrap the listener task in task_mgr::exit_on_panic_or_error")
     181            0 :     }
     182              : }
     183              : impl Connections {
     184            0 :     pub(crate) async fn shutdown(self) {
     185              :         let Self {
     186            0 :             cancel,
     187            0 :             mut tasks,
     188            0 :             gate,
     189            0 :         } = self;
     190            0 :         cancel.cancel();
     191            0 :         while let Some(res) = tasks.join_next().await {
     192            0 :             Self::handle_connection_completion(res);
     193            0 :         }
     194            0 :         gate.close().await;
     195            0 :     }
     196              : 
     197            0 :     fn handle_connection_completion(res: Result<anyhow::Result<()>, tokio::task::JoinError>) {
     198            0 :         match res {
     199            0 :             Ok(Ok(())) => {}
     200            0 :             Ok(Err(e)) => error!("error in page_service connection task: {:?}", e),
     201            0 :             Err(e) => error!("page_service connection task panicked: {:?}", e),
     202              :         }
     203            0 :     }
     204              : }
     205              : 
     206              : ///
     207              : /// Main loop of the page service.
     208              : ///
     209              : /// Listens for connections, and launches a new handler task for each.
     210              : ///
     211              : /// Returns Ok(()) upon cancellation via `cancel`, returning the set of
     212              : /// open connections.
     213              : ///
     214              : #[allow(clippy::too_many_arguments)]
     215            0 : pub async fn libpq_listener_main(
     216            0 :     conf: &'static PageServerConf,
     217            0 :     tenant_manager: Arc<TenantManager>,
     218            0 :     auth: Option<Arc<SwappableJwtAuth>>,
     219            0 :     perf_trace_dispatch: Option<Dispatch>,
     220            0 :     listener: tokio::net::TcpListener,
     221            0 :     auth_type: AuthType,
     222            0 :     tls_config: Option<Arc<rustls::ServerConfig>>,
     223            0 :     pipelining_config: PageServicePipeliningConfig,
     224            0 :     feature_resolver: FeatureResolver,
     225            0 :     listener_ctx: RequestContext,
     226            0 :     listener_cancel: CancellationToken,
     227            0 : ) -> Connections {
     228            0 :     let connections_cancel = CancellationToken::new();
     229            0 :     let connections_gate = Gate::default();
     230            0 :     let mut connection_handler_tasks = tokio::task::JoinSet::default();
     231              : 
     232              :     loop {
     233            0 :         let gate_guard = match connections_gate.enter() {
     234            0 :             Ok(guard) => guard,
     235            0 :             Err(_) => break,
     236              :         };
     237              : 
     238            0 :         let accepted = tokio::select! {
     239              :             biased;
     240            0 :             _ = listener_cancel.cancelled() => break,
     241            0 :             next = connection_handler_tasks.join_next(), if !connection_handler_tasks.is_empty() => {
     242            0 :                 let res = next.expect("we dont poll while empty");
     243            0 :                 Connections::handle_connection_completion(res);
     244            0 :                 continue;
     245              :             }
     246            0 :             accepted = listener.accept() => accepted,
     247              :         };
     248              : 
     249            0 :         match accepted {
     250            0 :             Ok((socket, peer_addr)) => {
     251              :                 // Connection established. Spawn a new task to handle it.
     252            0 :                 debug!("accepted connection from {}", peer_addr);
     253            0 :                 let local_auth = auth.clone();
     254            0 :                 let connection_ctx = RequestContextBuilder::from(&listener_ctx)
     255            0 :                     .task_kind(TaskKind::PageRequestHandler)
     256            0 :                     .download_behavior(DownloadBehavior::Download)
     257            0 :                     .perf_span_dispatch(perf_trace_dispatch.clone())
     258            0 :                     .detached_child();
     259              : 
     260            0 :                 connection_handler_tasks.spawn(page_service_conn_main(
     261            0 :                     conf,
     262            0 :                     tenant_manager.clone(),
     263            0 :                     local_auth,
     264            0 :                     socket,
     265            0 :                     auth_type,
     266            0 :                     tls_config.clone(),
     267            0 :                     pipelining_config.clone(),
     268            0 :                     feature_resolver.clone(),
     269            0 :                     connection_ctx,
     270            0 :                     connections_cancel.child_token(),
     271            0 :                     gate_guard,
     272              :                 ));
     273              :             }
     274            0 :             Err(err) => {
     275              :                 // accept() failed. Log the error, and loop back to retry on next connection.
     276            0 :                 error!("accept() failed: {:?}", err);
     277              :             }
     278              :         }
     279              :     }
     280              : 
     281            0 :     debug!("page_service listener loop terminated");
     282              : 
     283            0 :     Connections {
     284            0 :         cancel: connections_cancel,
     285            0 :         tasks: connection_handler_tasks,
     286            0 :         gate: connections_gate,
     287            0 :     }
     288            0 : }
     289              : 
     290              : type ConnectionHandlerResult = anyhow::Result<()>;
     291              : 
     292              : /// Perf root spans start at the per-request level, after shard routing.
     293              : /// This struct carries connection-level information to the root perf span definition.
     294              : #[derive(Clone, Default)]
     295              : struct ConnectionPerfSpanFields {
     296              :     peer_addr: String,
     297              :     application_name: Option<String>,
     298              :     compute_mode: Option<String>,
     299              : }
     300              : 
     301              : #[instrument(skip_all, fields(peer_addr, application_name, compute_mode))]
     302              : #[allow(clippy::too_many_arguments)]
     303              : async fn page_service_conn_main(
     304              :     conf: &'static PageServerConf,
     305              :     tenant_manager: Arc<TenantManager>,
     306              :     auth: Option<Arc<SwappableJwtAuth>>,
     307              :     socket: tokio::net::TcpStream,
     308              :     auth_type: AuthType,
     309              :     tls_config: Option<Arc<rustls::ServerConfig>>,
     310              :     pipelining_config: PageServicePipeliningConfig,
     311              :     feature_resolver: FeatureResolver,
     312              :     connection_ctx: RequestContext,
     313              :     cancel: CancellationToken,
     314              :     gate_guard: GateGuard,
     315              : ) -> ConnectionHandlerResult {
     316              :     let _guard = LIVE_CONNECTIONS
     317              :         .with_label_values(&["page_service"])
     318              :         .guard();
     319              : 
     320              :     socket
     321              :         .set_nodelay(true)
     322              :         .context("could not set TCP_NODELAY")?;
     323              : 
     324              :     let socket_fd = socket.as_raw_fd();
     325              : 
     326              :     let peer_addr = socket.peer_addr().context("get peer address")?;
     327              : 
     328              :     let perf_span_fields = ConnectionPerfSpanFields {
     329              :         peer_addr: peer_addr.to_string(),
     330              :         application_name: None, // filled in later
     331              :         compute_mode: None,     // filled in later
     332              :     };
     333              :     tracing::Span::current().record("peer_addr", field::display(peer_addr));
     334              : 
     335              :     // setup read timeout of 10 minutes. the timeout is rather arbitrary for requirements:
     336              :     // - long enough for most valid compute connections
     337              :     // - less than infinite to stop us from "leaking" connections to long-gone computes
     338              :     //
     339              :     // no write timeout is used, because the kernel is assumed to error writes after some time.
     340              :     let mut socket = tokio_io_timeout::TimeoutReader::new(socket);
     341              : 
     342              :     let default_timeout_ms = 10 * 60 * 1000; // 10 minutes by default
     343            0 :     let socket_timeout_ms = (|| {
     344            0 :         fail::fail_point!("simulated-bad-compute-connection", |avg_timeout_ms| {
     345              :             // Exponential distribution for simulating
     346              :             // poor network conditions, expect about avg_timeout_ms to be around 15
     347              :             // in tests
     348            0 :             if let Some(avg_timeout_ms) = avg_timeout_ms {
     349            0 :                 let avg = avg_timeout_ms.parse::<i64>().unwrap() as f32;
     350            0 :                 let u = rand::random::<f32>();
     351            0 :                 ((1.0 - u).ln() / (-avg)) as u64
     352              :             } else {
     353            0 :                 default_timeout_ms
     354              :             }
     355            0 :         });
     356            0 :         default_timeout_ms
     357              :     })();
     358              : 
     359              :     // A timeout here does not mean the client died, it can happen if it's just idle for
     360              :     // a while: we will tear down this PageServerHandler and instantiate a new one if/when
     361              :     // they reconnect.
     362              :     socket.set_timeout(Some(std::time::Duration::from_millis(socket_timeout_ms)));
     363              :     let socket = Box::pin(socket);
     364              : 
     365              :     fail::fail_point!("ps::connection-start::pre-login");
     366              : 
     367              :     // XXX: pgbackend.run() should take the connection_ctx,
     368              :     // and create a child per-query context when it invokes process_query.
     369              :     // But it's in a shared crate, so, we store connection_ctx inside PageServerHandler
     370              :     // and create the per-query context in process_query ourselves.
     371              :     let mut conn_handler = PageServerHandler::new(
     372              :         tenant_manager,
     373              :         auth,
     374              :         pipelining_config,
     375              :         conf.get_vectored_concurrent_io,
     376              :         perf_span_fields,
     377              :         connection_ctx,
     378              :         cancel.clone(),
     379              :         feature_resolver.clone(),
     380              :         gate_guard,
     381              :     );
     382              :     let pgbackend =
     383              :         PostgresBackend::new_from_io(socket_fd, socket, peer_addr, auth_type, tls_config)?;
     384              : 
     385              :     match pgbackend.run(&mut conn_handler, &cancel).await {
     386              :         Ok(()) => {
     387              :             // we've been requested to shut down
     388              :             Ok(())
     389              :         }
     390              :         Err(QueryError::Disconnected(ConnectionError::Io(io_error))) => {
     391              :             if is_expected_io_error(&io_error) {
     392              :                 info!("Postgres client disconnected ({io_error})");
     393              :                 Ok(())
     394              :             } else {
     395              :                 let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
     396              :                 Err(io_error).context(format!(
     397              :                     "Postgres connection error for tenant_id={tenant_id:?} client at peer_addr={peer_addr}"
     398              :                 ))
     399              :             }
     400              :         }
     401              :         other => {
     402              :             let tenant_id = conn_handler.timeline_handles.as_ref().unwrap().tenant_id();
     403              :             other.context(format!(
     404              :                 "Postgres query error for tenant_id={tenant_id:?} client peer_addr={peer_addr}"
     405              :             ))
     406              :         }
     407              :     }
     408              : }
     409              : 
     410              : /// Page service connection handler.
     411              : struct PageServerHandler {
     412              :     auth: Option<Arc<SwappableJwtAuth>>,
     413              :     claims: Option<Claims>,
     414              : 
     415              :     /// The context created for the lifetime of the connection
     416              :     /// services by this PageServerHandler.
     417              :     /// For each query received over the connection,
     418              :     /// `process_query` creates a child context from this one.
     419              :     connection_ctx: RequestContext,
     420              : 
     421              :     perf_span_fields: ConnectionPerfSpanFields,
     422              : 
     423              :     cancel: CancellationToken,
     424              : 
     425              :     /// None only while pagestream protocol is being processed.
     426              :     timeline_handles: Option<TimelineHandles>,
     427              : 
     428              :     pipelining_config: PageServicePipeliningConfig,
     429              :     get_vectored_concurrent_io: GetVectoredConcurrentIo,
     430              : 
     431              :     feature_resolver: FeatureResolver,
     432              : 
     433              :     gate_guard: GateGuard,
     434              : }
     435              : 
     436              : struct TimelineHandles {
     437              :     wrapper: TenantManagerWrapper,
     438              :     /// Note on size: the typical size of this map is 1.  The largest size we expect
     439              :     /// to see is the number of shards divided by the number of pageservers (typically < 2),
     440              :     /// or the ratio used when splitting shards (i.e. how many children created from one)
     441              :     /// parent shard, where a "large" number might be ~8.
     442              :     handles: timeline::handle::Cache<TenantManagerTypes>,
     443              : }
     444              : 
     445              : impl TimelineHandles {
     446            0 :     fn new(tenant_manager: Arc<TenantManager>) -> Self {
     447            0 :         Self {
     448            0 :             wrapper: TenantManagerWrapper {
     449            0 :                 tenant_manager,
     450            0 :                 tenant_id: OnceCell::new(),
     451            0 :             },
     452            0 :             handles: Default::default(),
     453            0 :         }
     454            0 :     }
     455            0 :     async fn get(
     456            0 :         &mut self,
     457            0 :         tenant_id: TenantId,
     458            0 :         timeline_id: TimelineId,
     459            0 :         shard_selector: ShardSelector,
     460            0 :     ) -> Result<Handle<TenantManagerTypes>, GetActiveTimelineError> {
     461            0 :         if *self.wrapper.tenant_id.get_or_init(|| tenant_id) != tenant_id {
     462            0 :             return Err(GetActiveTimelineError::Tenant(
     463            0 :                 GetActiveTenantError::SwitchedTenant,
     464            0 :             ));
     465            0 :         }
     466            0 :         self.handles
     467            0 :             .get(timeline_id, shard_selector, &self.wrapper)
     468            0 :             .await
     469            0 :     }
     470              : 
     471            0 :     fn tenant_id(&self) -> Option<TenantId> {
     472            0 :         self.wrapper.tenant_id.get().copied()
     473            0 :     }
     474              : }
     475              : 
     476              : pub(crate) struct TenantManagerWrapper {
     477              :     tenant_manager: Arc<TenantManager>,
     478              :     // We do not support switching tenant_id on a connection at this point.
     479              :     // We can can add support for this later if needed without changing
     480              :     // the protocol.
     481              :     tenant_id: once_cell::sync::OnceCell<TenantId>,
     482              : }
     483              : 
     484              : pub(crate) struct TenantManagerTypes;
     485              : 
     486              : impl timeline::handle::Types for TenantManagerTypes {
     487              :     type TenantManager = TenantManagerWrapper;
     488              :     type Timeline = TenantManagerCacheItem;
     489              : }
     490              : 
     491              : pub(crate) struct TenantManagerCacheItem {
     492              :     pub(crate) timeline: Arc<Timeline>,
     493              :     // allow() for cheap propagation through RequestContext inside a task
     494              :     #[allow(clippy::redundant_allocation)]
     495              :     pub(crate) metrics: Arc<Arc<TimelineMetrics>>,
     496              :     #[allow(dead_code)] // we store it to keep the gate open
     497              :     pub(crate) gate_guard: GateGuard,
     498              : }
     499              : 
     500              : impl std::ops::Deref for TenantManagerCacheItem {
     501              :     type Target = Arc<Timeline>;
     502            0 :     fn deref(&self) -> &Self::Target {
     503            0 :         &self.timeline
     504            0 :     }
     505              : }
     506              : 
     507              : impl timeline::handle::Timeline<TenantManagerTypes> for TenantManagerCacheItem {
     508            0 :     fn shard_timeline_id(&self) -> timeline::handle::ShardTimelineId {
     509            0 :         Timeline::shard_timeline_id(&self.timeline)
     510            0 :     }
     511              : 
     512            0 :     fn per_timeline_state(&self) -> &timeline::handle::PerTimelineState<TenantManagerTypes> {
     513            0 :         &self.timeline.handles
     514            0 :     }
     515              : 
     516            0 :     fn get_shard_identity(&self) -> &pageserver_api::shard::ShardIdentity {
     517            0 :         Timeline::get_shard_identity(&self.timeline)
     518            0 :     }
     519              : }
     520              : 
     521              : impl timeline::handle::TenantManager<TenantManagerTypes> for TenantManagerWrapper {
     522            0 :     async fn resolve(
     523            0 :         &self,
     524            0 :         timeline_id: TimelineId,
     525            0 :         shard_selector: ShardSelector,
     526            0 :     ) -> Result<TenantManagerCacheItem, GetActiveTimelineError> {
     527            0 :         let tenant_id = self.tenant_id.get().expect("we set this in get()");
     528            0 :         let timeout = ACTIVE_TENANT_TIMEOUT;
     529            0 :         let wait_start = Instant::now();
     530            0 :         let deadline = wait_start + timeout;
     531            0 :         let tenant_shard = loop {
     532            0 :             let resolved = self
     533            0 :                 .tenant_manager
     534            0 :                 .resolve_attached_shard(tenant_id, shard_selector);
     535            0 :             match resolved {
     536            0 :                 ShardResolveResult::Found(tenant_shard) => break tenant_shard,
     537              :                 ShardResolveResult::NotFound => {
     538            0 :                     MISROUTED_PAGESTREAM_REQUESTS.inc();
     539            0 :                     return Err(GetActiveTimelineError::Tenant(
     540            0 :                         GetActiveTenantError::NotFound(GetTenantError::NotFound(*tenant_id)),
     541            0 :                     ));
     542              :                 }
     543            0 :                 ShardResolveResult::InProgress(barrier) => {
     544              :                     // We can't authoritatively answer right now: wait for InProgress state
     545              :                     // to end, then try again
     546            0 :                     tokio::select! {
     547            0 :                         _  = barrier.wait() => {
     548            0 :                             // The barrier completed: proceed around the loop to try looking up again
     549            0 :                         },
     550            0 :                         _ = tokio::time::sleep(deadline.duration_since(Instant::now())) => {
     551            0 :                             return Err(GetActiveTimelineError::Tenant(GetActiveTenantError::WaitForActiveTimeout {
     552            0 :                                 latest_state: None,
     553            0 :                                 wait_time: timeout,
     554            0 :                             }));
     555              :                         }
     556              :                     }
     557              :                 }
     558              :             };
     559              :         };
     560              : 
     561            0 :         tracing::debug!("Waiting for tenant to enter active state...");
     562            0 :         tenant_shard
     563            0 :             .wait_to_become_active(deadline.duration_since(Instant::now()))
     564            0 :             .await
     565            0 :             .map_err(GetActiveTimelineError::Tenant)?;
     566              : 
     567            0 :         let timeline = tenant_shard
     568            0 :             .get_timeline(timeline_id, true)
     569            0 :             .map_err(GetActiveTimelineError::Timeline)?;
     570              : 
     571            0 :         let gate_guard = match timeline.gate.enter() {
     572            0 :             Ok(guard) => guard,
     573              :             Err(_) => {
     574            0 :                 return Err(GetActiveTimelineError::Timeline(
     575            0 :                     GetTimelineError::ShuttingDown,
     576            0 :                 ));
     577              :             }
     578              :         };
     579              : 
     580            0 :         let metrics = Arc::new(Arc::clone(&timeline.metrics));
     581              : 
     582            0 :         Ok(TenantManagerCacheItem {
     583            0 :             timeline,
     584            0 :             metrics,
     585            0 :             gate_guard,
     586            0 :         })
     587            0 :     }
     588              : }
     589              : 
     590              : /// Whether to hold the applied GC cutoff guard when processing GetPage requests.
     591              : /// This is determined once at the start of pagestream subprotocol handling based on
     592              : /// feature flags, configuration, and test conditions.
     593              : #[derive(Debug, Clone, Copy)]
     594              : enum HoldAppliedGcCutoffGuard {
     595              :     Yes,
     596              :     No,
     597              : }
     598              : 
     599              : #[derive(thiserror::Error, Debug)]
     600              : enum PageStreamError {
     601              :     /// We encountered an error that should prompt the client to reconnect:
     602              :     /// in practice this means we drop the connection without sending a response.
     603              :     #[error("Reconnect required: {0}")]
     604              :     Reconnect(Cow<'static, str>),
     605              : 
     606              :     /// We were instructed to shutdown while processing the query
     607              :     #[error("Shutting down")]
     608              :     Shutdown,
     609              : 
     610              :     /// Something went wrong reading a page: this likely indicates a pageserver bug
     611              :     #[error("Read error")]
     612              :     Read(#[source] PageReconstructError),
     613              : 
     614              :     /// Ran out of time waiting for an LSN
     615              :     #[error("LSN timeout: {0}")]
     616              :     LsnTimeout(WaitLsnError),
     617              : 
     618              :     /// The entity required to serve the request (tenant or timeline) is not found,
     619              :     /// or is not found in a suitable state to serve a request.
     620              :     #[error("Not found: {0}")]
     621              :     NotFound(Cow<'static, str>),
     622              : 
     623              :     /// Request asked for something that doesn't make sense, like an invalid LSN
     624              :     #[error("Bad request: {0}")]
     625              :     BadRequest(Cow<'static, str>),
     626              : }
     627              : 
     628              : impl From<PageStreamError> for tonic::Status {
     629            0 :     fn from(err: PageStreamError) -> Self {
     630              :         use tonic::Code;
     631            0 :         let message = err.to_string();
     632            0 :         let code = match err {
     633            0 :             PageStreamError::Reconnect(_) => Code::Unavailable,
     634            0 :             PageStreamError::Shutdown => Code::Unavailable,
     635            0 :             PageStreamError::Read(err) => match err {
     636            0 :                 PageReconstructError::Cancelled => Code::Unavailable,
     637            0 :                 PageReconstructError::MissingKey(_) => Code::NotFound,
     638            0 :                 PageReconstructError::AncestorLsnTimeout(err) => tonic::Status::from(err).code(),
     639            0 :                 PageReconstructError::Other(_) => Code::Internal,
     640            0 :                 PageReconstructError::WalRedo(_) => Code::Internal,
     641              :             },
     642            0 :             PageStreamError::LsnTimeout(err) => tonic::Status::from(err).code(),
     643            0 :             PageStreamError::NotFound(_) => Code::NotFound,
     644            0 :             PageStreamError::BadRequest(_) => Code::InvalidArgument,
     645              :         };
     646            0 :         tonic::Status::new(code, message)
     647            0 :     }
     648              : }
     649              : 
     650              : impl From<PageReconstructError> for PageStreamError {
     651            0 :     fn from(value: PageReconstructError) -> Self {
     652            0 :         match value {
     653            0 :             PageReconstructError::Cancelled => Self::Shutdown,
     654            0 :             e => Self::Read(e),
     655              :         }
     656            0 :     }
     657              : }
     658              : 
     659              : impl From<GetActiveTimelineError> for PageStreamError {
     660            0 :     fn from(value: GetActiveTimelineError) -> Self {
     661            0 :         match value {
     662              :             GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled)
     663              :             | GetActiveTimelineError::Tenant(GetActiveTenantError::WillNotBecomeActive(
     664              :                 TenantState::Stopping { .. },
     665              :             ))
     666            0 :             | GetActiveTimelineError::Timeline(GetTimelineError::ShuttingDown) => Self::Shutdown,
     667            0 :             GetActiveTimelineError::Tenant(e) => Self::NotFound(format!("{e}").into()),
     668            0 :             GetActiveTimelineError::Timeline(e) => Self::NotFound(format!("{e}").into()),
     669              :         }
     670            0 :     }
     671              : }
     672              : 
     673              : impl From<WaitLsnError> for PageStreamError {
     674            0 :     fn from(value: WaitLsnError) -> Self {
     675            0 :         match value {
     676            0 :             e @ WaitLsnError::Timeout(_) => Self::LsnTimeout(e),
     677            0 :             WaitLsnError::Shutdown => Self::Shutdown,
     678            0 :             e @ WaitLsnError::BadState { .. } => Self::Reconnect(format!("{e}").into()),
     679              :         }
     680            0 :     }
     681              : }
     682              : 
     683              : impl From<WaitLsnError> for QueryError {
     684            0 :     fn from(value: WaitLsnError) -> Self {
     685            0 :         match value {
     686            0 :             e @ WaitLsnError::Timeout(_) => Self::Other(anyhow::Error::new(e)),
     687            0 :             WaitLsnError::Shutdown => Self::Shutdown,
     688            0 :             WaitLsnError::BadState { .. } => Self::Reconnect,
     689              :         }
     690            0 :     }
     691              : }
     692              : 
     693              : #[derive(thiserror::Error, Debug)]
     694              : struct BatchedPageStreamError {
     695              :     req: PagestreamRequest,
     696              :     err: PageStreamError,
     697              : }
     698              : 
     699              : impl std::fmt::Display for BatchedPageStreamError {
     700            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     701            0 :         self.err.fmt(f)
     702            0 :     }
     703              : }
     704              : 
     705              : struct BatchedGetPageRequest {
     706              :     req: PagestreamGetPageRequest,
     707              :     timer: SmgrOpTimer,
     708              :     lsn_range: LsnRange,
     709              :     ctx: RequestContext,
     710              :     // If the request is perf enabled, this contains a context
     711              :     // with a perf span tracking the time spent waiting for the executor.
     712              :     batch_wait_ctx: Option<RequestContext>,
     713              : }
     714              : 
     715              : #[cfg(feature = "testing")]
     716              : struct BatchedTestRequest {
     717              :     req: pagestream_api::PagestreamTestRequest,
     718              :     timer: SmgrOpTimer,
     719              : }
     720              : 
     721              : /// NB: we only hold [`timeline::handle::WeakHandle`] inside this enum,
     722              : /// so that we don't keep the [`Timeline::gate`] open while the batch
     723              : /// is being built up inside the [`spsc_fold`] (pagestream pipelining).
     724              : #[derive(IntoStaticStr)]
     725              : #[allow(clippy::large_enum_variant)]
     726              : enum BatchedFeMessage {
     727              :     Exists {
     728              :         span: Span,
     729              :         timer: SmgrOpTimer,
     730              :         shard: WeakHandle<TenantManagerTypes>,
     731              :         req: PagestreamExistsRequest,
     732              :     },
     733              :     Nblocks {
     734              :         span: Span,
     735              :         timer: SmgrOpTimer,
     736              :         shard: WeakHandle<TenantManagerTypes>,
     737              :         req: PagestreamNblocksRequest,
     738              :     },
     739              :     GetPage {
     740              :         span: Span,
     741              :         shard: WeakHandle<TenantManagerTypes>,
     742              :         applied_gc_cutoff_guard: Option<RcuReadGuard<Lsn>>,
     743              :         pages: SmallVec<[BatchedGetPageRequest; 1]>,
     744              :         batch_break_reason: GetPageBatchBreakReason,
     745              :     },
     746              :     DbSize {
     747              :         span: Span,
     748              :         timer: SmgrOpTimer,
     749              :         shard: WeakHandle<TenantManagerTypes>,
     750              :         req: PagestreamDbSizeRequest,
     751              :     },
     752              :     GetSlruSegment {
     753              :         span: Span,
     754              :         timer: SmgrOpTimer,
     755              :         shard: WeakHandle<TenantManagerTypes>,
     756              :         req: PagestreamGetSlruSegmentRequest,
     757              :     },
     758              :     #[cfg(feature = "testing")]
     759              :     Test {
     760              :         span: Span,
     761              :         shard: WeakHandle<TenantManagerTypes>,
     762              :         requests: Vec<BatchedTestRequest>,
     763              :     },
     764              :     RespondError {
     765              :         span: Span,
     766              :         error: BatchedPageStreamError,
     767              :     },
     768              : }
     769              : 
     770              : impl BatchedFeMessage {
     771            0 :     fn as_static_str(&self) -> &'static str {
     772            0 :         self.into()
     773            0 :     }
     774              : 
     775            0 :     fn observe_execution_start(&mut self, at: Instant) {
     776            0 :         match self {
     777            0 :             BatchedFeMessage::Exists { timer, .. }
     778            0 :             | BatchedFeMessage::Nblocks { timer, .. }
     779            0 :             | BatchedFeMessage::DbSize { timer, .. }
     780            0 :             | BatchedFeMessage::GetSlruSegment { timer, .. } => {
     781            0 :                 timer.observe_execution_start(at);
     782            0 :             }
     783            0 :             BatchedFeMessage::GetPage { pages, .. } => {
     784            0 :                 for page in pages {
     785            0 :                     page.timer.observe_execution_start(at);
     786            0 :                 }
     787              :             }
     788              :             #[cfg(feature = "testing")]
     789            0 :             BatchedFeMessage::Test { requests, .. } => {
     790            0 :                 for req in requests {
     791            0 :                     req.timer.observe_execution_start(at);
     792            0 :                 }
     793              :             }
     794            0 :             BatchedFeMessage::RespondError { .. } => {}
     795              :         }
     796            0 :     }
     797              : 
     798            0 :     fn should_break_batch(
     799            0 :         &self,
     800            0 :         other: &BatchedFeMessage,
     801            0 :         max_batch_size: NonZeroUsize,
     802            0 :         batching_strategy: PageServiceProtocolPipelinedBatchingStrategy,
     803            0 :     ) -> Option<GetPageBatchBreakReason> {
     804            0 :         match (self, other) {
     805              :             (
     806              :                 BatchedFeMessage::GetPage {
     807            0 :                     shard: accum_shard,
     808            0 :                     pages: accum_pages,
     809              :                     ..
     810              :                 },
     811              :                 BatchedFeMessage::GetPage {
     812            0 :                     shard: this_shard,
     813            0 :                     pages: this_pages,
     814              :                     ..
     815              :                 },
     816              :             ) => {
     817            0 :                 assert_eq!(this_pages.len(), 1);
     818            0 :                 if accum_pages.len() >= max_batch_size.get() {
     819            0 :                     trace!(%max_batch_size, "stopping batching because of batch size");
     820            0 :                     assert_eq!(accum_pages.len(), max_batch_size.get());
     821              : 
     822            0 :                     return Some(GetPageBatchBreakReason::BatchFull);
     823            0 :                 }
     824            0 :                 if !accum_shard.is_same_handle_as(this_shard) {
     825            0 :                     trace!("stopping batching because timeline object mismatch");
     826              :                     // TODO: we _could_ batch & execute each shard seperately (and in parallel).
     827              :                     // But the current logic for keeping responses in order does not support that.
     828              : 
     829            0 :                     return Some(GetPageBatchBreakReason::NonUniformTimeline);
     830            0 :                 }
     831              : 
     832            0 :                 match batching_strategy {
     833              :                     PageServiceProtocolPipelinedBatchingStrategy::UniformLsn => {
     834            0 :                         if let Some(last_in_batch) = accum_pages.last() {
     835            0 :                             if last_in_batch.lsn_range.effective_lsn
     836            0 :                                 != this_pages[0].lsn_range.effective_lsn
     837              :                             {
     838            0 :                                 trace!(
     839              :                                     accum_lsn = %last_in_batch.lsn_range.effective_lsn,
     840            0 :                                     this_lsn = %this_pages[0].lsn_range.effective_lsn,
     841            0 :                                     "stopping batching because LSN changed"
     842              :                                 );
     843              : 
     844            0 :                                 return Some(GetPageBatchBreakReason::NonUniformLsn);
     845            0 :                             }
     846            0 :                         }
     847              :                     }
     848              :                     PageServiceProtocolPipelinedBatchingStrategy::ScatteredLsn => {
     849              :                         // The read path doesn't curently support serving the same page at different LSNs.
     850              :                         // While technically possible, it's uncertain if the complexity is worth it.
     851              :                         // Break the batch if such a case is encountered.
     852            0 :                         let same_page_different_lsn = accum_pages.iter().any(|batched| {
     853            0 :                             batched.req.rel == this_pages[0].req.rel
     854            0 :                                 && batched.req.blkno == this_pages[0].req.blkno
     855            0 :                                 && batched.lsn_range.effective_lsn
     856            0 :                                     != this_pages[0].lsn_range.effective_lsn
     857            0 :                         });
     858              : 
     859            0 :                         if same_page_different_lsn {
     860            0 :                             trace!(
     861            0 :                                 rel=%this_pages[0].req.rel,
     862            0 :                                 blkno=%this_pages[0].req.blkno,
     863            0 :                                 lsn=%this_pages[0].lsn_range.effective_lsn,
     864            0 :                                 "stopping batching because same page was requested at different LSNs"
     865              :                             );
     866              : 
     867            0 :                             return Some(GetPageBatchBreakReason::SamePageAtDifferentLsn);
     868            0 :                         }
     869              :                     }
     870              :                 }
     871              : 
     872            0 :                 None
     873              :             }
     874              :             #[cfg(feature = "testing")]
     875              :             (
     876              :                 BatchedFeMessage::Test {
     877            0 :                     shard: accum_shard,
     878            0 :                     requests: accum_requests,
     879              :                     ..
     880              :                 },
     881              :                 BatchedFeMessage::Test {
     882            0 :                     shard: this_shard,
     883            0 :                     requests: this_requests,
     884              :                     ..
     885              :                 },
     886              :             ) => {
     887            0 :                 assert!(this_requests.len() == 1);
     888            0 :                 if accum_requests.len() >= max_batch_size.get() {
     889            0 :                     trace!(%max_batch_size, "stopping batching because of batch size");
     890            0 :                     assert_eq!(accum_requests.len(), max_batch_size.get());
     891            0 :                     return Some(GetPageBatchBreakReason::BatchFull);
     892            0 :                 }
     893            0 :                 if !accum_shard.is_same_handle_as(this_shard) {
     894            0 :                     trace!("stopping batching because timeline object mismatch");
     895              :                     // TODO: we _could_ batch & execute each shard seperately (and in parallel).
     896              :                     // But the current logic for keeping responses in order does not support that.
     897            0 :                     return Some(GetPageBatchBreakReason::NonUniformTimeline);
     898            0 :                 }
     899            0 :                 let this_batch_key = this_requests[0].req.batch_key;
     900            0 :                 let accum_batch_key = accum_requests[0].req.batch_key;
     901            0 :                 if this_requests[0].req.batch_key != accum_requests[0].req.batch_key {
     902            0 :                     trace!(%accum_batch_key, %this_batch_key, "stopping batching because batch key changed");
     903            0 :                     return Some(GetPageBatchBreakReason::NonUniformKey);
     904            0 :                 }
     905            0 :                 None
     906              :             }
     907            0 :             (_, _) => Some(GetPageBatchBreakReason::NonBatchableRequest),
     908              :         }
     909            0 :     }
     910              : }
     911              : 
     912              : impl PageServerHandler {
     913              :     #[allow(clippy::too_many_arguments)]
     914            0 :     pub fn new(
     915            0 :         tenant_manager: Arc<TenantManager>,
     916            0 :         auth: Option<Arc<SwappableJwtAuth>>,
     917            0 :         pipelining_config: PageServicePipeliningConfig,
     918            0 :         get_vectored_concurrent_io: GetVectoredConcurrentIo,
     919            0 :         perf_span_fields: ConnectionPerfSpanFields,
     920            0 :         connection_ctx: RequestContext,
     921            0 :         cancel: CancellationToken,
     922            0 :         feature_resolver: FeatureResolver,
     923            0 :         gate_guard: GateGuard,
     924            0 :     ) -> Self {
     925            0 :         PageServerHandler {
     926            0 :             auth,
     927            0 :             claims: None,
     928            0 :             connection_ctx,
     929            0 :             perf_span_fields,
     930            0 :             timeline_handles: Some(TimelineHandles::new(tenant_manager)),
     931            0 :             cancel,
     932            0 :             pipelining_config,
     933            0 :             get_vectored_concurrent_io,
     934            0 :             feature_resolver,
     935            0 :             gate_guard,
     936            0 :         }
     937            0 :     }
     938              : 
     939              :     /// This function always respects cancellation of any timeline in `[Self::shard_timelines]`.  Pass in
     940              :     /// a cancellation token at the next scope up (such as a tenant cancellation token) to ensure we respect
     941              :     /// cancellation if there aren't any timelines in the cache.
     942              :     ///
     943              :     /// If calling from a function that doesn't use the `[Self::shard_timelines]` cache, then pass in the
     944              :     /// timeline cancellation token.
     945            0 :     async fn flush_cancellable<IO>(
     946            0 :         &self,
     947            0 :         pgb: &mut PostgresBackend<IO>,
     948            0 :         cancel: &CancellationToken,
     949            0 :     ) -> Result<(), QueryError>
     950            0 :     where
     951            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
     952            0 :     {
     953            0 :         tokio::select!(
     954            0 :             flush_r = pgb.flush() => {
     955            0 :                 Ok(flush_r?)
     956              :             },
     957            0 :             _ = cancel.cancelled() => {
     958            0 :                 Err(QueryError::Shutdown)
     959              :             }
     960              :         )
     961            0 :     }
     962              : 
     963              :     #[allow(clippy::too_many_arguments)]
     964            0 :     async fn pagestream_read_message<IO>(
     965            0 :         pgb: &mut PostgresBackendReader<IO>,
     966            0 :         tenant_id: TenantId,
     967            0 :         timeline_id: TimelineId,
     968            0 :         timeline_handles: &mut TimelineHandles,
     969            0 :         conn_perf_span_fields: &ConnectionPerfSpanFields,
     970            0 :         cancel: &CancellationToken,
     971            0 :         ctx: &RequestContext,
     972            0 :         protocol_version: PagestreamProtocolVersion,
     973            0 :         parent_span: Span,
     974            0 :         hold_gc_cutoff_guard: HoldAppliedGcCutoffGuard,
     975            0 :     ) -> Result<Option<BatchedFeMessage>, QueryError>
     976            0 :     where
     977            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
     978            0 :     {
     979            0 :         let msg = tokio::select! {
     980              :             biased;
     981            0 :             _ = cancel.cancelled() => {
     982            0 :                 return Err(QueryError::Shutdown)
     983              :             }
     984            0 :             msg = pgb.read_message() => { msg }
     985              :         };
     986              : 
     987            0 :         let received_at = Instant::now();
     988              : 
     989            0 :         let copy_data_bytes = match msg? {
     990            0 :             Some(FeMessage::CopyData(bytes)) => bytes,
     991              :             Some(FeMessage::Terminate) => {
     992            0 :                 return Ok(None);
     993              :             }
     994            0 :             Some(m) => {
     995            0 :                 return Err(QueryError::Other(anyhow::anyhow!(
     996            0 :                     "unexpected message: {m:?} during COPY"
     997            0 :                 )));
     998              :             }
     999              :             None => {
    1000            0 :                 return Ok(None);
    1001              :             } // client disconnected
    1002              :         };
    1003            0 :         trace!("query: {copy_data_bytes:?}");
    1004              : 
    1005            0 :         fail::fail_point!("ps::handle-pagerequest-message");
    1006              : 
    1007              :         // parse request
    1008            0 :         let neon_fe_msg =
    1009            0 :             PagestreamFeMessage::parse(&mut copy_data_bytes.reader(), protocol_version)?;
    1010              : 
    1011            0 :         let batched_msg = match neon_fe_msg {
    1012            0 :             PagestreamFeMessage::Exists(req) => {
    1013            0 :                 let shard = timeline_handles
    1014            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
    1015            0 :                     .await?;
    1016            0 :                 debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    1017            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());
    1018            0 :                 let timer = Self::record_op_start_and_throttle(
    1019            0 :                     &shard,
    1020            0 :                     metrics::SmgrQueryType::GetRelExists,
    1021            0 :                     received_at,
    1022            0 :                 )
    1023            0 :                 .await?;
    1024            0 :                 BatchedFeMessage::Exists {
    1025            0 :                     span,
    1026            0 :                     timer,
    1027            0 :                     shard: shard.downgrade(),
    1028            0 :                     req,
    1029            0 :                 }
    1030              :             }
    1031            0 :             PagestreamFeMessage::Nblocks(req) => {
    1032            0 :                 let shard = timeline_handles
    1033            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
    1034            0 :                     .await?;
    1035            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());
    1036            0 :                 let timer = Self::record_op_start_and_throttle(
    1037            0 :                     &shard,
    1038            0 :                     metrics::SmgrQueryType::GetRelSize,
    1039            0 :                     received_at,
    1040            0 :                 )
    1041            0 :                 .await?;
    1042            0 :                 BatchedFeMessage::Nblocks {
    1043            0 :                     span,
    1044            0 :                     timer,
    1045            0 :                     shard: shard.downgrade(),
    1046            0 :                     req,
    1047            0 :                 }
    1048              :             }
    1049            0 :             PagestreamFeMessage::DbSize(req) => {
    1050            0 :                 let shard = timeline_handles
    1051            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
    1052            0 :                     .await?;
    1053            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());
    1054            0 :                 let timer = Self::record_op_start_and_throttle(
    1055            0 :                     &shard,
    1056            0 :                     metrics::SmgrQueryType::GetDbSize,
    1057            0 :                     received_at,
    1058            0 :                 )
    1059            0 :                 .await?;
    1060            0 :                 BatchedFeMessage::DbSize {
    1061            0 :                     span,
    1062            0 :                     timer,
    1063            0 :                     shard: shard.downgrade(),
    1064            0 :                     req,
    1065            0 :                 }
    1066              :             }
    1067            0 :             PagestreamFeMessage::GetSlruSegment(req) => {
    1068            0 :                 let shard = timeline_handles
    1069            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
    1070            0 :                     .await?;
    1071            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());
    1072            0 :                 let timer = Self::record_op_start_and_throttle(
    1073            0 :                     &shard,
    1074            0 :                     metrics::SmgrQueryType::GetSlruSegment,
    1075            0 :                     received_at,
    1076            0 :                 )
    1077            0 :                 .await?;
    1078            0 :                 BatchedFeMessage::GetSlruSegment {
    1079            0 :                     span,
    1080            0 :                     timer,
    1081            0 :                     shard: shard.downgrade(),
    1082            0 :                     req,
    1083            0 :                 }
    1084              :             }
    1085            0 :             PagestreamFeMessage::GetPage(req) => {
    1086              :                 // avoid a somewhat costly Span::record() by constructing the entire span in one go.
    1087              :                 macro_rules! mkspan {
    1088              :                     (before shard routing) => {{
    1089              :                         tracing::info_span!(
    1090              :                             parent: &parent_span,
    1091              :                             "handle_get_page_request",
    1092              :                             request_id = %req.hdr.reqid,
    1093              :                             rel = %req.rel,
    1094              :                             blkno = %req.blkno,
    1095              :                             req_lsn = %req.hdr.request_lsn,
    1096              :                             not_modified_since_lsn = %req.hdr.not_modified_since,
    1097              :                         )
    1098              :                     }};
    1099              :                     ($shard_id:expr) => {{
    1100              :                         tracing::info_span!(
    1101              :                             parent: &parent_span,
    1102              :                             "handle_get_page_request",
    1103              :                             request_id = %req.hdr.reqid,
    1104              :                             rel = %req.rel,
    1105              :                             blkno = %req.blkno,
    1106              :                             req_lsn = %req.hdr.request_lsn,
    1107              :                             not_modified_since_lsn = %req.hdr.not_modified_since,
    1108              :                             shard_id = %$shard_id,
    1109              :                         )
    1110              :                     }};
    1111              :                 }
    1112              : 
    1113              :                 macro_rules! respond_error {
    1114              :                     ($span:expr, $error:expr) => {{
    1115              :                         let error = BatchedFeMessage::RespondError {
    1116              :                             span: $span,
    1117              :                             error: BatchedPageStreamError {
    1118              :                                 req: req.hdr,
    1119              :                                 err: $error,
    1120              :                             },
    1121              :                         };
    1122              :                         Ok(Some(error))
    1123              :                     }};
    1124              :                 }
    1125              : 
    1126            0 :                 let key = rel_block_to_key(req.rel, req.blkno);
    1127              : 
    1128            0 :                 let res = timeline_handles
    1129            0 :                     .get(tenant_id, timeline_id, ShardSelector::Page(key))
    1130            0 :                     .await;
    1131              : 
    1132            0 :                 let shard = match res {
    1133            0 :                     Ok(tl) => tl,
    1134            0 :                     Err(e) => {
    1135            0 :                         let span = mkspan!(before shard routing);
    1136            0 :                         match e {
    1137              :                             GetActiveTimelineError::Tenant(GetActiveTenantError::NotFound(_)) => {
    1138              :                                 // We already know this tenant exists in general, because we resolved it at
    1139              :                                 // start of connection.  Getting a NotFound here indicates that the shard containing
    1140              :                                 // the requested page is not present on this node: the client's knowledge of shard->pageserver
    1141              :                                 // mapping is out of date.
    1142              :                                 //
    1143              :                                 // Closing the connection by returning ``::Reconnect` has the side effect of rate-limiting above message, via
    1144              :                                 // client's reconnect backoff, as well as hopefully prompting the client to load its updated configuration
    1145              :                                 // and talk to a different pageserver.
    1146            0 :                                 MISROUTED_PAGESTREAM_REQUESTS.inc();
    1147            0 :                                 return respond_error!(
    1148            0 :                                     span,
    1149            0 :                                     PageStreamError::Reconnect(
    1150            0 :                                         "getpage@lsn request routed to wrong shard".into()
    1151            0 :                                     )
    1152              :                                 );
    1153              :                             }
    1154            0 :                             e => {
    1155            0 :                                 return respond_error!(span, e.into());
    1156              :                             }
    1157              :                         }
    1158              :                     }
    1159              :                 };
    1160              : 
    1161            0 :                 let ctx = if shard.is_get_page_request_sampled() {
    1162            0 :                     RequestContextBuilder::from(ctx)
    1163            0 :                         .root_perf_span(|| {
    1164            0 :                             info_span!(
    1165              :                             target: PERF_TRACE_TARGET,
    1166              :                             "GET_PAGE",
    1167              :                             peer_addr = conn_perf_span_fields.peer_addr,
    1168              :                             application_name = conn_perf_span_fields.application_name,
    1169              :                             compute_mode = conn_perf_span_fields.compute_mode,
    1170              :                             tenant_id = %tenant_id,
    1171            0 :                             shard_id = %shard.get_shard_identity().shard_slug(),
    1172              :                             timeline_id = %timeline_id,
    1173              :                             lsn = %req.hdr.request_lsn,
    1174              :                             not_modified_since_lsn = %req.hdr.not_modified_since,
    1175              :                             request_id = %req.hdr.reqid,
    1176              :                             key = %key,
    1177              :                             )
    1178            0 :                         })
    1179            0 :                         .attached_child()
    1180              :                 } else {
    1181            0 :                     ctx.attached_child()
    1182              :                 };
    1183              : 
    1184              :                 // This ctx travels as part of the BatchedFeMessage through
    1185              :                 // batching into the request handler.
    1186              :                 // The request handler needs to do some per-request work
    1187              :                 // (relsize check) before dispatching the batch as a single
    1188              :                 // get_vectored call to the Timeline.
    1189              :                 // This ctx will be used for the reslize check, whereas the
    1190              :                 // get_vectored call will be a different ctx with separate
    1191              :                 // perf span.
    1192            0 :                 let ctx = ctx.with_scope_page_service_pagestream(&shard);
    1193              : 
    1194              :                 // Similar game for this `span`: we funnel it through so that
    1195              :                 // request handler log messages contain the request-specific fields.
    1196            0 :                 let span = mkspan!(shard.tenant_shard_id.shard_slug());
    1197              : 
    1198            0 :                 let timer = Self::record_op_start_and_throttle(
    1199            0 :                     &shard,
    1200            0 :                     metrics::SmgrQueryType::GetPageAtLsn,
    1201            0 :                     received_at,
    1202              :                 )
    1203            0 :                 .maybe_perf_instrument(&ctx, |current_perf_span| {
    1204            0 :                     info_span!(
    1205              :                         target: PERF_TRACE_TARGET,
    1206            0 :                         parent: current_perf_span,
    1207              :                         "THROTTLE",
    1208              :                     )
    1209            0 :                 })
    1210            0 :                 .await?;
    1211              : 
    1212            0 :                 let applied_gc_cutoff_guard = shard.get_applied_gc_cutoff_lsn(); // hold guard
    1213              :                 // We're holding the Handle
    1214            0 :                 let effective_lsn = match Self::effective_request_lsn(
    1215            0 :                     &shard,
    1216            0 :                     shard.get_last_record_lsn(),
    1217            0 :                     req.hdr.request_lsn,
    1218            0 :                     req.hdr.not_modified_since,
    1219            0 :                     &applied_gc_cutoff_guard,
    1220            0 :                 ) {
    1221            0 :                     Ok(lsn) => lsn,
    1222            0 :                     Err(e) => {
    1223            0 :                         return respond_error!(span, e);
    1224              :                     }
    1225              :                 };
    1226            0 :                 let applied_gc_cutoff_guard = match hold_gc_cutoff_guard {
    1227            0 :                     HoldAppliedGcCutoffGuard::Yes => Some(applied_gc_cutoff_guard),
    1228              :                     HoldAppliedGcCutoffGuard::No => {
    1229            0 :                         drop(applied_gc_cutoff_guard);
    1230            0 :                         None
    1231              :                     }
    1232              :                 };
    1233              : 
    1234            0 :                 let batch_wait_ctx = if ctx.has_perf_span() {
    1235              :                     Some(
    1236            0 :                         RequestContextBuilder::from(&ctx)
    1237            0 :                             .perf_span(|crnt_perf_span| {
    1238            0 :                                 info_span!(
    1239              :                                     target: PERF_TRACE_TARGET,
    1240            0 :                                     parent: crnt_perf_span,
    1241              :                                     "WAIT_EXECUTOR",
    1242              :                                 )
    1243            0 :                             })
    1244            0 :                             .attached_child(),
    1245              :                     )
    1246              :                 } else {
    1247            0 :                     None
    1248              :                 };
    1249              : 
    1250              :                 BatchedFeMessage::GetPage {
    1251            0 :                     span,
    1252            0 :                     shard: shard.downgrade(),
    1253            0 :                     applied_gc_cutoff_guard,
    1254            0 :                     pages: smallvec![BatchedGetPageRequest {
    1255            0 :                         req,
    1256            0 :                         timer,
    1257            0 :                         lsn_range: LsnRange {
    1258            0 :                             effective_lsn,
    1259            0 :                             request_lsn: req.hdr.request_lsn
    1260            0 :                         },
    1261            0 :                         ctx,
    1262            0 :                         batch_wait_ctx,
    1263            0 :                     }],
    1264              :                     // The executor grabs the batch when it becomes idle.
    1265              :                     // Hence, [`GetPageBatchBreakReason::ExecutorSteal`] is the
    1266              :                     // default reason for breaking the batch.
    1267            0 :                     batch_break_reason: GetPageBatchBreakReason::ExecutorSteal,
    1268              :                 }
    1269              :             }
    1270              :             #[cfg(feature = "testing")]
    1271            0 :             PagestreamFeMessage::Test(req) => {
    1272            0 :                 let shard = timeline_handles
    1273            0 :                     .get(tenant_id, timeline_id, ShardSelector::Zero)
    1274            0 :                     .await?;
    1275            0 :                 let span = tracing::info_span!(parent: &parent_span, "handle_test_request", shard_id = %shard.tenant_shard_id.shard_slug());
    1276            0 :                 let timer = Self::record_op_start_and_throttle(
    1277            0 :                     &shard,
    1278            0 :                     metrics::SmgrQueryType::Test,
    1279            0 :                     received_at,
    1280            0 :                 )
    1281            0 :                 .await?;
    1282            0 :                 BatchedFeMessage::Test {
    1283            0 :                     span,
    1284            0 :                     shard: shard.downgrade(),
    1285            0 :                     requests: vec![BatchedTestRequest { req, timer }],
    1286            0 :                 }
    1287              :             }
    1288              :         };
    1289            0 :         Ok(Some(batched_msg))
    1290            0 :     }
    1291              : 
    1292              :     /// Starts a SmgrOpTimer at received_at and throttles the request.
    1293            0 :     async fn record_op_start_and_throttle(
    1294            0 :         shard: &Handle<TenantManagerTypes>,
    1295            0 :         op: metrics::SmgrQueryType,
    1296            0 :         received_at: Instant,
    1297            0 :     ) -> Result<SmgrOpTimer, QueryError> {
    1298              :         // It's important to start the smgr op metric recorder as early as possible
    1299              :         // so that the _started counters are incremented before we do
    1300              :         // any serious waiting, e.g., for throttle, batching, or actual request handling.
    1301            0 :         let mut timer = shard.query_metrics.start_smgr_op(op, received_at);
    1302            0 :         let now = Instant::now();
    1303            0 :         timer.observe_throttle_start(now);
    1304            0 :         let throttled = tokio::select! {
    1305            0 :             res = shard.pagestream_throttle.throttle(1, now) => res,
    1306            0 :             _ = shard.cancel.cancelled() => return Err(QueryError::Shutdown),
    1307              :         };
    1308            0 :         timer.observe_throttle_done(throttled);
    1309            0 :         Ok(timer)
    1310            0 :     }
    1311              : 
    1312              :     /// Post-condition: `batch` is Some()
    1313              :     #[instrument(skip_all, level = tracing::Level::TRACE)]
    1314              :     #[allow(clippy::boxed_local)]
    1315              :     fn pagestream_do_batch(
    1316              :         batching_strategy: PageServiceProtocolPipelinedBatchingStrategy,
    1317              :         max_batch_size: NonZeroUsize,
    1318              :         batch: &mut Result<BatchedFeMessage, QueryError>,
    1319              :         this_msg: Result<BatchedFeMessage, QueryError>,
    1320              :     ) -> Result<(), Result<BatchedFeMessage, QueryError>> {
    1321              :         debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    1322              : 
    1323              :         let this_msg = match this_msg {
    1324              :             Ok(this_msg) => this_msg,
    1325              :             Err(e) => return Err(Err(e)),
    1326              :         };
    1327              : 
    1328              :         let eligible_batch = match batch {
    1329              :             Ok(b) => b,
    1330              :             Err(_) => {
    1331              :                 return Err(Ok(this_msg));
    1332              :             }
    1333              :         };
    1334              : 
    1335              :         let batch_break =
    1336              :             eligible_batch.should_break_batch(&this_msg, max_batch_size, batching_strategy);
    1337              : 
    1338              :         match batch_break {
    1339              :             Some(reason) => {
    1340              :                 if let BatchedFeMessage::GetPage {
    1341              :                     batch_break_reason, ..
    1342              :                 } = eligible_batch
    1343              :                 {
    1344              :                     *batch_break_reason = reason;
    1345              :                 }
    1346              : 
    1347              :                 Err(Ok(this_msg))
    1348              :             }
    1349              :             None => {
    1350              :                 // ok to batch
    1351              :                 match (eligible_batch, this_msg) {
    1352              :                     (
    1353              :                         BatchedFeMessage::GetPage {
    1354              :                             pages: accum_pages,
    1355              :                             applied_gc_cutoff_guard: accum_applied_gc_cutoff_guard,
    1356              :                             ..
    1357              :                         },
    1358              :                         BatchedFeMessage::GetPage {
    1359              :                             pages: this_pages,
    1360              :                             applied_gc_cutoff_guard: this_applied_gc_cutoff_guard,
    1361              :                             ..
    1362              :                         },
    1363              :                     ) => {
    1364              :                         accum_pages.extend(this_pages);
    1365              :                         // the minimum of the two guards will keep data for both alive
    1366              :                         match (&accum_applied_gc_cutoff_guard, this_applied_gc_cutoff_guard) {
    1367              :                             (None, None) => (),
    1368              :                             (None, Some(this)) => *accum_applied_gc_cutoff_guard = Some(this),
    1369              :                             (Some(_), None) => (),
    1370              :                             (Some(accum), Some(this)) => {
    1371              :                                 if **accum > *this {
    1372              :                                     *accum_applied_gc_cutoff_guard = Some(this);
    1373              :                                 }
    1374              :                             }
    1375              :                         };
    1376              :                         Ok(())
    1377              :                     }
    1378              :                     #[cfg(feature = "testing")]
    1379              :                     (
    1380              :                         BatchedFeMessage::Test {
    1381              :                             requests: accum_requests,
    1382              :                             ..
    1383              :                         },
    1384              :                         BatchedFeMessage::Test {
    1385              :                             requests: this_requests,
    1386              :                             ..
    1387              :                         },
    1388              :                     ) => {
    1389              :                         accum_requests.extend(this_requests);
    1390              :                         Ok(())
    1391              :                     }
    1392              :                     // Shape guaranteed by [`BatchedFeMessage::should_break_batch`]
    1393              :                     _ => unreachable!(),
    1394              :                 }
    1395              :             }
    1396              :         }
    1397              :     }
    1398              : 
    1399            0 :     #[instrument(level = tracing::Level::DEBUG, skip_all)]
    1400              :     async fn pagestream_handle_batched_message<IO>(
    1401              :         &mut self,
    1402              :         pgb_writer: &mut PostgresBackend<IO>,
    1403              :         batch: BatchedFeMessage,
    1404              :         io_concurrency: IoConcurrency,
    1405              :         cancel: &CancellationToken,
    1406              :         protocol_version: PagestreamProtocolVersion,
    1407              :         ctx: &RequestContext,
    1408              :     ) -> Result<(), QueryError>
    1409              :     where
    1410              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
    1411              :     {
    1412              :         let started_at = Instant::now();
    1413              :         let batch = {
    1414              :             let mut batch = batch;
    1415              :             batch.observe_execution_start(started_at);
    1416              :             batch
    1417              :         };
    1418              : 
    1419              :         // Dispatch the batch to the appropriate request handler.
    1420              :         let log_slow_name = batch.as_static_str();
    1421              :         let (mut handler_results, span) = {
    1422              :             // TODO: we unfortunately have to pin the future on the heap, since GetPage futures are huge and
    1423              :             // won't fit on the stack.
    1424              :             let mut boxpinned = Box::pin(Self::pagestream_dispatch_batched_message(
    1425              :                 batch,
    1426              :                 io_concurrency,
    1427              :                 ctx,
    1428              :             ));
    1429              :             log_slow(
    1430              :                 log_slow_name,
    1431              :                 LOG_SLOW_GETPAGE_THRESHOLD,
    1432              :                 boxpinned.as_mut(),
    1433              :             )
    1434              :             .await?
    1435              :         };
    1436              : 
    1437              :         // We purposefully don't count flush time into the smgr operation timer.
    1438              :         //
    1439              :         // The reason is that current compute client will not perform protocol processing
    1440              :         // if the postgres backend process is doing things other than `->smgr_read()`.
    1441              :         // This is especially the case for prefetch.
    1442              :         //
    1443              :         // If the compute doesn't read from the connection, eventually TCP will backpressure
    1444              :         // all the way into our flush call below.
    1445              :         //
    1446              :         // The timer's underlying metric is used for a storage-internal latency SLO and
    1447              :         // we don't want to include latency in it that we can't control.
    1448              :         // And as pointed out above, in this case, we don't control the time that flush will take.
    1449              :         //
    1450              :         // We put each response in the batch onto the wire in a separate pgb_writer.flush()
    1451              :         // call, which (all unmeasured) adds syscall overhead but reduces time to first byte
    1452              :         // and avoids building up a "giant" contiguous userspace buffer to hold the entire response.
    1453              :         // TODO: vectored socket IO would be great, but pgb_writer doesn't support that.
    1454              :         let flush_timers = {
    1455              :             let flushing_start_time = Instant::now();
    1456              :             let mut flush_timers = Vec::with_capacity(handler_results.len());
    1457              :             for handler_result in &mut handler_results {
    1458              :                 let flush_timer = match handler_result {
    1459              :                     Ok((_response, timer, _ctx)) => Some(
    1460              :                         timer
    1461              :                             .observe_execution_end(flushing_start_time)
    1462              :                             .expect("we are the first caller"),
    1463              :                     ),
    1464              :                     Err(_) => {
    1465              :                         // TODO: measure errors
    1466              :                         None
    1467              :                     }
    1468              :                 };
    1469              :                 flush_timers.push(flush_timer);
    1470              :             }
    1471              :             assert_eq!(flush_timers.len(), handler_results.len());
    1472              :             flush_timers
    1473              :         };
    1474              : 
    1475              :         // Map handler result to protocol behavior.
    1476              :         // Some handler errors cause exit from pagestream protocol.
    1477              :         // Other handler errors are sent back as an error message and we stay in pagestream protocol.
    1478              :         for (handler_result, flushing_timer) in handler_results.into_iter().zip(flush_timers) {
    1479              :             let (response_msg, ctx) = match handler_result {
    1480              :                 Err(e) => match &e.err {
    1481              :                     PageStreamError::Shutdown => {
    1482              :                         // BEGIN HADRON
    1483              :                         PAGESTREAM_HANDLER_RESULTS_TOTAL
    1484              :                             .with_label_values(&[metrics::PAGESTREAM_HANDLER_OUTCOME_OTHER_ERROR])
    1485              :                             .inc();
    1486              :                         // END HADRON
    1487              : 
    1488              :                         // If we fail to fulfil a request during shutdown, which may be _because_ of
    1489              :                         // shutdown, then do not send the error to the client.  Instead just drop the
    1490              :                         // connection.
    1491            0 :                         span.in_scope(|| info!("dropping connection due to shutdown"));
    1492              :                         return Err(QueryError::Shutdown);
    1493              :                     }
    1494              :                     PageStreamError::Reconnect(_reason) => {
    1495            0 :                         span.in_scope(|| {
    1496              :                             // BEGIN HADRON
    1497              :                             // We can get here because the compute node is pointing at the wrong PS. We
    1498              :                             // already have a metric to keep track of this so suppressing this log to
    1499              :                             // reduce log spam. The information in this log message is not going to be that
    1500              :                             // helpful given the volume of logs that can be generated.
    1501              :                             // info!("handler requested reconnect: {reason}")
    1502              :                             // END HADRON
    1503            0 :                         });
    1504              :                         // BEGIN HADRON
    1505              :                         PAGESTREAM_HANDLER_RESULTS_TOTAL
    1506              :                             .with_label_values(&[
    1507              :                                 metrics::PAGESTREAM_HANDLER_OUTCOME_INTERNAL_ERROR,
    1508              :                             ])
    1509              :                             .inc();
    1510              :                         // END HADRON
    1511              :                         return Err(QueryError::Reconnect);
    1512              :                     }
    1513              :                     PageStreamError::Read(_)
    1514              :                     | PageStreamError::LsnTimeout(_)
    1515              :                     | PageStreamError::NotFound(_)
    1516              :                     | PageStreamError::BadRequest(_) => {
    1517              :                         // BEGIN HADRON
    1518              :                         if let PageStreamError::Read(_) | PageStreamError::LsnTimeout(_) = &e.err {
    1519              :                             PAGESTREAM_HANDLER_RESULTS_TOTAL
    1520              :                                 .with_label_values(&[
    1521              :                                     metrics::PAGESTREAM_HANDLER_OUTCOME_INTERNAL_ERROR,
    1522              :                                 ])
    1523              :                                 .inc();
    1524              :                         } else {
    1525              :                             PAGESTREAM_HANDLER_RESULTS_TOTAL
    1526              :                                 .with_label_values(&[
    1527              :                                     metrics::PAGESTREAM_HANDLER_OUTCOME_OTHER_ERROR,
    1528              :                                 ])
    1529              :                                 .inc();
    1530              :                         }
    1531              :                         // END HADRON
    1532              : 
    1533              :                         // print the all details to the log with {:#}, but for the client the
    1534              :                         // error message is enough.  Do not log if shutting down, as the anyhow::Error
    1535              :                         // here includes cancellation which is not an error.
    1536              :                         let full = utils::error::report_compact_sources(&e.err);
    1537            0 :                         span.in_scope(|| {
    1538            0 :                             error!("error reading relation or page version: {full:#}")
    1539            0 :                         });
    1540              : 
    1541              :                         (
    1542              :                             PagestreamBeMessage::Error(PagestreamErrorResponse {
    1543              :                                 req: e.req,
    1544              :                                 message: e.err.to_string(),
    1545              :                             }),
    1546              :                             None,
    1547              :                         )
    1548              :                     }
    1549              :                 },
    1550              :                 Ok((response_msg, _op_timer_already_observed, ctx)) => {
    1551              :                     // BEGIN HADRON
    1552              :                     PAGESTREAM_HANDLER_RESULTS_TOTAL
    1553              :                         .with_label_values(&[metrics::PAGESTREAM_HANDLER_OUTCOME_SUCCESS])
    1554              :                         .inc();
    1555              :                     // END HADRON
    1556              : 
    1557              :                     (response_msg, Some(ctx))
    1558              :                 }
    1559              :             };
    1560              : 
    1561            0 :             let ctx = ctx.map(|req_ctx| {
    1562            0 :                 RequestContextBuilder::from(&req_ctx)
    1563            0 :                     .perf_span(|crnt_perf_span| {
    1564            0 :                         info_span!(
    1565              :                             target: PERF_TRACE_TARGET,
    1566            0 :                             parent: crnt_perf_span,
    1567              :                             "FLUSH_RESPONSE",
    1568              :                         )
    1569            0 :                     })
    1570            0 :                     .attached_child()
    1571            0 :             });
    1572              : 
    1573              :             //
    1574              :             // marshal & transmit response message
    1575              :             //
    1576              : 
    1577              :             pgb_writer.write_message_noflush(&BeMessage::CopyData(
    1578              :                 &response_msg.serialize(protocol_version),
    1579              :             ))?;
    1580              : 
    1581              :             failpoint_support::sleep_millis_async!("before-pagestream-msg-flush", cancel);
    1582              : 
    1583              :             // what we want to do
    1584              :             let socket_fd = pgb_writer.socket_fd;
    1585              :             let flush_fut = pgb_writer.flush();
    1586              :             // metric for how long flushing takes
    1587              :             let flush_fut = match flushing_timer {
    1588              :                 Some(flushing_timer) => futures::future::Either::Left(flushing_timer.measure(
    1589              :                     Instant::now(),
    1590              :                     flush_fut,
    1591              :                     socket_fd,
    1592              :                 )),
    1593              :                 None => futures::future::Either::Right(flush_fut),
    1594              :             };
    1595              : 
    1596              :             let flush_fut = if let Some(req_ctx) = ctx.as_ref() {
    1597              :                 futures::future::Either::Left(
    1598            0 :                     flush_fut.maybe_perf_instrument(req_ctx, |current_perf_span| {
    1599            0 :                         current_perf_span.clone()
    1600            0 :                     }),
    1601              :                 )
    1602              :             } else {
    1603              :                 futures::future::Either::Right(flush_fut)
    1604              :             };
    1605              : 
    1606              :             // do it while respecting cancellation
    1607            0 :             let _: () = async move {
    1608            0 :                 tokio::select! {
    1609              :                     biased;
    1610            0 :                     _ = cancel.cancelled() => {
    1611              :                         // We were requested to shut down.
    1612            0 :                         info!("shutdown request received in page handler");
    1613            0 :                         return Err(QueryError::Shutdown)
    1614              :                     }
    1615            0 :                     res = flush_fut => {
    1616            0 :                         res?;
    1617              :                     }
    1618              :                 }
    1619            0 :                 Ok(())
    1620            0 :             }
    1621              :             .await?;
    1622              :         }
    1623              :         Ok(())
    1624              :     }
    1625              : 
    1626              :     /// Helper which dispatches a batched message to the appropriate handler.
    1627              :     /// Returns a vec of results, along with the extracted trace span.
    1628            0 :     async fn pagestream_dispatch_batched_message(
    1629            0 :         batch: BatchedFeMessage,
    1630            0 :         io_concurrency: IoConcurrency,
    1631            0 :         ctx: &RequestContext,
    1632            0 :     ) -> Result<
    1633            0 :         (
    1634            0 :             Vec<Result<(PagestreamBeMessage, SmgrOpTimer, RequestContext), BatchedPageStreamError>>,
    1635            0 :             Span,
    1636            0 :         ),
    1637            0 :         QueryError,
    1638            0 :     > {
    1639              :         macro_rules! upgrade_handle_and_set_context {
    1640              :             ($shard:ident) => {{
    1641              :                 let weak_handle = &$shard;
    1642              :                 let handle = weak_handle.upgrade()?;
    1643              :                 let ctx = ctx.with_scope_page_service_pagestream(&handle);
    1644              :                 (handle, ctx)
    1645              :             }};
    1646              :         }
    1647            0 :         Ok(match batch {
    1648              :             BatchedFeMessage::Exists {
    1649            0 :                 span,
    1650            0 :                 timer,
    1651            0 :                 shard,
    1652            0 :                 req,
    1653              :             } => {
    1654            0 :                 fail::fail_point!("ps::handle-pagerequest-message::exists");
    1655            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1656              :                 (
    1657            0 :                     vec![
    1658            0 :                         Self::handle_get_rel_exists_request(&shard, &req, &ctx)
    1659            0 :                             .instrument(span.clone())
    1660            0 :                             .await
    1661            0 :                             .map(|msg| (PagestreamBeMessage::Exists(msg), timer, ctx))
    1662            0 :                             .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
    1663              :                     ],
    1664            0 :                     span,
    1665              :                 )
    1666              :             }
    1667              :             BatchedFeMessage::Nblocks {
    1668            0 :                 span,
    1669            0 :                 timer,
    1670            0 :                 shard,
    1671            0 :                 req,
    1672              :             } => {
    1673            0 :                 fail::fail_point!("ps::handle-pagerequest-message::nblocks");
    1674            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1675              :                 (
    1676            0 :                     vec![
    1677            0 :                         Self::handle_get_nblocks_request(&shard, &req, false, &ctx)
    1678            0 :                             .instrument(span.clone())
    1679            0 :                             .await
    1680            0 :                             .map(|msg| msg.expect("allow_missing=false"))
    1681            0 :                             .map(|msg| (PagestreamBeMessage::Nblocks(msg), timer, ctx))
    1682            0 :                             .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
    1683              :                     ],
    1684            0 :                     span,
    1685              :                 )
    1686              :             }
    1687              :             BatchedFeMessage::GetPage {
    1688            0 :                 span,
    1689            0 :                 shard,
    1690            0 :                 applied_gc_cutoff_guard,
    1691            0 :                 pages,
    1692            0 :                 batch_break_reason,
    1693              :             } => {
    1694            0 :                 fail::fail_point!("ps::handle-pagerequest-message::getpage");
    1695            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1696              :                 (
    1697              :                     {
    1698            0 :                         let npages = pages.len();
    1699            0 :                         trace!(npages, "handling getpage request");
    1700            0 :                         let res = Self::handle_get_page_at_lsn_request_batched(
    1701            0 :                             &shard,
    1702            0 :                             pages,
    1703            0 :                             io_concurrency,
    1704            0 :                             batch_break_reason,
    1705            0 :                             &ctx,
    1706            0 :                         )
    1707            0 :                         .instrument(span.clone())
    1708            0 :                         .await;
    1709            0 :                         assert_eq!(res.len(), npages);
    1710            0 :                         drop(applied_gc_cutoff_guard);
    1711            0 :                         res
    1712              :                     },
    1713            0 :                     span,
    1714              :                 )
    1715              :             }
    1716              :             BatchedFeMessage::DbSize {
    1717            0 :                 span,
    1718            0 :                 timer,
    1719            0 :                 shard,
    1720            0 :                 req,
    1721              :             } => {
    1722            0 :                 fail::fail_point!("ps::handle-pagerequest-message::dbsize");
    1723            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1724              :                 (
    1725            0 :                     vec![
    1726            0 :                         Self::handle_db_size_request(&shard, &req, &ctx)
    1727            0 :                             .instrument(span.clone())
    1728            0 :                             .await
    1729            0 :                             .map(|msg| (PagestreamBeMessage::DbSize(msg), timer, ctx))
    1730            0 :                             .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
    1731              :                     ],
    1732            0 :                     span,
    1733              :                 )
    1734              :             }
    1735              :             BatchedFeMessage::GetSlruSegment {
    1736            0 :                 span,
    1737            0 :                 timer,
    1738            0 :                 shard,
    1739            0 :                 req,
    1740              :             } => {
    1741            0 :                 fail::fail_point!("ps::handle-pagerequest-message::slrusegment");
    1742            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1743              :                 (
    1744            0 :                     vec![
    1745            0 :                         Self::handle_get_slru_segment_request(&shard, &req, &ctx)
    1746            0 :                             .instrument(span.clone())
    1747            0 :                             .await
    1748            0 :                             .map(|msg| (PagestreamBeMessage::GetSlruSegment(msg), timer, ctx))
    1749            0 :                             .map_err(|err| BatchedPageStreamError { err, req: req.hdr }),
    1750              :                     ],
    1751            0 :                     span,
    1752              :                 )
    1753              :             }
    1754              :             #[cfg(feature = "testing")]
    1755              :             BatchedFeMessage::Test {
    1756            0 :                 span,
    1757            0 :                 shard,
    1758            0 :                 requests,
    1759              :             } => {
    1760            0 :                 fail::fail_point!("ps::handle-pagerequest-message::test");
    1761            0 :                 let (shard, ctx) = upgrade_handle_and_set_context!(shard);
    1762              :                 (
    1763              :                     {
    1764            0 :                         let npages = requests.len();
    1765            0 :                         trace!(npages, "handling getpage request");
    1766            0 :                         let res = Self::handle_test_request_batch(&shard, requests, &ctx)
    1767            0 :                             .instrument(span.clone())
    1768            0 :                             .await;
    1769            0 :                         assert_eq!(res.len(), npages);
    1770            0 :                         res
    1771              :                     },
    1772            0 :                     span,
    1773              :                 )
    1774              :             }
    1775            0 :             BatchedFeMessage::RespondError { span, error } => {
    1776              :                 // We've already decided to respond with an error, so we don't need to
    1777              :                 // call the handler.
    1778            0 :                 (vec![Err(error)], span)
    1779              :             }
    1780              :         })
    1781            0 :     }
    1782              : 
    1783              :     /// Pagestream sub-protocol handler.
    1784              :     ///
    1785              :     /// It is a simple request-response protocol inside a COPYBOTH session.
    1786              :     ///
    1787              :     /// # Coding Discipline
    1788              :     ///
    1789              :     /// Coding discipline within this function: all interaction with the `pgb` connection
    1790              :     /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
    1791              :     /// This is so that we can shutdown page_service quickly.
    1792              :     #[instrument(skip_all, fields(hold_gc_cutoff_guard))]
    1793              :     async fn handle_pagerequests<IO>(
    1794              :         &mut self,
    1795              :         pgb: &mut PostgresBackend<IO>,
    1796              :         tenant_id: TenantId,
    1797              :         timeline_id: TimelineId,
    1798              :         protocol_version: PagestreamProtocolVersion,
    1799              :         ctx: RequestContext,
    1800              :     ) -> Result<(), QueryError>
    1801              :     where
    1802              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1803              :     {
    1804              :         debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    1805              : 
    1806              :         // switch client to COPYBOTH
    1807              :         pgb.write_message_noflush(&BeMessage::CopyBothResponse)?;
    1808              :         tokio::select! {
    1809              :             biased;
    1810              :             _ = self.cancel.cancelled() => {
    1811              :                 return Err(QueryError::Shutdown)
    1812              :             }
    1813              :             res = pgb.flush() => {
    1814              :                 res?;
    1815              :             }
    1816              :         }
    1817              : 
    1818              :         let io_concurrency = IoConcurrency::spawn_from_conf(
    1819              :             self.get_vectored_concurrent_io,
    1820              :             match self.gate_guard.try_clone() {
    1821              :                 Ok(guard) => guard,
    1822              :                 Err(_) => {
    1823              :                     info!("shutdown request received in page handler");
    1824              :                     return Err(QueryError::Shutdown);
    1825              :                 }
    1826              :             },
    1827              :         );
    1828              : 
    1829              :         let pgb_reader = pgb
    1830              :             .split()
    1831              :             .context("implementation error: split pgb into reader and writer")?;
    1832              : 
    1833              :         let timeline_handles = self
    1834              :             .timeline_handles
    1835              :             .take()
    1836              :             .expect("implementation error: timeline_handles should not be locked");
    1837              : 
    1838              :         // Evaluate the expensive feature resolver check once per pagestream subprotocol handling
    1839              :         // instead of once per GetPage request. This is shared between pipelined and serial paths.
    1840              :         let hold_gc_cutoff_guard = if cfg!(test) || cfg!(feature = "testing") {
    1841              :             HoldAppliedGcCutoffGuard::Yes
    1842              :         } else {
    1843              :             // Use the global feature resolver with the tenant ID directly, avoiding the need
    1844              :             // to get a timeline/shard which might not be available on this pageserver node.
    1845              :             let empty_properties = std::collections::HashMap::new();
    1846              :             match self.feature_resolver.evaluate_boolean(
    1847              :                 "page-service-getpage-hold-applied-gc-cutoff-guard",
    1848              :                 tenant_id,
    1849              :                 &empty_properties,
    1850              :             ) {
    1851              :                 Ok(()) => HoldAppliedGcCutoffGuard::Yes,
    1852              :                 Err(_) => HoldAppliedGcCutoffGuard::No,
    1853              :             }
    1854              :         };
    1855              :         // record it in the span of handle_pagerequests so that both the request_span
    1856              :         // and the pipeline implementation spans contains the field.
    1857              :         Span::current().record(
    1858              :             "hold_gc_cutoff_guard",
    1859              :             tracing::field::debug(&hold_gc_cutoff_guard),
    1860              :         );
    1861              : 
    1862              :         let request_span = info_span!("request");
    1863              :         let ((pgb_reader, timeline_handles), result) = match self.pipelining_config.clone() {
    1864              :             PageServicePipeliningConfig::Pipelined(pipelining_config) => {
    1865              :                 self.handle_pagerequests_pipelined(
    1866              :                     pgb,
    1867              :                     pgb_reader,
    1868              :                     tenant_id,
    1869              :                     timeline_id,
    1870              :                     timeline_handles,
    1871              :                     request_span,
    1872              :                     pipelining_config,
    1873              :                     protocol_version,
    1874              :                     io_concurrency,
    1875              :                     hold_gc_cutoff_guard,
    1876              :                     &ctx,
    1877              :                 )
    1878              :                 .await
    1879              :             }
    1880              :             PageServicePipeliningConfig::Serial => {
    1881              :                 self.handle_pagerequests_serial(
    1882              :                     pgb,
    1883              :                     pgb_reader,
    1884              :                     tenant_id,
    1885              :                     timeline_id,
    1886              :                     timeline_handles,
    1887              :                     request_span,
    1888              :                     protocol_version,
    1889              :                     io_concurrency,
    1890              :                     hold_gc_cutoff_guard,
    1891              :                     &ctx,
    1892              :                 )
    1893              :                 .await
    1894              :             }
    1895              :         };
    1896              : 
    1897              :         debug!("pagestream subprotocol shut down cleanly");
    1898              : 
    1899              :         pgb.unsplit(pgb_reader)
    1900              :             .context("implementation error: unsplit pgb")?;
    1901              : 
    1902              :         let replaced = self.timeline_handles.replace(timeline_handles);
    1903              :         assert!(replaced.is_none());
    1904              : 
    1905              :         result
    1906              :     }
    1907              : 
    1908              :     #[allow(clippy::too_many_arguments)]
    1909            0 :     async fn handle_pagerequests_serial<IO>(
    1910            0 :         &mut self,
    1911            0 :         pgb_writer: &mut PostgresBackend<IO>,
    1912            0 :         mut pgb_reader: PostgresBackendReader<IO>,
    1913            0 :         tenant_id: TenantId,
    1914            0 :         timeline_id: TimelineId,
    1915            0 :         mut timeline_handles: TimelineHandles,
    1916            0 :         request_span: Span,
    1917            0 :         protocol_version: PagestreamProtocolVersion,
    1918            0 :         io_concurrency: IoConcurrency,
    1919            0 :         hold_gc_cutoff_guard: HoldAppliedGcCutoffGuard,
    1920            0 :         ctx: &RequestContext,
    1921            0 :     ) -> (
    1922            0 :         (PostgresBackendReader<IO>, TimelineHandles),
    1923            0 :         Result<(), QueryError>,
    1924            0 :     )
    1925            0 :     where
    1926            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1927            0 :     {
    1928            0 :         let cancel = self.cancel.clone();
    1929              : 
    1930            0 :         let err = loop {
    1931            0 :             let msg = Self::pagestream_read_message(
    1932            0 :                 &mut pgb_reader,
    1933            0 :                 tenant_id,
    1934            0 :                 timeline_id,
    1935            0 :                 &mut timeline_handles,
    1936            0 :                 &self.perf_span_fields,
    1937            0 :                 &cancel,
    1938            0 :                 ctx,
    1939            0 :                 protocol_version,
    1940            0 :                 request_span.clone(),
    1941            0 :                 hold_gc_cutoff_guard,
    1942            0 :             )
    1943            0 :             .await;
    1944            0 :             let msg = match msg {
    1945            0 :                 Ok(msg) => msg,
    1946            0 :                 Err(e) => break e,
    1947              :             };
    1948            0 :             let msg = match msg {
    1949            0 :                 Some(msg) => msg,
    1950              :                 None => {
    1951            0 :                     debug!("pagestream subprotocol end observed");
    1952            0 :                     return ((pgb_reader, timeline_handles), Ok(()));
    1953              :                 }
    1954              :             };
    1955              : 
    1956            0 :             let result = self
    1957            0 :                 .pagestream_handle_batched_message(
    1958            0 :                     pgb_writer,
    1959            0 :                     msg,
    1960            0 :                     io_concurrency.clone(),
    1961            0 :                     &cancel,
    1962            0 :                     protocol_version,
    1963            0 :                     ctx,
    1964            0 :                 )
    1965            0 :                 .await;
    1966            0 :             match result {
    1967            0 :                 Ok(()) => {}
    1968            0 :                 Err(e) => break e,
    1969              :             }
    1970              :         };
    1971            0 :         ((pgb_reader, timeline_handles), Err(err))
    1972            0 :     }
    1973              : 
    1974              :     /// # Cancel-Safety
    1975              :     ///
    1976              :     /// May leak tokio tasks if not polled to completion.
    1977              :     #[allow(clippy::too_many_arguments)]
    1978            0 :     async fn handle_pagerequests_pipelined<IO>(
    1979            0 :         &mut self,
    1980            0 :         pgb_writer: &mut PostgresBackend<IO>,
    1981            0 :         pgb_reader: PostgresBackendReader<IO>,
    1982            0 :         tenant_id: TenantId,
    1983            0 :         timeline_id: TimelineId,
    1984            0 :         mut timeline_handles: TimelineHandles,
    1985            0 :         request_span: Span,
    1986            0 :         pipelining_config: PageServicePipeliningConfigPipelined,
    1987            0 :         protocol_version: PagestreamProtocolVersion,
    1988            0 :         io_concurrency: IoConcurrency,
    1989            0 :         hold_gc_cutoff_guard: HoldAppliedGcCutoffGuard,
    1990            0 :         ctx: &RequestContext,
    1991            0 :     ) -> (
    1992            0 :         (PostgresBackendReader<IO>, TimelineHandles),
    1993            0 :         Result<(), QueryError>,
    1994            0 :     )
    1995            0 :     where
    1996            0 :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    1997            0 :     {
    1998              :         //
    1999              :         // Pipelined pagestream handling consists of
    2000              :         // - a Batcher that reads requests off the wire and
    2001              :         //   and batches them if possible,
    2002              :         // - an Executor that processes the batched requests.
    2003              :         //
    2004              :         // The batch is built up inside an `spsc_fold` channel,
    2005              :         // shared betwen Batcher (Sender) and Executor (Receiver).
    2006              :         //
    2007              :         // The Batcher continously folds client requests into the batch,
    2008              :         // while the Executor can at any time take out what's in the batch
    2009              :         // in order to process it.
    2010              :         // This means the next batch builds up while the Executor
    2011              :         // executes the last batch.
    2012              :         //
    2013              :         // CANCELLATION
    2014              :         //
    2015              :         // We run both Batcher and Executor futures to completion before
    2016              :         // returning from this function.
    2017              :         //
    2018              :         // If Executor exits first, it signals cancellation to the Batcher
    2019              :         // via a CancellationToken that is child of `self.cancel`.
    2020              :         // If Batcher exits first, it signals cancellation to the Executor
    2021              :         // by dropping the spsc_fold channel Sender.
    2022              :         //
    2023              :         // CLEAN SHUTDOWN
    2024              :         //
    2025              :         // Clean shutdown means that the client ends the COPYBOTH session.
    2026              :         // In response to such a client message, the Batcher exits.
    2027              :         // The Executor continues to run, draining the spsc_fold channel.
    2028              :         // Once drained, the spsc_fold recv will fail with a distinct error
    2029              :         // indicating that the sender disconnected.
    2030              :         // The Executor exits with Ok(()) in response to that error.
    2031              :         //
    2032              :         // Server initiated shutdown is not clean shutdown, but instead
    2033              :         // is an error Err(QueryError::Shutdown) that is propagated through
    2034              :         // error propagation.
    2035              :         //
    2036              :         // ERROR PROPAGATION
    2037              :         //
    2038              :         // When the Batcher encounter an error, it sends it as a value
    2039              :         // through the spsc_fold channel and exits afterwards.
    2040              :         // When the Executor observes such an error in the channel,
    2041              :         // it exits returning that error value.
    2042              :         //
    2043              :         // This design ensures that the Executor stage will still process
    2044              :         // the batch that was in flight when the Batcher encountered an error,
    2045              :         // thereby beahving identical to a serial implementation.
    2046              : 
    2047              :         let PageServicePipeliningConfigPipelined {
    2048            0 :             max_batch_size,
    2049            0 :             execution,
    2050            0 :             batching: batching_strategy,
    2051            0 :         } = pipelining_config;
    2052              : 
    2053              :         // Macro to _define_ a pipeline stage.
    2054              :         macro_rules! pipeline_stage {
    2055              :             ($name:literal, $cancel:expr, $make_fut:expr) => {{
    2056              :                 let cancel: CancellationToken = $cancel;
    2057              :                 let stage_fut = $make_fut(cancel.clone());
    2058            0 :                 async move {
    2059            0 :                     scopeguard::defer! {
    2060              :                         debug!("exiting");
    2061              :                     }
    2062            0 :                     timed_after_cancellation(stage_fut, $name, Duration::from_millis(100), &cancel)
    2063            0 :                         .await
    2064            0 :                 }
    2065              :                 .instrument(tracing::info_span!($name))
    2066              :             }};
    2067              :         }
    2068              : 
    2069              :         //
    2070              :         // Batcher
    2071              :         //
    2072              : 
    2073            0 :         let perf_span_fields = self.perf_span_fields.clone();
    2074              : 
    2075            0 :         let cancel_batcher = self.cancel.child_token();
    2076            0 :         let (mut batch_tx, mut batch_rx) = spsc_fold::channel();
    2077            0 :         let batcher = pipeline_stage!("batcher", cancel_batcher.clone(), move |cancel_batcher| {
    2078            0 :             let ctx = ctx.attached_child();
    2079            0 :             async move {
    2080            0 :                 let mut pgb_reader = pgb_reader;
    2081            0 :                 let mut exit = false;
    2082            0 :                 while !exit {
    2083            0 :                     let read_res = Self::pagestream_read_message(
    2084            0 :                         &mut pgb_reader,
    2085            0 :                         tenant_id,
    2086            0 :                         timeline_id,
    2087            0 :                         &mut timeline_handles,
    2088            0 :                         &perf_span_fields,
    2089            0 :                         &cancel_batcher,
    2090            0 :                         &ctx,
    2091            0 :                         protocol_version,
    2092            0 :                         request_span.clone(),
    2093            0 :                         hold_gc_cutoff_guard,
    2094            0 :                     )
    2095            0 :                     .await;
    2096            0 :                     let Some(read_res) = read_res.transpose() else {
    2097            0 :                         debug!("client-initiated shutdown");
    2098            0 :                         break;
    2099              :                     };
    2100            0 :                     exit |= read_res.is_err();
    2101            0 :                     let could_send = batch_tx
    2102            0 :                         .send(read_res, |batch, res| {
    2103            0 :                             Self::pagestream_do_batch(batching_strategy, max_batch_size, batch, res)
    2104            0 :                         })
    2105            0 :                         .await;
    2106            0 :                     exit |= could_send.is_err();
    2107              :                 }
    2108            0 :                 (pgb_reader, timeline_handles)
    2109            0 :             }
    2110            0 :         });
    2111              : 
    2112              :         //
    2113              :         // Executor
    2114              :         //
    2115              : 
    2116            0 :         let executor = pipeline_stage!("executor", self.cancel.clone(), move |cancel| {
    2117            0 :             let ctx = ctx.attached_child();
    2118            0 :             async move {
    2119            0 :                 let _cancel_batcher = cancel_batcher.drop_guard();
    2120              :                 loop {
    2121            0 :                     let maybe_batch = batch_rx.recv().await;
    2122            0 :                     let batch = match maybe_batch {
    2123            0 :                         Ok(batch) => batch,
    2124              :                         Err(spsc_fold::RecvError::SenderGone) => {
    2125            0 :                             debug!("upstream gone");
    2126            0 :                             return Ok(());
    2127              :                         }
    2128              :                     };
    2129            0 :                     let mut batch = match batch {
    2130            0 :                         Ok(batch) => batch,
    2131            0 :                         Err(e) => {
    2132            0 :                             return Err(e);
    2133              :                         }
    2134              :                     };
    2135              : 
    2136              :                     if let BatchedFeMessage::GetPage {
    2137            0 :                         pages,
    2138              :                         span: _,
    2139              :                         shard: _,
    2140              :                         applied_gc_cutoff_guard: _,
    2141              :                         batch_break_reason: _,
    2142            0 :                     } = &mut batch
    2143              :                     {
    2144            0 :                         for req in pages {
    2145            0 :                             req.batch_wait_ctx.take();
    2146            0 :                         }
    2147            0 :                     }
    2148              : 
    2149            0 :                     self.pagestream_handle_batched_message(
    2150            0 :                         pgb_writer,
    2151            0 :                         batch,
    2152            0 :                         io_concurrency.clone(),
    2153            0 :                         &cancel,
    2154            0 :                         protocol_version,
    2155            0 :                         &ctx,
    2156            0 :                     )
    2157            0 :                     .await?;
    2158              :                 }
    2159            0 :             }
    2160            0 :         });
    2161              : 
    2162              :         //
    2163              :         // Execute the stages.
    2164              :         //
    2165              : 
    2166            0 :         match execution {
    2167              :             PageServiceProtocolPipelinedExecutionStrategy::ConcurrentFutures => {
    2168            0 :                 tokio::join!(batcher, executor)
    2169              :             }
    2170              :             PageServiceProtocolPipelinedExecutionStrategy::Tasks => {
    2171              :                 // These tasks are not tracked anywhere.
    2172            0 :                 let read_messages_task = tokio::spawn(batcher);
    2173            0 :                 let (read_messages_task_res, executor_res_) =
    2174            0 :                     tokio::join!(read_messages_task, executor,);
    2175            0 :                 (
    2176            0 :                     read_messages_task_res.expect("propagated panic from read_messages"),
    2177            0 :                     executor_res_,
    2178            0 :                 )
    2179              :             }
    2180              :         }
    2181            0 :     }
    2182              : 
    2183              :     /// Helper function to handle the LSN from client request.
    2184              :     ///
    2185              :     /// Each GetPage (and Exists and Nblocks) request includes information about
    2186              :     /// which version of the page is being requested. The primary compute node
    2187              :     /// will always request the latest page version, by setting 'request_lsn' to
    2188              :     /// the last inserted or flushed WAL position, while a standby will request
    2189              :     /// a version at the LSN that it's currently caught up to.
    2190              :     ///
    2191              :     /// In either case, if the page server hasn't received the WAL up to the
    2192              :     /// requested LSN yet, we will wait for it to arrive. The return value is
    2193              :     /// the LSN that should be used to look up the page versions.
    2194              :     ///
    2195              :     /// In addition to the request LSN, each request carries another LSN,
    2196              :     /// 'not_modified_since', which is a hint to the pageserver that the client
    2197              :     /// knows that the page has not been modified between 'not_modified_since'
    2198              :     /// and the request LSN. This allows skipping the wait, as long as the WAL
    2199              :     /// up to 'not_modified_since' has arrived. If the client doesn't have any
    2200              :     /// information about when the page was modified, it will use
    2201              :     /// not_modified_since == lsn. If the client lies and sends a too low
    2202              :     /// not_modified_hint such that there are in fact later page versions, the
    2203              :     /// behavior is undefined: the pageserver may return any of the page versions
    2204              :     /// or an error.
    2205            0 :     async fn wait_or_get_last_lsn(
    2206            0 :         timeline: &Timeline,
    2207            0 :         request_lsn: Lsn,
    2208            0 :         not_modified_since: Lsn,
    2209            0 :         latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
    2210            0 :         ctx: &RequestContext,
    2211            0 :     ) -> Result<Lsn, PageStreamError> {
    2212            0 :         let last_record_lsn = timeline.get_last_record_lsn();
    2213            0 :         let effective_request_lsn = Self::effective_request_lsn(
    2214            0 :             timeline,
    2215            0 :             last_record_lsn,
    2216            0 :             request_lsn,
    2217            0 :             not_modified_since,
    2218            0 :             latest_gc_cutoff_lsn,
    2219            0 :         )?;
    2220              : 
    2221            0 :         if effective_request_lsn > last_record_lsn {
    2222            0 :             timeline
    2223            0 :                 .wait_lsn(
    2224            0 :                     not_modified_since,
    2225            0 :                     crate::tenant::timeline::WaitLsnWaiter::PageService,
    2226            0 :                     timeline::WaitLsnTimeout::Default,
    2227            0 :                     ctx,
    2228            0 :                 )
    2229            0 :                 .await?;
    2230              : 
    2231              :             // Since we waited for 'effective_request_lsn' to arrive, that is now the last
    2232              :             // record LSN. (Or close enough for our purposes; the last-record LSN can
    2233              :             // advance immediately after we return anyway)
    2234            0 :         }
    2235              : 
    2236            0 :         Ok(effective_request_lsn)
    2237            0 :     }
    2238              : 
    2239            0 :     fn effective_request_lsn(
    2240            0 :         timeline: &Timeline,
    2241            0 :         last_record_lsn: Lsn,
    2242            0 :         request_lsn: Lsn,
    2243            0 :         not_modified_since: Lsn,
    2244            0 :         latest_gc_cutoff_lsn: &RcuReadGuard<Lsn>,
    2245            0 :     ) -> Result<Lsn, PageStreamError> {
    2246              :         // Sanity check the request
    2247            0 :         if request_lsn < not_modified_since {
    2248            0 :             return Err(PageStreamError::BadRequest(
    2249            0 :                 format!(
    2250            0 :                     "invalid request with request LSN {request_lsn} and not_modified_since {not_modified_since}",
    2251            0 :                 )
    2252            0 :                 .into(),
    2253            0 :             ));
    2254            0 :         }
    2255              : 
    2256              :         // Check explicitly for INVALID just to get a less scary error message if the request is obviously bogus
    2257            0 :         if request_lsn == Lsn::INVALID {
    2258            0 :             return Err(PageStreamError::BadRequest(
    2259            0 :                 "invalid LSN(0) in request".into(),
    2260            0 :             ));
    2261            0 :         }
    2262              : 
    2263              :         // Clients should only read from recent LSNs on their timeline, or from locations holding an LSN lease.
    2264              :         //
    2265              :         // We may have older data available, but we make a best effort to detect this case and return an error,
    2266              :         // to distinguish a misbehaving client (asking for old LSN) from a storage issue (data missing at a legitimate LSN).
    2267            0 :         if request_lsn < **latest_gc_cutoff_lsn && !timeline.is_gc_blocked_by_lsn_lease_deadline() {
    2268            0 :             let gc_info = &timeline.gc_info.read().unwrap();
    2269            0 :             if !gc_info.lsn_covered_by_lease(request_lsn) {
    2270            0 :                 return Err(
    2271            0 :                     PageStreamError::BadRequest(format!(
    2272            0 :                         "tried to request a page version that was garbage collected. requested at {} gc cutoff {}",
    2273            0 :                         request_lsn, **latest_gc_cutoff_lsn
    2274            0 :                     ).into())
    2275            0 :                 );
    2276            0 :             }
    2277            0 :         }
    2278              : 
    2279            0 :         if not_modified_since > last_record_lsn {
    2280            0 :             Ok(not_modified_since)
    2281              :         } else {
    2282              :             // It might be better to use max(not_modified_since, latest_gc_cutoff_lsn)
    2283              :             // here instead. That would give the same result, since we know that there
    2284              :             // haven't been any modifications since 'not_modified_since'. Using an older
    2285              :             // LSN might be faster, because that could allow skipping recent layers when
    2286              :             // finding the page. However, we have historically used 'last_record_lsn', so
    2287              :             // stick to that for now.
    2288            0 :             Ok(std::cmp::min(last_record_lsn, request_lsn))
    2289              :         }
    2290            0 :     }
    2291              : 
    2292              :     /// Handles the lsn lease request.
    2293              :     /// If a lease cannot be obtained, the client will receive NULL.
    2294              :     #[instrument(skip_all, fields(shard_id, %lsn))]
    2295              :     async fn handle_make_lsn_lease<IO>(
    2296              :         &mut self,
    2297              :         pgb: &mut PostgresBackend<IO>,
    2298              :         tenant_shard_id: TenantShardId,
    2299              :         timeline_id: TimelineId,
    2300              :         lsn: Lsn,
    2301              :         ctx: &RequestContext,
    2302              :     ) -> Result<(), QueryError>
    2303              :     where
    2304              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
    2305              :     {
    2306              :         let timeline = self
    2307              :             .timeline_handles
    2308              :             .as_mut()
    2309              :             .unwrap()
    2310              :             .get(
    2311              :                 tenant_shard_id.tenant_id,
    2312              :                 timeline_id,
    2313              :                 ShardSelector::Known(tenant_shard_id.to_index()),
    2314              :             )
    2315              :             .await?;
    2316              :         set_tracing_field_shard_id(&timeline);
    2317              : 
    2318              :         let lease = timeline
    2319              :             .renew_lsn_lease(lsn, timeline.get_lsn_lease_length(), ctx)
    2320            0 :             .inspect_err(|e| {
    2321            0 :                 warn!("{e}");
    2322            0 :             })
    2323              :             .ok();
    2324            0 :         let valid_until_str = lease.map(|l| {
    2325            0 :             l.valid_until
    2326            0 :                 .duration_since(SystemTime::UNIX_EPOCH)
    2327            0 :                 .expect("valid_until is earlier than UNIX_EPOCH")
    2328            0 :                 .as_millis()
    2329            0 :                 .to_string()
    2330            0 :         });
    2331              : 
    2332              :         info!(
    2333              :             "acquired lease for {} until {}",
    2334              :             lsn,
    2335              :             valid_until_str.as_deref().unwrap_or("<unknown>")
    2336              :         );
    2337              : 
    2338            0 :         let bytes = valid_until_str.as_ref().map(|x| x.as_bytes());
    2339              : 
    2340              :         pgb.write_message_noflush(&BeMessage::RowDescription(&[RowDescriptor::text_col(
    2341              :             b"valid_until",
    2342              :         )]))?
    2343              :         .write_message_noflush(&BeMessage::DataRow(&[bytes]))?;
    2344              : 
    2345              :         Ok(())
    2346              :     }
    2347              : 
    2348              :     #[instrument(skip_all, fields(shard_id))]
    2349              :     async fn handle_get_rel_exists_request(
    2350              :         timeline: &Timeline,
    2351              :         req: &PagestreamExistsRequest,
    2352              :         ctx: &RequestContext,
    2353              :     ) -> Result<PagestreamExistsResponse, PageStreamError> {
    2354              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2355              :         let lsn = Self::wait_or_get_last_lsn(
    2356              :             timeline,
    2357              :             req.hdr.request_lsn,
    2358              :             req.hdr.not_modified_since,
    2359              :             &latest_gc_cutoff_lsn,
    2360              :             ctx,
    2361              :         )
    2362              :         .await?;
    2363              : 
    2364              :         let exists = timeline
    2365              :             .get_rel_exists(
    2366              :                 req.rel,
    2367              :                 Version::LsnRange(LsnRange {
    2368              :                     effective_lsn: lsn,
    2369              :                     request_lsn: req.hdr.request_lsn,
    2370              :                 }),
    2371              :                 ctx,
    2372              :             )
    2373              :             .await?;
    2374              : 
    2375              :         Ok(PagestreamExistsResponse { req: *req, exists })
    2376              :     }
    2377              : 
    2378              :     /// If `allow_missing` is true, returns None instead of Err on missing relations. Otherwise,
    2379              :     /// never returns None. It is only supported by the gRPC protocol, so we pass it separately to
    2380              :     /// avoid changing the libpq protocol types.
    2381              :     #[instrument(skip_all, fields(shard_id))]
    2382              :     async fn handle_get_nblocks_request(
    2383              :         timeline: &Timeline,
    2384              :         req: &PagestreamNblocksRequest,
    2385              :         allow_missing: bool,
    2386              :         ctx: &RequestContext,
    2387              :     ) -> Result<Option<PagestreamNblocksResponse>, PageStreamError> {
    2388              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2389              :         let lsn = Self::wait_or_get_last_lsn(
    2390              :             timeline,
    2391              :             req.hdr.request_lsn,
    2392              :             req.hdr.not_modified_since,
    2393              :             &latest_gc_cutoff_lsn,
    2394              :             ctx,
    2395              :         )
    2396              :         .await?;
    2397              : 
    2398              :         let n_blocks = timeline
    2399              :             .get_rel_size_in_reldir(
    2400              :                 req.rel,
    2401              :                 Version::LsnRange(LsnRange {
    2402              :                     effective_lsn: lsn,
    2403              :                     request_lsn: req.hdr.request_lsn,
    2404              :                 }),
    2405              :                 None,
    2406              :                 allow_missing,
    2407              :                 ctx,
    2408              :             )
    2409              :             .await?;
    2410              :         let Some(n_blocks) = n_blocks else {
    2411              :             return Ok(None);
    2412              :         };
    2413              : 
    2414              :         Ok(Some(PagestreamNblocksResponse {
    2415              :             req: *req,
    2416              :             n_blocks,
    2417              :         }))
    2418              :     }
    2419              : 
    2420              :     #[instrument(skip_all, fields(shard_id))]
    2421              :     async fn handle_db_size_request(
    2422              :         timeline: &Timeline,
    2423              :         req: &PagestreamDbSizeRequest,
    2424              :         ctx: &RequestContext,
    2425              :     ) -> Result<PagestreamDbSizeResponse, PageStreamError> {
    2426              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2427              :         let lsn = Self::wait_or_get_last_lsn(
    2428              :             timeline,
    2429              :             req.hdr.request_lsn,
    2430              :             req.hdr.not_modified_since,
    2431              :             &latest_gc_cutoff_lsn,
    2432              :             ctx,
    2433              :         )
    2434              :         .await?;
    2435              : 
    2436              :         let total_blocks = timeline
    2437              :             .get_db_size(
    2438              :                 DEFAULTTABLESPACE_OID,
    2439              :                 req.dbnode,
    2440              :                 Version::LsnRange(LsnRange {
    2441              :                     effective_lsn: lsn,
    2442              :                     request_lsn: req.hdr.request_lsn,
    2443              :                 }),
    2444              :                 ctx,
    2445              :             )
    2446              :             .await?;
    2447              :         let db_size = total_blocks as i64 * BLCKSZ as i64;
    2448              : 
    2449              :         Ok(PagestreamDbSizeResponse { req: *req, db_size })
    2450              :     }
    2451              : 
    2452              :     #[instrument(skip_all)]
    2453              :     async fn handle_get_page_at_lsn_request_batched(
    2454              :         timeline: &Timeline,
    2455              :         requests: SmallVec<[BatchedGetPageRequest; 1]>,
    2456              :         io_concurrency: IoConcurrency,
    2457              :         batch_break_reason: GetPageBatchBreakReason,
    2458              :         ctx: &RequestContext,
    2459              :     ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer, RequestContext), BatchedPageStreamError>>
    2460              :     {
    2461              :         debug_assert_current_span_has_tenant_and_timeline_id();
    2462              : 
    2463              :         timeline
    2464              :             .query_metrics
    2465              :             .observe_getpage_batch_start(requests.len(), batch_break_reason);
    2466              : 
    2467              :         // If a page trace is running, submit an event for this request.
    2468              :         if let Some(page_trace) = timeline.page_trace.load().as_ref() {
    2469              :             let time = SystemTime::now();
    2470              :             for batch in &requests {
    2471              :                 let key = rel_block_to_key(batch.req.rel, batch.req.blkno).to_compact();
    2472              :                 // Ignore error (trace buffer may be full or tracer may have disconnected).
    2473              :                 _ = page_trace.try_send(PageTraceEvent {
    2474              :                     key,
    2475              :                     effective_lsn: batch.lsn_range.effective_lsn,
    2476              :                     time,
    2477              :                 });
    2478              :             }
    2479              :         }
    2480              : 
    2481              :         // If any request in the batch needs to wait for LSN, then do so now.
    2482              :         let mut perf_instrument = false;
    2483              :         let max_effective_lsn = requests
    2484              :             .iter()
    2485            0 :             .map(|req| {
    2486            0 :                 if req.ctx.has_perf_span() {
    2487            0 :                     perf_instrument = true;
    2488            0 :                 }
    2489              : 
    2490            0 :                 req.lsn_range.effective_lsn
    2491            0 :             })
    2492              :             .max()
    2493              :             .expect("batch is never empty");
    2494              : 
    2495              :         let ctx = match perf_instrument {
    2496              :             true => RequestContextBuilder::from(ctx)
    2497            0 :                 .root_perf_span(|| {
    2498            0 :                     info_span!(
    2499              :                         target: PERF_TRACE_TARGET,
    2500              :                         "GET_VECTORED",
    2501              :                         tenant_id = %timeline.tenant_shard_id.tenant_id,
    2502              :                         timeline_id = %timeline.timeline_id,
    2503            0 :                         shard = %timeline.tenant_shard_id.shard_slug(),
    2504              :                         %max_effective_lsn
    2505              :                     )
    2506            0 :                 })
    2507              :                 .attached_child(),
    2508              :             false => ctx.attached_child(),
    2509              :         };
    2510              : 
    2511              :         let last_record_lsn = timeline.get_last_record_lsn();
    2512              :         if max_effective_lsn > last_record_lsn {
    2513              :             if let Err(e) = timeline
    2514              :                 .wait_lsn(
    2515              :                     max_effective_lsn,
    2516              :                     crate::tenant::timeline::WaitLsnWaiter::PageService,
    2517              :                     timeline::WaitLsnTimeout::Default,
    2518              :                     &ctx,
    2519              :                 )
    2520            0 :                 .maybe_perf_instrument(&ctx, |current_perf_span| {
    2521            0 :                     info_span!(
    2522              :                         target: PERF_TRACE_TARGET,
    2523            0 :                         parent: current_perf_span,
    2524              :                         "WAIT_LSN",
    2525              :                     )
    2526            0 :                 })
    2527              :                 .await
    2528              :             {
    2529            0 :                 return Vec::from_iter(requests.into_iter().map(|req| {
    2530            0 :                     Err(BatchedPageStreamError {
    2531            0 :                         err: PageStreamError::from(e.clone()),
    2532            0 :                         req: req.req.hdr,
    2533            0 :                     })
    2534            0 :                 }));
    2535              :             }
    2536              :         }
    2537              : 
    2538              :         let results = timeline
    2539              :             .get_rel_page_at_lsn_batched(
    2540            0 :                 requests.iter().map(|p| {
    2541            0 :                     (
    2542            0 :                         &p.req.rel,
    2543            0 :                         &p.req.blkno,
    2544            0 :                         p.lsn_range,
    2545            0 :                         p.ctx.attached_child(),
    2546            0 :                     )
    2547            0 :                 }),
    2548              :                 io_concurrency,
    2549              :                 &ctx,
    2550              :             )
    2551              :             .await;
    2552              :         assert_eq!(results.len(), requests.len());
    2553              : 
    2554              :         // TODO: avoid creating the new Vec here
    2555              :         Vec::from_iter(
    2556              :             requests
    2557              :                 .into_iter()
    2558              :                 .zip(results.into_iter())
    2559            0 :                 .map(|(req, res)| {
    2560            0 :                     res.map(|page| {
    2561            0 :                         (
    2562            0 :                             PagestreamBeMessage::GetPage(
    2563            0 :                                 pagestream_api::PagestreamGetPageResponse { req: req.req, page },
    2564            0 :                             ),
    2565            0 :                             req.timer,
    2566            0 :                             req.ctx,
    2567            0 :                         )
    2568            0 :                     })
    2569            0 :                     .map_err(|e| BatchedPageStreamError {
    2570            0 :                         err: PageStreamError::from(e),
    2571            0 :                         req: req.req.hdr,
    2572            0 :                     })
    2573            0 :                 }),
    2574              :         )
    2575              :     }
    2576              : 
    2577              :     #[instrument(skip_all, fields(shard_id))]
    2578              :     async fn handle_get_slru_segment_request(
    2579              :         timeline: &Timeline,
    2580              :         req: &PagestreamGetSlruSegmentRequest,
    2581              :         ctx: &RequestContext,
    2582              :     ) -> Result<PagestreamGetSlruSegmentResponse, PageStreamError> {
    2583              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2584              :         let lsn = Self::wait_or_get_last_lsn(
    2585              :             timeline,
    2586              :             req.hdr.request_lsn,
    2587              :             req.hdr.not_modified_since,
    2588              :             &latest_gc_cutoff_lsn,
    2589              :             ctx,
    2590              :         )
    2591              :         .await?;
    2592              : 
    2593              :         let kind = SlruKind::from_repr(req.kind)
    2594              :             .ok_or(PageStreamError::BadRequest("invalid SLRU kind".into()))?;
    2595              :         let segment = timeline.get_slru_segment(kind, req.segno, lsn, ctx).await?;
    2596              : 
    2597              :         Ok(PagestreamGetSlruSegmentResponse { req: *req, segment })
    2598              :     }
    2599              : 
    2600              :     // NB: this impl mimics what we do for batched getpage requests.
    2601              :     #[cfg(feature = "testing")]
    2602              :     #[instrument(skip_all, fields(shard_id))]
    2603              :     async fn handle_test_request_batch(
    2604              :         timeline: &Timeline,
    2605              :         requests: Vec<BatchedTestRequest>,
    2606              :         _ctx: &RequestContext,
    2607              :     ) -> Vec<Result<(PagestreamBeMessage, SmgrOpTimer, RequestContext), BatchedPageStreamError>>
    2608              :     {
    2609              :         // real requests would do something with the timeline
    2610              :         let mut results = Vec::with_capacity(requests.len());
    2611              :         for _req in requests.iter() {
    2612              :             tokio::task::yield_now().await;
    2613              : 
    2614              :             results.push({
    2615              :                 if timeline.cancel.is_cancelled() {
    2616              :                     Err(PageReconstructError::Cancelled)
    2617              :                 } else {
    2618              :                     Ok(())
    2619              :                 }
    2620              :             });
    2621              :         }
    2622              : 
    2623              :         // TODO: avoid creating the new Vec here
    2624              :         Vec::from_iter(
    2625              :             requests
    2626              :                 .into_iter()
    2627              :                 .zip(results.into_iter())
    2628            0 :                 .map(|(req, res)| {
    2629            0 :                     res.map(|()| {
    2630            0 :                         (
    2631            0 :                             PagestreamBeMessage::Test(pagestream_api::PagestreamTestResponse {
    2632            0 :                                 req: req.req.clone(),
    2633            0 :                             }),
    2634            0 :                             req.timer,
    2635            0 :                             RequestContext::new(
    2636            0 :                                 TaskKind::PageRequestHandler,
    2637            0 :                                 DownloadBehavior::Warn,
    2638            0 :                             ),
    2639            0 :                         )
    2640            0 :                     })
    2641            0 :                     .map_err(|e| BatchedPageStreamError {
    2642            0 :                         err: PageStreamError::from(e),
    2643            0 :                         req: req.req.hdr,
    2644            0 :                     })
    2645            0 :                 }),
    2646              :         )
    2647              :     }
    2648              : 
    2649              :     /// Note on "fullbackup":
    2650              :     /// Full basebackups should only be used for debugging purposes.
    2651              :     /// Originally, it was introduced to enable breaking storage format changes,
    2652              :     /// but that is not applicable anymore.
    2653              :     ///
    2654              :     /// # Coding Discipline
    2655              :     ///
    2656              :     /// Coding discipline within this function: all interaction with the `pgb` connection
    2657              :     /// needs to be sensitive to connection shutdown, currently signalled via [`Self::cancel`].
    2658              :     /// This is so that we can shutdown page_service quickly.
    2659              :     ///
    2660              :     /// TODO: wrap the pgb that we pass to the basebackup handler so that it's sensitive
    2661              :     /// to connection cancellation.
    2662              :     #[allow(clippy::too_many_arguments)]
    2663              :     #[instrument(skip_all, fields(shard_id, ?lsn, ?prev_lsn, %full_backup))]
    2664              :     async fn handle_basebackup_request<IO>(
    2665              :         &mut self,
    2666              :         pgb: &mut PostgresBackend<IO>,
    2667              :         tenant_id: TenantId,
    2668              :         timeline_id: TimelineId,
    2669              :         lsn: Option<Lsn>,
    2670              :         prev_lsn: Option<Lsn>,
    2671              :         full_backup: bool,
    2672              :         gzip: bool,
    2673              :         replica: bool,
    2674              :         ctx: &RequestContext,
    2675              :     ) -> Result<(), QueryError>
    2676              :     where
    2677              :         IO: AsyncRead + AsyncWrite + Send + Sync + Unpin,
    2678              :     {
    2679              :         let started = std::time::Instant::now();
    2680              : 
    2681              :         let timeline = self
    2682              :             .timeline_handles
    2683              :             .as_mut()
    2684              :             .unwrap()
    2685              :             .get(tenant_id, timeline_id, ShardSelector::Zero)
    2686              :             .await?;
    2687              :         set_tracing_field_shard_id(&timeline);
    2688              :         let ctx = ctx.with_scope_timeline(&timeline);
    2689              : 
    2690              :         if timeline.is_archived() == Some(true) {
    2691              :             tracing::info!(
    2692              :                 "timeline {tenant_id}/{timeline_id} is archived, but got basebackup request for it."
    2693              :             );
    2694              :             return Err(QueryError::NotFound("timeline is archived".into()));
    2695              :         }
    2696              : 
    2697              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    2698              :         if let Some(lsn) = lsn {
    2699              :             // Backup was requested at a particular LSN. Wait for it to arrive.
    2700              :             info!("waiting for {}", lsn);
    2701              :             timeline
    2702              :                 .wait_lsn(
    2703              :                     lsn,
    2704              :                     crate::tenant::timeline::WaitLsnWaiter::PageService,
    2705              :                     crate::tenant::timeline::WaitLsnTimeout::Default,
    2706              :                     &ctx,
    2707              :                 )
    2708              :                 .await?;
    2709              :             timeline
    2710              :                 .check_lsn_is_in_scope(lsn, &latest_gc_cutoff_lsn)
    2711              :                 .context("invalid basebackup lsn")?;
    2712              :         }
    2713              : 
    2714              :         let lsn_awaited_after = started.elapsed();
    2715              : 
    2716              :         // switch client to COPYOUT
    2717              :         pgb.write_message_noflush(&BeMessage::CopyOutResponse)
    2718              :             .map_err(QueryError::Disconnected)?;
    2719              :         self.flush_cancellable(pgb, &self.cancel).await?;
    2720              : 
    2721              :         let mut from_cache = false;
    2722              : 
    2723              :         // Send a tarball of the latest layer on the timeline. Compress if not
    2724              :         // fullbackup. TODO Compress in that case too (tests need to be updated)
    2725              :         if full_backup {
    2726              :             let mut writer = pgb.copyout_writer();
    2727              :             basebackup::send_basebackup_tarball(
    2728              :                 &mut writer,
    2729              :                 &timeline,
    2730              :                 lsn,
    2731              :                 prev_lsn,
    2732              :                 full_backup,
    2733              :                 replica,
    2734              :                 None,
    2735              :                 &ctx,
    2736              :             )
    2737              :             .await?;
    2738              :         } else {
    2739              :             let mut writer = BufWriter::new(pgb.copyout_writer());
    2740              : 
    2741              :             let cached = timeline
    2742              :                 .get_cached_basebackup_if_enabled(lsn, prev_lsn, full_backup, replica, gzip)
    2743              :                 .await;
    2744              : 
    2745              :             if let Some(mut cached) = cached {
    2746              :                 from_cache = true;
    2747              :                 tokio::io::copy(&mut cached, &mut writer)
    2748              :                     .await
    2749            0 :                     .map_err(|err| {
    2750            0 :                         BasebackupError::Client(err, "handle_basebackup_request,cached,copy")
    2751            0 :                     })?;
    2752              :             } else {
    2753              :                 basebackup::send_basebackup_tarball(
    2754              :                     &mut writer,
    2755              :                     &timeline,
    2756              :                     lsn,
    2757              :                     prev_lsn,
    2758              :                     full_backup,
    2759              :                     replica,
    2760              :                     // NB: using fast compression because it's on the critical path for compute
    2761              :                     // startup. For an empty database, we get <100KB with this method. The
    2762              :                     // Level::Best compression method gives us <20KB, but maybe we should add
    2763              :                     // basebackup caching on compute shutdown first.
    2764              :                     gzip.then_some(async_compression::Level::Fastest),
    2765              :                     &ctx,
    2766              :                 )
    2767              :                 .await?;
    2768              :             }
    2769              :             writer
    2770              :                 .flush()
    2771              :                 .await
    2772            0 :                 .map_err(|err| BasebackupError::Client(err, "handle_basebackup_request,flush"))?;
    2773              :         }
    2774              : 
    2775              :         pgb.write_message_noflush(&BeMessage::CopyDone)
    2776              :             .map_err(QueryError::Disconnected)?;
    2777              :         self.flush_cancellable(pgb, &timeline.cancel).await?;
    2778              : 
    2779              :         let basebackup_after = started
    2780              :             .elapsed()
    2781              :             .checked_sub(lsn_awaited_after)
    2782              :             .unwrap_or(Duration::ZERO);
    2783              : 
    2784              :         info!(
    2785              :             lsn_await_millis = lsn_awaited_after.as_millis(),
    2786              :             basebackup_millis = basebackup_after.as_millis(),
    2787              :             %from_cache,
    2788              :             "basebackup complete"
    2789              :         );
    2790              : 
    2791              :         Ok(())
    2792              :     }
    2793              : 
    2794              :     // when accessing management api supply None as an argument
    2795              :     // when using to authorize tenant pass corresponding tenant id
    2796            0 :     fn check_permission(&self, tenant_id: Option<TenantId>) -> Result<(), QueryError> {
    2797            0 :         if self.auth.is_none() {
    2798              :             // auth is set to Trust, nothing to check so just return ok
    2799            0 :             return Ok(());
    2800            0 :         }
    2801              :         // auth is some, just checked above, when auth is some
    2802              :         // then claims are always present because of checks during connection init
    2803              :         // so this expect won't trigger
    2804            0 :         let claims = self
    2805            0 :             .claims
    2806            0 :             .as_ref()
    2807            0 :             .expect("claims presence already checked");
    2808            0 :         check_permission(claims, tenant_id).map_err(|e| QueryError::Unauthorized(e.0))
    2809            0 :     }
    2810              : }
    2811              : 
    2812              : /// `basebackup tenant timeline [lsn] [--gzip] [--replica]`
    2813              : #[derive(Debug, Clone, Eq, PartialEq)]
    2814              : struct BaseBackupCmd {
    2815              :     tenant_id: TenantId,
    2816              :     timeline_id: TimelineId,
    2817              :     lsn: Option<Lsn>,
    2818              :     gzip: bool,
    2819              :     replica: bool,
    2820              : }
    2821              : 
    2822              : /// `fullbackup tenant timeline [lsn] [prev_lsn]`
    2823              : #[derive(Debug, Clone, Eq, PartialEq)]
    2824              : struct FullBackupCmd {
    2825              :     tenant_id: TenantId,
    2826              :     timeline_id: TimelineId,
    2827              :     lsn: Option<Lsn>,
    2828              :     prev_lsn: Option<Lsn>,
    2829              : }
    2830              : 
    2831              : /// `pagestream_v2 tenant timeline`
    2832              : #[derive(Debug, Clone, Eq, PartialEq)]
    2833              : struct PageStreamCmd {
    2834              :     tenant_id: TenantId,
    2835              :     timeline_id: TimelineId,
    2836              :     protocol_version: PagestreamProtocolVersion,
    2837              : }
    2838              : 
    2839              : /// `lease lsn tenant timeline lsn`
    2840              : #[derive(Debug, Clone, Eq, PartialEq)]
    2841              : struct LeaseLsnCmd {
    2842              :     tenant_shard_id: TenantShardId,
    2843              :     timeline_id: TimelineId,
    2844              :     lsn: Lsn,
    2845              : }
    2846              : 
    2847              : #[derive(Debug, Clone, Eq, PartialEq)]
    2848              : enum PageServiceCmd {
    2849              :     Set,
    2850              :     PageStream(PageStreamCmd),
    2851              :     BaseBackup(BaseBackupCmd),
    2852              :     FullBackup(FullBackupCmd),
    2853              :     LeaseLsn(LeaseLsnCmd),
    2854              : }
    2855              : 
    2856              : impl PageStreamCmd {
    2857            3 :     fn parse(query: &str, protocol_version: PagestreamProtocolVersion) -> anyhow::Result<Self> {
    2858            3 :         let parameters = query.split_whitespace().collect_vec();
    2859            3 :         if parameters.len() != 2 {
    2860            1 :             bail!(
    2861            1 :                 "invalid number of parameters for pagestream command: {}",
    2862              :                 query
    2863              :             );
    2864            2 :         }
    2865            2 :         let tenant_id = TenantId::from_str(parameters[0])
    2866            2 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2867            1 :         let timeline_id = TimelineId::from_str(parameters[1])
    2868            1 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2869            1 :         Ok(Self {
    2870            1 :             tenant_id,
    2871            1 :             timeline_id,
    2872            1 :             protocol_version,
    2873            1 :         })
    2874            3 :     }
    2875              : }
    2876              : 
    2877              : impl FullBackupCmd {
    2878            2 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2879            2 :         let parameters = query.split_whitespace().collect_vec();
    2880            2 :         if parameters.len() < 2 || parameters.len() > 4 {
    2881            0 :             bail!(
    2882            0 :                 "invalid number of parameters for basebackup command: {}",
    2883              :                 query
    2884              :             );
    2885            2 :         }
    2886            2 :         let tenant_id = TenantId::from_str(parameters[0])
    2887            2 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2888            2 :         let timeline_id = TimelineId::from_str(parameters[1])
    2889            2 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2890              :         // The caller is responsible for providing correct lsn and prev_lsn.
    2891            2 :         let lsn = if let Some(lsn_str) = parameters.get(2) {
    2892              :             Some(
    2893            1 :                 Lsn::from_str(lsn_str)
    2894            1 :                     .with_context(|| format!("Failed to parse Lsn from {lsn_str}"))?,
    2895              :             )
    2896              :         } else {
    2897            1 :             None
    2898              :         };
    2899            2 :         let prev_lsn = if let Some(prev_lsn_str) = parameters.get(3) {
    2900              :             Some(
    2901            1 :                 Lsn::from_str(prev_lsn_str)
    2902            1 :                     .with_context(|| format!("Failed to parse Lsn from {prev_lsn_str}"))?,
    2903              :             )
    2904              :         } else {
    2905            1 :             None
    2906              :         };
    2907            2 :         Ok(Self {
    2908            2 :             tenant_id,
    2909            2 :             timeline_id,
    2910            2 :             lsn,
    2911            2 :             prev_lsn,
    2912            2 :         })
    2913            2 :     }
    2914              : }
    2915              : 
    2916              : impl BaseBackupCmd {
    2917            9 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2918            9 :         let parameters = query.split_whitespace().collect_vec();
    2919            9 :         if parameters.len() < 2 {
    2920            0 :             bail!(
    2921            0 :                 "invalid number of parameters for basebackup command: {}",
    2922              :                 query
    2923              :             );
    2924            9 :         }
    2925            9 :         let tenant_id = TenantId::from_str(parameters[0])
    2926            9 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2927            9 :         let timeline_id = TimelineId::from_str(parameters[1])
    2928            9 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2929              :         let lsn;
    2930              :         let flags_parse_from;
    2931            9 :         if let Some(maybe_lsn) = parameters.get(2) {
    2932            8 :             if *maybe_lsn == "latest" {
    2933            1 :                 lsn = None;
    2934            1 :                 flags_parse_from = 3;
    2935            7 :             } else if maybe_lsn.starts_with("--") {
    2936            5 :                 lsn = None;
    2937            5 :                 flags_parse_from = 2;
    2938            5 :             } else {
    2939              :                 lsn = Some(
    2940            2 :                     Lsn::from_str(maybe_lsn)
    2941            2 :                         .with_context(|| format!("Failed to parse lsn from {maybe_lsn}"))?,
    2942              :                 );
    2943            2 :                 flags_parse_from = 3;
    2944              :             }
    2945            1 :         } else {
    2946            1 :             lsn = None;
    2947            1 :             flags_parse_from = 2;
    2948            1 :         }
    2949              : 
    2950            9 :         let mut gzip = false;
    2951            9 :         let mut replica = false;
    2952              : 
    2953           11 :         for &param in &parameters[flags_parse_from..] {
    2954           11 :             match param {
    2955           11 :                 "--gzip" => {
    2956            7 :                     if gzip {
    2957            1 :                         bail!("duplicate parameter for basebackup command: {param}")
    2958            6 :                     }
    2959            6 :                     gzip = true
    2960              :                 }
    2961            4 :                 "--replica" => {
    2962            2 :                     if replica {
    2963            0 :                         bail!("duplicate parameter for basebackup command: {param}")
    2964            2 :                     }
    2965            2 :                     replica = true
    2966              :                 }
    2967            2 :                 _ => bail!("invalid parameter for basebackup command: {param}"),
    2968              :             }
    2969              :         }
    2970            6 :         Ok(Self {
    2971            6 :             tenant_id,
    2972            6 :             timeline_id,
    2973            6 :             lsn,
    2974            6 :             gzip,
    2975            6 :             replica,
    2976            6 :         })
    2977            9 :     }
    2978              : }
    2979              : 
    2980              : impl LeaseLsnCmd {
    2981            2 :     fn parse(query: &str) -> anyhow::Result<Self> {
    2982            2 :         let parameters = query.split_whitespace().collect_vec();
    2983            2 :         if parameters.len() != 3 {
    2984            0 :             bail!(
    2985            0 :                 "invalid number of parameters for lease lsn command: {}",
    2986              :                 query
    2987              :             );
    2988            2 :         }
    2989            2 :         let tenant_shard_id = TenantShardId::from_str(parameters[0])
    2990            2 :             .with_context(|| format!("Failed to parse tenant id from {}", parameters[0]))?;
    2991            2 :         let timeline_id = TimelineId::from_str(parameters[1])
    2992            2 :             .with_context(|| format!("Failed to parse timeline id from {}", parameters[1]))?;
    2993            2 :         let lsn = Lsn::from_str(parameters[2])
    2994            2 :             .with_context(|| format!("Failed to parse lsn from {}", parameters[2]))?;
    2995            2 :         Ok(Self {
    2996            2 :             tenant_shard_id,
    2997            2 :             timeline_id,
    2998            2 :             lsn,
    2999            2 :         })
    3000            2 :     }
    3001              : }
    3002              : 
    3003              : impl PageServiceCmd {
    3004           21 :     fn parse(query: &str) -> anyhow::Result<Self> {
    3005           21 :         let query = query.trim();
    3006           21 :         let Some((cmd, other)) = query.split_once(' ') else {
    3007            2 :             bail!("cannot parse query: {query}")
    3008              :         };
    3009           19 :         match cmd.to_ascii_lowercase().as_str() {
    3010           19 :             "pagestream_v2" => Ok(Self::PageStream(PageStreamCmd::parse(
    3011            3 :                 other,
    3012            3 :                 PagestreamProtocolVersion::V2,
    3013            2 :             )?)),
    3014           16 :             "pagestream_v3" => Ok(Self::PageStream(PageStreamCmd::parse(
    3015            0 :                 other,
    3016            0 :                 PagestreamProtocolVersion::V3,
    3017            0 :             )?)),
    3018           16 :             "basebackup" => Ok(Self::BaseBackup(BaseBackupCmd::parse(other)?)),
    3019            7 :             "fullbackup" => Ok(Self::FullBackup(FullBackupCmd::parse(other)?)),
    3020            5 :             "lease" => {
    3021            3 :                 let Some((cmd2, other)) = other.split_once(' ') else {
    3022            0 :                     bail!("invalid lease command: {cmd}");
    3023              :                 };
    3024            3 :                 let cmd2 = cmd2.to_ascii_lowercase();
    3025            3 :                 if cmd2 == "lsn" {
    3026            2 :                     Ok(Self::LeaseLsn(LeaseLsnCmd::parse(other)?))
    3027              :                 } else {
    3028            1 :                     bail!("invalid lease command: {cmd}");
    3029              :                 }
    3030              :             }
    3031            2 :             "set" => Ok(Self::Set),
    3032            0 :             _ => Err(anyhow::anyhow!("unsupported command {cmd} in {query}")),
    3033              :         }
    3034           21 :     }
    3035              : }
    3036              : 
    3037              : /// Parse the startup options from the postgres wire protocol startup packet.
    3038              : ///
    3039              : /// It takes a sequence of `-c option=X` or `-coption=X`. It parses the options string
    3040              : /// by best effort and returns all the options parsed (key-value pairs) and a bool indicating
    3041              : /// whether all options are successfully parsed. There could be duplicates in the options
    3042              : /// if the caller passed such parameters.
    3043            7 : fn parse_options(options: &str) -> (Vec<(String, String)>, bool) {
    3044            7 :     let mut parsing_config = false;
    3045            7 :     let mut has_error = false;
    3046            7 :     let mut config = Vec::new();
    3047           16 :     for item in options.split_whitespace() {
    3048           16 :         if item == "-c" {
    3049            9 :             if !parsing_config {
    3050            8 :                 parsing_config = true;
    3051            8 :             } else {
    3052              :                 // "-c" followed with another "-c"
    3053            1 :                 tracing::warn!("failed to parse the startup options: {options}");
    3054            1 :                 has_error = true;
    3055            1 :                 break;
    3056              :             }
    3057            7 :         } else if item.starts_with("-c") || parsing_config {
    3058            7 :             let Some((mut key, value)) = item.split_once('=') else {
    3059              :                 // "-c" followed with an invalid option
    3060            1 :                 tracing::warn!("failed to parse the startup options: {options}");
    3061            1 :                 has_error = true;
    3062            1 :                 break;
    3063              :             };
    3064            6 :             if !parsing_config {
    3065              :                 // Parse "-coptions=X"
    3066            1 :                 let Some(stripped_key) = key.strip_prefix("-c") else {
    3067            0 :                     tracing::warn!("failed to parse the startup options: {options}");
    3068            0 :                     has_error = true;
    3069            0 :                     break;
    3070              :                 };
    3071            1 :                 key = stripped_key;
    3072            5 :             }
    3073            6 :             config.push((key.to_string(), value.to_string()));
    3074            6 :             parsing_config = false;
    3075              :         } else {
    3076            0 :             tracing::warn!("failed to parse the startup options: {options}");
    3077            0 :             has_error = true;
    3078            0 :             break;
    3079              :         }
    3080              :     }
    3081            7 :     if parsing_config {
    3082              :         // "-c" without the option
    3083            3 :         tracing::warn!("failed to parse the startup options: {options}");
    3084            3 :         has_error = true;
    3085            4 :     }
    3086            7 :     (config, has_error)
    3087            7 : }
    3088              : 
    3089              : impl<IO> postgres_backend::Handler<IO> for PageServerHandler
    3090              : where
    3091              :     IO: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    3092              : {
    3093            0 :     fn check_auth_jwt(
    3094            0 :         &mut self,
    3095            0 :         _pgb: &mut PostgresBackend<IO>,
    3096            0 :         jwt_response: &[u8],
    3097            0 :     ) -> Result<(), QueryError> {
    3098              :         // this unwrap is never triggered, because check_auth_jwt only called when auth_type is NeonJWT
    3099              :         // which requires auth to be present
    3100            0 :         let data: TokenData<Claims> = self
    3101            0 :             .auth
    3102            0 :             .as_ref()
    3103            0 :             .unwrap()
    3104            0 :             .decode(str::from_utf8(jwt_response).context("jwt response is not UTF-8")?)
    3105            0 :             .map_err(|e| QueryError::Unauthorized(e.0))?;
    3106              : 
    3107            0 :         if matches!(data.claims.scope, Scope::Tenant) && data.claims.tenant_id.is_none() {
    3108            0 :             return Err(QueryError::Unauthorized(
    3109            0 :                 "jwt token scope is Tenant, but tenant id is missing".into(),
    3110            0 :             ));
    3111            0 :         }
    3112              : 
    3113            0 :         debug!(
    3114            0 :             "jwt scope check succeeded for scope: {:#?} by tenant id: {:?}",
    3115              :             data.claims.scope, data.claims.tenant_id,
    3116              :         );
    3117              : 
    3118            0 :         self.claims = Some(data.claims);
    3119            0 :         Ok(())
    3120            0 :     }
    3121              : 
    3122            0 :     fn startup(
    3123            0 :         &mut self,
    3124            0 :         _pgb: &mut PostgresBackend<IO>,
    3125            0 :         sm: &FeStartupPacket,
    3126            0 :     ) -> Result<(), QueryError> {
    3127            0 :         fail::fail_point!("ps::connection-start::startup-packet");
    3128              : 
    3129            0 :         if let FeStartupPacket::StartupMessage { params, .. } = sm {
    3130            0 :             if let Some(app_name) = params.get("application_name") {
    3131            0 :                 self.perf_span_fields.application_name = Some(app_name.to_string());
    3132            0 :                 Span::current().record("application_name", field::display(app_name));
    3133            0 :             }
    3134            0 :             if let Some(options) = params.get("options") {
    3135            0 :                 let (config, _) = parse_options(options);
    3136            0 :                 for (key, value) in config {
    3137            0 :                     if key == "neon.compute_mode" {
    3138            0 :                         self.perf_span_fields.compute_mode = Some(value.clone());
    3139            0 :                         Span::current().record("compute_mode", field::display(value));
    3140            0 :                     }
    3141              :                 }
    3142            0 :             }
    3143            0 :         };
    3144              : 
    3145            0 :         Ok(())
    3146            0 :     }
    3147              : 
    3148              :     #[instrument(skip_all, fields(tenant_id, timeline_id))]
    3149              :     async fn process_query(
    3150              :         &mut self,
    3151              :         pgb: &mut PostgresBackend<IO>,
    3152              :         query_string: &str,
    3153              :     ) -> Result<(), QueryError> {
    3154            0 :         fail::fail_point!("simulated-bad-compute-connection", |_| {
    3155            0 :             info!("Hit failpoint for bad connection");
    3156            0 :             Err(QueryError::SimulatedConnectionError)
    3157            0 :         });
    3158              : 
    3159              :         fail::fail_point!("ps::connection-start::process-query");
    3160              : 
    3161              :         let ctx = self.connection_ctx.attached_child();
    3162              :         debug!("process query {query_string}");
    3163              :         let query = PageServiceCmd::parse(query_string)?;
    3164              :         match query {
    3165              :             PageServiceCmd::PageStream(PageStreamCmd {
    3166              :                 tenant_id,
    3167              :                 timeline_id,
    3168              :                 protocol_version,
    3169              :             }) => {
    3170              :                 tracing::Span::current()
    3171              :                     .record("tenant_id", field::display(tenant_id))
    3172              :                     .record("timeline_id", field::display(timeline_id));
    3173              : 
    3174              :                 self.check_permission(Some(tenant_id))?;
    3175              :                 let command_kind = match protocol_version {
    3176              :                     PagestreamProtocolVersion::V2 => ComputeCommandKind::PageStreamV2,
    3177              :                     PagestreamProtocolVersion::V3 => ComputeCommandKind::PageStreamV3,
    3178              :                 };
    3179              :                 COMPUTE_COMMANDS_COUNTERS.for_command(command_kind).inc();
    3180              : 
    3181              :                 self.handle_pagerequests(pgb, tenant_id, timeline_id, protocol_version, ctx)
    3182              :                     .await?;
    3183              :             }
    3184              :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    3185              :                 tenant_id,
    3186              :                 timeline_id,
    3187              :                 lsn,
    3188              :                 gzip,
    3189              :                 replica,
    3190              :             }) => {
    3191              :                 tracing::Span::current()
    3192              :                     .record("tenant_id", field::display(tenant_id))
    3193              :                     .record("timeline_id", field::display(timeline_id));
    3194              : 
    3195              :                 self.check_permission(Some(tenant_id))?;
    3196              : 
    3197              :                 COMPUTE_COMMANDS_COUNTERS
    3198              :                     .for_command(ComputeCommandKind::Basebackup)
    3199              :                     .inc();
    3200              :                 let metric_recording = metrics::BASEBACKUP_QUERY_TIME.start_recording();
    3201            0 :                 let res = async {
    3202            0 :                     self.handle_basebackup_request(
    3203            0 :                         pgb,
    3204            0 :                         tenant_id,
    3205            0 :                         timeline_id,
    3206            0 :                         lsn,
    3207            0 :                         None,
    3208            0 :                         false,
    3209            0 :                         gzip,
    3210            0 :                         replica,
    3211            0 :                         &ctx,
    3212            0 :                     )
    3213            0 :                     .await?;
    3214            0 :                     pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    3215            0 :                     Result::<(), QueryError>::Ok(())
    3216            0 :                 }
    3217              :                 .await;
    3218              :                 metric_recording.observe(&res);
    3219              :                 res?;
    3220              :             }
    3221              :             // same as basebackup, but result includes relational data as well
    3222              :             PageServiceCmd::FullBackup(FullBackupCmd {
    3223              :                 tenant_id,
    3224              :                 timeline_id,
    3225              :                 lsn,
    3226              :                 prev_lsn,
    3227              :             }) => {
    3228              :                 tracing::Span::current()
    3229              :                     .record("tenant_id", field::display(tenant_id))
    3230              :                     .record("timeline_id", field::display(timeline_id));
    3231              : 
    3232              :                 self.check_permission(Some(tenant_id))?;
    3233              : 
    3234              :                 COMPUTE_COMMANDS_COUNTERS
    3235              :                     .for_command(ComputeCommandKind::Fullbackup)
    3236              :                     .inc();
    3237              : 
    3238              :                 // Check that the timeline exists
    3239              :                 self.handle_basebackup_request(
    3240              :                     pgb,
    3241              :                     tenant_id,
    3242              :                     timeline_id,
    3243              :                     lsn,
    3244              :                     prev_lsn,
    3245              :                     true,
    3246              :                     false,
    3247              :                     false,
    3248              :                     &ctx,
    3249              :                 )
    3250              :                 .await?;
    3251              :                 pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    3252              :             }
    3253              :             PageServiceCmd::Set => {
    3254              :                 // important because psycopg2 executes "SET datestyle TO 'ISO'"
    3255              :                 // on connect
    3256              :                 // TODO: allow setting options, i.e., application_name/compute_mode via SET commands
    3257              :                 pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?;
    3258              :             }
    3259              :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    3260              :                 tenant_shard_id,
    3261              :                 timeline_id,
    3262              :                 lsn,
    3263              :             }) => {
    3264              :                 tracing::Span::current()
    3265              :                     .record("tenant_id", field::display(tenant_shard_id))
    3266              :                     .record("timeline_id", field::display(timeline_id));
    3267              : 
    3268              :                 self.check_permission(Some(tenant_shard_id.tenant_id))?;
    3269              : 
    3270              :                 COMPUTE_COMMANDS_COUNTERS
    3271              :                     .for_command(ComputeCommandKind::LeaseLsn)
    3272              :                     .inc();
    3273              : 
    3274              :                 match self
    3275              :                     .handle_make_lsn_lease(pgb, tenant_shard_id, timeline_id, lsn, &ctx)
    3276              :                     .await
    3277              :                 {
    3278              :                     Ok(()) => {
    3279              :                         pgb.write_message_noflush(&BeMessage::CommandComplete(b"SELECT 1"))?
    3280              :                     }
    3281              :                     Err(e) => {
    3282              :                         error!("error obtaining lsn lease for {lsn}: {e:?}");
    3283              :                         pgb.write_message_noflush(&BeMessage::ErrorResponse(
    3284              :                             &e.to_string(),
    3285              :                             Some(e.pg_error_code()),
    3286              :                         ))?
    3287              :                     }
    3288              :                 };
    3289              :             }
    3290              :         }
    3291              : 
    3292              :         Ok(())
    3293              :     }
    3294              : }
    3295              : 
    3296              : /// Serves the page service over gRPC. Dispatches to PageServerHandler for request processing.
    3297              : ///
    3298              : /// TODO: rename to PageServiceHandler when libpq impl is removed.
    3299              : pub struct GrpcPageServiceHandler {
    3300              :     tenant_manager: Arc<TenantManager>,
    3301              :     ctx: RequestContext,
    3302              : 
    3303              :     /// Cancelled to shut down the server. Tonic will shut down in response to this, but wait for
    3304              :     /// in-flight requests to complete. Any tasks we spawn ourselves must respect this token.
    3305              :     cancel: CancellationToken,
    3306              : 
    3307              :     /// Any tasks we spawn ourselves should clone this gate guard, so that we can wait for them to
    3308              :     /// complete during shutdown. Request handlers implicitly hold this guard already.
    3309              :     gate_guard: GateGuard,
    3310              : 
    3311              :     /// `get_vectored` concurrency setting.
    3312              :     get_vectored_concurrent_io: GetVectoredConcurrentIo,
    3313              : }
    3314              : 
    3315              : impl GrpcPageServiceHandler {
    3316              :     /// Spawns a gRPC server for the page service.
    3317              :     ///
    3318              :     /// Returns a `CancellableTask` handle that can be used to shut down the server. It waits for
    3319              :     /// any in-flight requests and tasks to complete first.
    3320              :     ///
    3321              :     /// TODO: this doesn't support TLS. We need TLS reloading via ReloadingCertificateResolver, so we
    3322              :     /// need to reimplement the TCP+TLS accept loop ourselves.
    3323            0 :     pub fn spawn(
    3324            0 :         tenant_manager: Arc<TenantManager>,
    3325            0 :         auth: Option<Arc<SwappableJwtAuth>>,
    3326            0 :         perf_trace_dispatch: Option<Dispatch>,
    3327            0 :         get_vectored_concurrent_io: GetVectoredConcurrentIo,
    3328            0 :         listener: std::net::TcpListener,
    3329            0 :     ) -> anyhow::Result<CancellableTask> {
    3330              :         // Set up a cancellation token for shutting down the server, and a gate to wait for all
    3331              :         // requests and spawned tasks to complete.
    3332            0 :         let cancel = CancellationToken::new();
    3333            0 :         let gate = Gate::default();
    3334              : 
    3335            0 :         let ctx = RequestContextBuilder::new(TaskKind::PageRequestHandler)
    3336            0 :             .download_behavior(DownloadBehavior::Download)
    3337            0 :             .perf_span_dispatch(perf_trace_dispatch)
    3338            0 :             .detached_child();
    3339              : 
    3340              :         // Set up the TCP socket. We take a preconfigured TcpListener to bind the
    3341              :         // port early during startup.
    3342            0 :         let incoming = {
    3343            0 :             let _runtime = COMPUTE_REQUEST_RUNTIME.enter(); // required by TcpListener::from_std
    3344            0 :             listener.set_nonblocking(true)?;
    3345            0 :             tonic::transport::server::TcpIncoming::from(tokio::net::TcpListener::from_std(
    3346            0 :                 listener,
    3347            0 :             )?)
    3348            0 :             .with_nodelay(Some(GRPC_TCP_NODELAY))
    3349            0 :             .with_keepalive(Some(GRPC_TCP_KEEPALIVE_TIME))
    3350              :         };
    3351              : 
    3352              :         // Set up the gRPC server.
    3353              :         //
    3354              :         // TODO: consider tuning window sizes.
    3355            0 :         let mut server = tonic::transport::Server::builder()
    3356            0 :             .http2_keepalive_interval(Some(GRPC_HTTP2_KEEPALIVE_INTERVAL))
    3357            0 :             .http2_keepalive_timeout(Some(GRPC_HTTP2_KEEPALIVE_TIMEOUT))
    3358            0 :             .max_concurrent_streams(Some(GRPC_MAX_CONCURRENT_STREAMS));
    3359              : 
    3360              :         // Main page service stack. Uses a mix of Tonic interceptors and Tower layers:
    3361              :         //
    3362              :         // * Interceptors: can inspect and modify the gRPC request. Sync code only, runs before service.
    3363              :         //
    3364              :         // * Layers: allow async code, can run code after the service response. However, only has access
    3365              :         //   to the raw HTTP request/response, not the gRPC types.
    3366            0 :         let page_service_handler = GrpcPageServiceHandler {
    3367            0 :             tenant_manager,
    3368            0 :             ctx,
    3369            0 :             cancel: cancel.clone(),
    3370            0 :             gate_guard: gate.enter().expect("gate was just created"),
    3371            0 :             get_vectored_concurrent_io,
    3372            0 :         };
    3373              : 
    3374            0 :         let observability_layer = ObservabilityLayer;
    3375            0 :         let mut tenant_interceptor = TenantMetadataInterceptor;
    3376            0 :         let mut auth_interceptor = TenantAuthInterceptor::new(auth);
    3377              : 
    3378            0 :         let page_service = tower::ServiceBuilder::new()
    3379              :             // Create tracing span and record request start time.
    3380            0 :             .layer(observability_layer)
    3381              :             // Intercept gRPC requests.
    3382            0 :             .layer(tonic::service::InterceptorLayer::new(move |mut req| {
    3383              :                 // Extract tenant metadata.
    3384            0 :                 req = tenant_interceptor.call(req)?;
    3385              :                 // Authenticate tenant JWT token.
    3386            0 :                 req = auth_interceptor.call(req)?;
    3387            0 :                 Ok(req)
    3388            0 :             }))
    3389              :             // Run the page service.
    3390            0 :             .service(
    3391            0 :                 proto::PageServiceServer::new(page_service_handler)
    3392              :                     // Support both gzip and zstd compression. The client decides what to use.
    3393            0 :                     .accept_compressed(tonic::codec::CompressionEncoding::Gzip)
    3394            0 :                     .accept_compressed(tonic::codec::CompressionEncoding::Zstd)
    3395            0 :                     .send_compressed(tonic::codec::CompressionEncoding::Gzip)
    3396            0 :                     .send_compressed(tonic::codec::CompressionEncoding::Zstd),
    3397              :             );
    3398            0 :         let server = server.add_service(page_service);
    3399              : 
    3400              :         // Reflection service for use with e.g. grpcurl.
    3401            0 :         let reflection_service = tonic_reflection::server::Builder::configure()
    3402            0 :             .register_encoded_file_descriptor_set(proto::FILE_DESCRIPTOR_SET)
    3403            0 :             .build_v1()?;
    3404            0 :         let server = server.add_service(reflection_service);
    3405              : 
    3406              :         // Spawn server task. It runs until the cancellation token fires and in-flight requests and
    3407              :         // tasks complete. The `CancellableTask` will wait for the task's join handle, which
    3408              :         // implicitly waits for the gate to close.
    3409            0 :         let task_cancel = cancel.clone();
    3410            0 :         let task = COMPUTE_REQUEST_RUNTIME.spawn(task_mgr::exit_on_panic_or_error(
    3411              :             "grpc pageservice listener",
    3412            0 :             async move {
    3413            0 :                 server
    3414            0 :                     .serve_with_incoming_shutdown(incoming, task_cancel.cancelled())
    3415            0 :                     .await?;
    3416              :                 // Server exited cleanly. All requests should have completed by now. Wait for any
    3417              :                 // spawned tasks to complete as well (e.g. IoConcurrency sidecars) via the gate.
    3418            0 :                 gate.close().await;
    3419            0 :                 anyhow::Ok(())
    3420            0 :             },
    3421              :         ));
    3422              : 
    3423            0 :         Ok(CancellableTask { task, cancel })
    3424            0 :     }
    3425              : 
    3426              :     /// Errors if the request is executed on a non-zero shard. Only shard 0 has a complete view of
    3427              :     /// relations and their sizes, as well as SLRU segments and similar data.
    3428              :     #[allow(clippy::result_large_err)]
    3429            0 :     fn ensure_shard_zero(timeline: &Handle<TenantManagerTypes>) -> Result<(), tonic::Status> {
    3430            0 :         match timeline.get_shard_index().shard_number.0 {
    3431            0 :             0 => Ok(()),
    3432            0 :             shard => Err(tonic::Status::invalid_argument(format!(
    3433            0 :                 "request must execute on shard zero (is shard {shard})",
    3434            0 :             ))),
    3435              :         }
    3436            0 :     }
    3437              : 
    3438              :     /// Generates a PagestreamRequest header from a ReadLsn and request ID.
    3439            0 :     fn make_hdr(
    3440            0 :         read_lsn: page_api::ReadLsn,
    3441            0 :         req_id: Option<page_api::RequestID>,
    3442            0 :     ) -> PagestreamRequest {
    3443              :         PagestreamRequest {
    3444            0 :             reqid: req_id.map(|r| r.id).unwrap_or_default(),
    3445            0 :             request_lsn: read_lsn.request_lsn,
    3446            0 :             not_modified_since: read_lsn
    3447            0 :                 .not_modified_since_lsn
    3448            0 :                 .unwrap_or(read_lsn.request_lsn),
    3449              :         }
    3450            0 :     }
    3451              : 
    3452              :     /// Acquires a timeline handle for the given request.
    3453              :     ///
    3454              :     /// TODO: during shard splits, the compute may still be sending requests to the parent shard
    3455              :     /// until the entire split is committed and the compute is notified. Consider installing a
    3456              :     /// temporary shard router from the parent to the children while the split is in progress.
    3457              :     ///
    3458              :     /// TODO: consider moving this to a middleware layer; all requests need it. Needs to manage
    3459              :     /// the TimelineHandles lifecycle.
    3460              :     ///
    3461              :     /// TODO: untangle acquisition from TenantManagerWrapper::resolve() and Cache::get(), to avoid
    3462              :     /// the unnecessary overhead.
    3463            0 :     async fn get_request_timeline(
    3464            0 :         &self,
    3465            0 :         req: &tonic::Request<impl Any>,
    3466            0 :     ) -> Result<Handle<TenantManagerTypes>, GetActiveTimelineError> {
    3467            0 :         let ttid = *extract::<TenantTimelineId>(req);
    3468            0 :         let shard_index = *extract::<ShardIndex>(req);
    3469            0 :         let shard_selector = ShardSelector::Known(shard_index);
    3470              : 
    3471            0 :         TimelineHandles::new(self.tenant_manager.clone())
    3472            0 :             .get(ttid.tenant_id, ttid.timeline_id, shard_selector)
    3473            0 :             .await
    3474            0 :     }
    3475              : 
    3476              :     /// Starts a SmgrOpTimer at received_at, throttles the request, and records execution start.
    3477              :     /// Only errors if the timeline is shutting down.
    3478              :     ///
    3479              :     /// TODO: move timer construction to ObservabilityLayer (see TODO there).
    3480              :     /// TODO: decouple rate limiting (middleware?), and return SlowDown errors instead.
    3481            0 :     async fn record_op_start_and_throttle(
    3482            0 :         timeline: &Handle<TenantManagerTypes>,
    3483            0 :         op: metrics::SmgrQueryType,
    3484            0 :         received_at: Instant,
    3485            0 :     ) -> Result<SmgrOpTimer, tonic::Status> {
    3486            0 :         let mut timer = PageServerHandler::record_op_start_and_throttle(timeline, op, received_at)
    3487            0 :             .await
    3488            0 :             .map_err(|err| match err {
    3489              :                 // record_op_start_and_throttle() only returns Shutdown.
    3490            0 :                 QueryError::Shutdown => tonic::Status::unavailable(format!("{err}")),
    3491            0 :                 err => tonic::Status::internal(format!("unexpected error: {err}")),
    3492            0 :             })?;
    3493            0 :         timer.observe_execution_start(Instant::now());
    3494            0 :         Ok(timer)
    3495            0 :     }
    3496              : 
    3497              :     /// Processes a GetPage batch request, via the GetPages bidirectional streaming RPC.
    3498              :     ///
    3499              :     /// NB: errors returned from here are intercepted in get_pages(), and may be converted to a
    3500              :     /// GetPageResponse with an appropriate status code to avoid terminating the stream.
    3501              :     ///
    3502              :     /// TODO: get_vectored() currently enforces a batch limit of 32. Postgres will typically send
    3503              :     /// batches up to effective_io_concurrency = 100. Either we have to accept large batches, or
    3504              :     /// split them up in the client or server.
    3505              :     #[instrument(skip_all, fields(req_id, rel, blkno, blks, req_lsn, mod_lsn))]
    3506              :     async fn get_page(
    3507              :         ctx: &RequestContext,
    3508              :         timeline: &WeakHandle<TenantManagerTypes>,
    3509              :         req: proto::GetPageRequest,
    3510              :         io_concurrency: IoConcurrency,
    3511              :     ) -> Result<proto::GetPageResponse, tonic::Status> {
    3512              :         let received_at = Instant::now();
    3513              :         let timeline = timeline.upgrade()?;
    3514              :         let ctx = ctx.with_scope_page_service_pagestream(&timeline);
    3515              : 
    3516              :         // Validate the request, decorate the span, and convert it to a Pagestream request.
    3517              :         let req = page_api::GetPageRequest::try_from(req)?;
    3518              : 
    3519              :         span_record!(
    3520              :             req_id = %req.request_id,
    3521              :             rel = %req.rel,
    3522              :             blkno = %req.block_numbers[0],
    3523              :             blks = %req.block_numbers.len(),
    3524              :             lsn = %req.read_lsn,
    3525              :         );
    3526              : 
    3527              :         for &blkno in &req.block_numbers {
    3528              :             let shard = timeline.get_shard_identity();
    3529              :             let key = rel_block_to_key(req.rel, blkno);
    3530              :             if !shard.is_key_local(&key) {
    3531              :                 return Err(tonic::Status::invalid_argument(format!(
    3532              :                     "block {blkno} of relation {} requested on wrong shard {} (is on {})",
    3533              :                     req.rel,
    3534              :                     timeline.get_shard_index(),
    3535              :                     ShardIndex::new(shard.get_shard_number(&key), shard.count),
    3536              :                 )));
    3537              :             }
    3538              :         }
    3539              : 
    3540              :         let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn(); // hold guard
    3541              :         let effective_lsn = PageServerHandler::effective_request_lsn(
    3542              :             &timeline,
    3543              :             timeline.get_last_record_lsn(),
    3544              :             req.read_lsn.request_lsn,
    3545              :             req.read_lsn
    3546              :                 .not_modified_since_lsn
    3547              :                 .unwrap_or(req.read_lsn.request_lsn),
    3548              :             &latest_gc_cutoff_lsn,
    3549              :         )?;
    3550              : 
    3551              :         let mut batch = SmallVec::with_capacity(req.block_numbers.len());
    3552              :         for blkno in req.block_numbers {
    3553              :             // TODO: this creates one timer per page and throttles it. We should have a timer for
    3554              :             // the entire batch, and throttle only the batch, but this is equivalent to what
    3555              :             // PageServerHandler does already so we keep it for now.
    3556              :             let timer = Self::record_op_start_and_throttle(
    3557              :                 &timeline,
    3558              :                 metrics::SmgrQueryType::GetPageAtLsn,
    3559              :                 received_at,
    3560              :             )
    3561              :             .await?;
    3562              : 
    3563              :             batch.push(BatchedGetPageRequest {
    3564              :                 req: PagestreamGetPageRequest {
    3565              :                     hdr: Self::make_hdr(req.read_lsn, Some(req.request_id)),
    3566              :                     rel: req.rel,
    3567              :                     blkno,
    3568              :                 },
    3569              :                 lsn_range: LsnRange {
    3570              :                     effective_lsn,
    3571              :                     request_lsn: req.read_lsn.request_lsn,
    3572              :                 },
    3573              :                 timer,
    3574              :                 ctx: ctx.attached_child(),
    3575              :                 batch_wait_ctx: None, // TODO: add tracing
    3576              :             });
    3577              :         }
    3578              : 
    3579              :         // TODO: this does a relation size query for every page in the batch. Since this batch is
    3580              :         // all for one relation, we could do this only once. However, this is not the case for the
    3581              :         // libpq implementation.
    3582              :         let results = PageServerHandler::handle_get_page_at_lsn_request_batched(
    3583              :             &timeline,
    3584              :             batch,
    3585              :             io_concurrency,
    3586              :             GetPageBatchBreakReason::BatchFull, // TODO: not relevant for gRPC batches
    3587              :             &ctx,
    3588              :         )
    3589              :         .await;
    3590              : 
    3591              :         let mut resp = page_api::GetPageResponse {
    3592              :             request_id: req.request_id,
    3593              :             status_code: page_api::GetPageStatusCode::Ok,
    3594              :             reason: None,
    3595              :             rel: req.rel,
    3596              :             pages: Vec::with_capacity(results.len()),
    3597              :         };
    3598              : 
    3599              :         for result in results {
    3600              :             match result {
    3601              :                 Ok((PagestreamBeMessage::GetPage(r), _, _)) => resp.pages.push(page_api::Page {
    3602              :                     block_number: r.req.blkno,
    3603              :                     image: r.page,
    3604              :                 }),
    3605              :                 Ok((resp, _, _)) => {
    3606              :                     return Err(tonic::Status::internal(format!(
    3607              :                         "unexpected response: {resp:?}"
    3608              :                     )));
    3609              :                 }
    3610              :                 Err(err) => return Err(err.err.into()),
    3611              :             };
    3612              :         }
    3613              : 
    3614              :         Ok(resp.into())
    3615              :     }
    3616              : }
    3617              : 
    3618              : /// Implements the gRPC page service.
    3619              : ///
    3620              : /// On client disconnect (e.g. timeout or client shutdown), Tonic will drop the request handler
    3621              : /// futures, so the read path must be cancellation-safe. On server shutdown, Tonic will wait for
    3622              : /// in-flight requests to complete.
    3623              : ///
    3624              : /// TODO: when the libpq impl is removed, remove the Pagestream types and inline the handler code.
    3625              : #[tonic::async_trait]
    3626              : impl proto::PageService for GrpcPageServiceHandler {
    3627              :     type GetBaseBackupStream = Pin<
    3628              :         Box<dyn Stream<Item = Result<proto::GetBaseBackupResponseChunk, tonic::Status>> + Send>,
    3629              :     >;
    3630              : 
    3631              :     type GetPagesStream =
    3632              :         Pin<Box<dyn Stream<Item = Result<proto::GetPageResponse, tonic::Status>> + Send>>;
    3633              : 
    3634              :     #[instrument(skip_all, fields(lsn))]
    3635              :     async fn get_base_backup(
    3636              :         &self,
    3637              :         req: tonic::Request<proto::GetBaseBackupRequest>,
    3638            0 :     ) -> Result<tonic::Response<Self::GetBaseBackupStream>, tonic::Status> {
    3639              :         // Send chunks of 256 KB to avoid large memory allocations. pagebench basebackup shows this
    3640              :         // to be the sweet spot where throughput is saturated.
    3641              :         const CHUNK_SIZE: usize = 256 * 1024;
    3642              : 
    3643            0 :         let timeline = self.get_request_timeline(&req).await?;
    3644            0 :         let ctx = self.ctx.with_scope_timeline(&timeline);
    3645              : 
    3646              :         // Validate the request and decorate the span.
    3647            0 :         Self::ensure_shard_zero(&timeline)?;
    3648            0 :         if timeline.is_archived() == Some(true) {
    3649            0 :             return Err(tonic::Status::failed_precondition("timeline is archived"));
    3650            0 :         }
    3651            0 :         let req: page_api::GetBaseBackupRequest = req.into_inner().try_into()?;
    3652              : 
    3653            0 :         span_record!(lsn=?req.lsn);
    3654              : 
    3655              :         // Wait for the LSN to arrive, if given.
    3656            0 :         if let Some(lsn) = req.lsn {
    3657            0 :             let latest_gc_cutoff_lsn = timeline.get_applied_gc_cutoff_lsn();
    3658            0 :             timeline
    3659            0 :                 .wait_lsn(
    3660            0 :                     lsn,
    3661            0 :                     WaitLsnWaiter::PageService,
    3662            0 :                     WaitLsnTimeout::Default,
    3663            0 :                     &ctx,
    3664            0 :                 )
    3665            0 :                 .await?;
    3666            0 :             timeline
    3667            0 :                 .check_lsn_is_in_scope(lsn, &latest_gc_cutoff_lsn)
    3668            0 :                 .map_err(|err| {
    3669            0 :                     tonic::Status::invalid_argument(format!("invalid basebackup LSN: {err}"))
    3670            0 :                 })?;
    3671            0 :         }
    3672              : 
    3673              :         // Spawn a task to run the basebackup.
    3674            0 :         let span = Span::current();
    3675            0 :         let gate_guard = self
    3676            0 :             .gate_guard
    3677            0 :             .try_clone()
    3678            0 :             .map_err(|_| tonic::Status::unavailable("shutting down"))?;
    3679            0 :         let (mut simplex_read, mut simplex_write) = tokio::io::simplex(CHUNK_SIZE);
    3680            0 :         let jh = tokio::spawn(async move {
    3681            0 :             let _gate_guard = gate_guard; // keep gate open until task completes
    3682              : 
    3683            0 :             let gzip_level = match req.compression {
    3684            0 :                 page_api::BaseBackupCompression::None => None,
    3685              :                 // NB: using fast compression because it's on the critical path for compute
    3686              :                 // startup. For an empty database, we get <100KB with this method. The
    3687              :                 // Level::Best compression method gives us <20KB, but maybe we should add
    3688              :                 // basebackup caching on compute shutdown first.
    3689            0 :                 page_api::BaseBackupCompression::Gzip => Some(async_compression::Level::Fastest),
    3690              :             };
    3691              : 
    3692              :             // Check for a cached basebackup.
    3693            0 :             let cached = timeline
    3694            0 :                 .get_cached_basebackup_if_enabled(
    3695            0 :                     req.lsn,
    3696            0 :                     None,
    3697            0 :                     req.full,
    3698            0 :                     req.replica,
    3699            0 :                     gzip_level.is_some(),
    3700            0 :                 )
    3701            0 :                 .await;
    3702              : 
    3703            0 :             let result = if let Some(mut cached) = cached {
    3704              :                 // If we have a cached basebackup, send it.
    3705            0 :                 tokio::io::copy(&mut cached, &mut simplex_write)
    3706            0 :                     .await
    3707            0 :                     .map(|_| ())
    3708            0 :                     .map_err(|err| BasebackupError::Client(err, "cached,copy"))
    3709              :             } else {
    3710            0 :                 basebackup::send_basebackup_tarball(
    3711            0 :                     &mut simplex_write,
    3712            0 :                     &timeline,
    3713            0 :                     req.lsn,
    3714            0 :                     None,
    3715            0 :                     req.full,
    3716            0 :                     req.replica,
    3717            0 :                     gzip_level,
    3718            0 :                     &ctx,
    3719            0 :                 )
    3720            0 :                 .instrument(span) // propagate request span
    3721            0 :                 .await
    3722              :             };
    3723            0 :             simplex_write
    3724            0 :                 .shutdown()
    3725            0 :                 .await
    3726            0 :                 .map_err(|err| BasebackupError::Client(err, "simplex_write"))?;
    3727            0 :             result
    3728            0 :         });
    3729              : 
    3730              :         // Emit chunks of size CHUNK_SIZE.
    3731            0 :         let chunks = async_stream::try_stream! {
    3732              :             loop {
    3733              :                 let mut chunk = BytesMut::with_capacity(CHUNK_SIZE).limit(CHUNK_SIZE);
    3734              :                 loop {
    3735            0 :                     let n = simplex_read.read_buf(&mut chunk).await.map_err(|err| {
    3736            0 :                         tonic::Status::internal(format!("failed to read basebackup chunk: {err}"))
    3737            0 :                     })?;
    3738              :                     if n == 0 {
    3739              :                         break; // full chunk or closed stream
    3740              :                     }
    3741              :                 }
    3742              :                 let chunk = chunk.into_inner().freeze();
    3743              :                 if chunk.is_empty() {
    3744              :                     break;
    3745              :                 }
    3746              :                 yield proto::GetBaseBackupResponseChunk::from(chunk);
    3747              :             }
    3748              :             // Wait for the basebackup task to exit and check for errors.
    3749            0 :             jh.await.map_err(|err| {
    3750            0 :                 tonic::Status::internal(format!("basebackup failed: {err}"))
    3751            0 :             })??;
    3752              :         };
    3753              : 
    3754            0 :         Ok(tonic::Response::new(Box::pin(chunks)))
    3755            0 :     }
    3756              : 
    3757              :     #[instrument(skip_all, fields(db_oid, lsn))]
    3758              :     async fn get_db_size(
    3759              :         &self,
    3760              :         req: tonic::Request<proto::GetDbSizeRequest>,
    3761            0 :     ) -> Result<tonic::Response<proto::GetDbSizeResponse>, tonic::Status> {
    3762            0 :         let received_at = extract::<ReceivedAt>(&req).0;
    3763            0 :         let timeline = self.get_request_timeline(&req).await?;
    3764            0 :         let ctx = self.ctx.with_scope_page_service_pagestream(&timeline);
    3765              : 
    3766              :         // Validate the request, decorate the span, and convert it to a Pagestream request.
    3767            0 :         Self::ensure_shard_zero(&timeline)?;
    3768            0 :         let req: page_api::GetDbSizeRequest = req.into_inner().try_into()?;
    3769              : 
    3770            0 :         span_record!(db_oid=%req.db_oid, lsn=%req.read_lsn);
    3771              : 
    3772            0 :         let req = PagestreamDbSizeRequest {
    3773            0 :             hdr: Self::make_hdr(req.read_lsn, None),
    3774            0 :             dbnode: req.db_oid,
    3775            0 :         };
    3776              : 
    3777              :         // Execute the request and convert the response.
    3778            0 :         let _timer = Self::record_op_start_and_throttle(
    3779            0 :             &timeline,
    3780            0 :             metrics::SmgrQueryType::GetDbSize,
    3781            0 :             received_at,
    3782            0 :         )
    3783            0 :         .await?;
    3784              : 
    3785            0 :         let resp = PageServerHandler::handle_db_size_request(&timeline, &req, &ctx).await?;
    3786            0 :         let resp = resp.db_size as page_api::GetDbSizeResponse;
    3787            0 :         Ok(tonic::Response::new(resp.into()))
    3788            0 :     }
    3789              : 
    3790              :     // NB: don't instrument this, instrument each streamed request.
    3791            0 :     async fn get_pages(
    3792              :         &self,
    3793              :         req: tonic::Request<tonic::Streaming<proto::GetPageRequest>>,
    3794            0 :     ) -> Result<tonic::Response<Self::GetPagesStream>, tonic::Status> {
    3795              :         // Extract the timeline from the request and check that it exists.
    3796            0 :         let ttid = *extract::<TenantTimelineId>(&req);
    3797            0 :         let shard_index = *extract::<ShardIndex>(&req);
    3798            0 :         let shard_selector = ShardSelector::Known(shard_index);
    3799              : 
    3800            0 :         let mut handles = TimelineHandles::new(self.tenant_manager.clone());
    3801            0 :         handles
    3802            0 :             .get(ttid.tenant_id, ttid.timeline_id, shard_selector)
    3803            0 :             .await?;
    3804              : 
    3805              :         // Spawn an IoConcurrency sidecar, if enabled.
    3806            0 :         let gate_guard = self
    3807            0 :             .gate_guard
    3808            0 :             .try_clone()
    3809            0 :             .map_err(|_| tonic::Status::unavailable("shutting down"))?;
    3810            0 :         let io_concurrency =
    3811            0 :             IoConcurrency::spawn_from_conf(self.get_vectored_concurrent_io, gate_guard);
    3812              : 
    3813              :         // Construct the GetPageRequest stream handler.
    3814            0 :         let span = Span::current();
    3815            0 :         let ctx = self.ctx.attached_child();
    3816            0 :         let cancel = self.cancel.clone();
    3817            0 :         let mut reqs = req.into_inner();
    3818              : 
    3819            0 :         let resps = async_stream::try_stream! {
    3820              :             let timeline = handles
    3821              :                 .get(ttid.tenant_id, ttid.timeline_id, shard_selector)
    3822              :                 .await?
    3823              :                 .downgrade();
    3824              :             loop {
    3825              :                 // NB: Tonic considers the entire stream to be an in-flight request and will wait
    3826              :                 // for it to complete before shutting down. React to cancellation between requests.
    3827              :                 let req = tokio::select! {
    3828              :                     biased;
    3829              :                     _ = cancel.cancelled() => Err(tonic::Status::unavailable("shutting down")),
    3830              : 
    3831              :                     result = reqs.message() => match result {
    3832              :                         Ok(Some(req)) => Ok(req),
    3833              :                         Ok(None) => break, // client closed the stream
    3834              :                         Err(err) => Err(err),
    3835              :                     },
    3836              :                 }?;
    3837              :                 let req_id = req.request_id.map(page_api::RequestID::from).unwrap_or_default();
    3838              :                 let result = Self::get_page(&ctx, &timeline, req, io_concurrency.clone())
    3839              :                     .instrument(span.clone()) // propagate request span
    3840              :                     .await;
    3841              :                 yield match result {
    3842              :                     Ok(resp) => resp,
    3843              :                     // Convert per-request errors to GetPageResponses as appropriate, or terminate
    3844              :                     // the stream with a tonic::Status. Log the error regardless, since
    3845              :                     // ObservabilityLayer can't automatically log stream errors.
    3846              :                     Err(status) => {
    3847              :                         // TODO: it would be nice if we could propagate the get_page() fields here.
    3848            0 :                         span.in_scope(|| {
    3849            0 :                             warn!("request failed with {:?}: {}", status.code(), status.message());
    3850            0 :                         });
    3851              :                         page_api::GetPageResponse::try_from_status(status, req_id)?.into()
    3852              :                     }
    3853              :                 }
    3854              :             }
    3855              :         };
    3856              : 
    3857            0 :         Ok(tonic::Response::new(Box::pin(resps)))
    3858            0 :     }
    3859              : 
    3860              :     #[instrument(skip_all, fields(rel, lsn, allow_missing))]
    3861              :     async fn get_rel_size(
    3862              :         &self,
    3863              :         req: tonic::Request<proto::GetRelSizeRequest>,
    3864            0 :     ) -> Result<tonic::Response<proto::GetRelSizeResponse>, tonic::Status> {
    3865            0 :         let received_at = extract::<ReceivedAt>(&req).0;
    3866            0 :         let timeline = self.get_request_timeline(&req).await?;
    3867            0 :         let ctx = self.ctx.with_scope_page_service_pagestream(&timeline);
    3868              : 
    3869              :         // Validate the request, decorate the span, and convert it to a Pagestream request.
    3870            0 :         Self::ensure_shard_zero(&timeline)?;
    3871            0 :         let req: page_api::GetRelSizeRequest = req.into_inner().try_into()?;
    3872            0 :         let allow_missing = req.allow_missing;
    3873              : 
    3874            0 :         span_record!(rel=%req.rel, lsn=%req.read_lsn, allow_missing=%req.allow_missing);
    3875              : 
    3876            0 :         let req = PagestreamNblocksRequest {
    3877            0 :             hdr: Self::make_hdr(req.read_lsn, None),
    3878            0 :             rel: req.rel,
    3879            0 :         };
    3880              : 
    3881              :         // Execute the request and convert the response.
    3882            0 :         let _timer = Self::record_op_start_and_throttle(
    3883            0 :             &timeline,
    3884            0 :             metrics::SmgrQueryType::GetRelSize,
    3885            0 :             received_at,
    3886            0 :         )
    3887            0 :         .await?;
    3888              : 
    3889            0 :         let resp =
    3890            0 :             PageServerHandler::handle_get_nblocks_request(&timeline, &req, allow_missing, &ctx)
    3891            0 :                 .await?;
    3892            0 :         let resp: page_api::GetRelSizeResponse = resp.map(|resp| resp.n_blocks);
    3893              : 
    3894            0 :         Ok(tonic::Response::new(resp.into()))
    3895            0 :     }
    3896              : 
    3897              :     #[instrument(skip_all, fields(kind, segno, lsn))]
    3898              :     async fn get_slru_segment(
    3899              :         &self,
    3900              :         req: tonic::Request<proto::GetSlruSegmentRequest>,
    3901            0 :     ) -> Result<tonic::Response<proto::GetSlruSegmentResponse>, tonic::Status> {
    3902            0 :         let received_at = extract::<ReceivedAt>(&req).0;
    3903            0 :         let timeline = self.get_request_timeline(&req).await?;
    3904            0 :         let ctx = self.ctx.with_scope_page_service_pagestream(&timeline);
    3905              : 
    3906              :         // Validate the request, decorate the span, and convert it to a Pagestream request.
    3907            0 :         Self::ensure_shard_zero(&timeline)?;
    3908            0 :         let req: page_api::GetSlruSegmentRequest = req.into_inner().try_into()?;
    3909              : 
    3910            0 :         span_record!(kind=%req.kind, segno=%req.segno, lsn=%req.read_lsn);
    3911              : 
    3912            0 :         let req = PagestreamGetSlruSegmentRequest {
    3913            0 :             hdr: Self::make_hdr(req.read_lsn, None),
    3914            0 :             kind: req.kind as u8,
    3915            0 :             segno: req.segno,
    3916            0 :         };
    3917              : 
    3918              :         // Execute the request and convert the response.
    3919            0 :         let _timer = Self::record_op_start_and_throttle(
    3920            0 :             &timeline,
    3921            0 :             metrics::SmgrQueryType::GetSlruSegment,
    3922            0 :             received_at,
    3923            0 :         )
    3924            0 :         .await?;
    3925              : 
    3926            0 :         let resp =
    3927            0 :             PageServerHandler::handle_get_slru_segment_request(&timeline, &req, &ctx).await?;
    3928            0 :         let resp: page_api::GetSlruSegmentResponse = resp.segment;
    3929            0 :         Ok(tonic::Response::new(resp.into()))
    3930            0 :     }
    3931              : 
    3932              :     #[instrument(skip_all, fields(lsn))]
    3933              :     async fn lease_lsn(
    3934              :         &self,
    3935              :         req: tonic::Request<proto::LeaseLsnRequest>,
    3936            0 :     ) -> Result<tonic::Response<proto::LeaseLsnResponse>, tonic::Status> {
    3937            0 :         let timeline = self.get_request_timeline(&req).await?;
    3938            0 :         let ctx = self.ctx.with_scope_timeline(&timeline);
    3939              : 
    3940              :         // Validate and convert the request, and decorate the span.
    3941            0 :         let req: page_api::LeaseLsnRequest = req.into_inner().try_into()?;
    3942              : 
    3943            0 :         span_record!(lsn=%req.lsn);
    3944              : 
    3945              :         // Attempt to acquire a lease. Return FailedPrecondition if the lease could not be granted.
    3946            0 :         let lease_length = timeline.get_lsn_lease_length();
    3947            0 :         let expires = match timeline.renew_lsn_lease(req.lsn, lease_length, &ctx) {
    3948            0 :             Ok(lease) => lease.valid_until,
    3949            0 :             Err(err) => return Err(tonic::Status::failed_precondition(format!("{err}"))),
    3950              :         };
    3951              : 
    3952              :         // TODO: is this spammy? Move it compute-side?
    3953            0 :         info!(
    3954            0 :             "acquired lease for {} until {}",
    3955              :             req.lsn,
    3956            0 :             chrono::DateTime::<Utc>::from(expires).to_rfc3339()
    3957              :         );
    3958              : 
    3959            0 :         Ok(tonic::Response::new(expires.into()))
    3960            0 :     }
    3961              : }
    3962              : 
    3963              : /// gRPC middleware layer that handles observability concerns:
    3964              : ///
    3965              : /// * Creates and enters a tracing span.
    3966              : /// * Records the request start time as a ReceivedAt request extension.
    3967              : ///
    3968              : /// TODO: add perf tracing.
    3969              : /// TODO: add timing and metrics.
    3970              : /// TODO: add logging.
    3971              : #[derive(Clone)]
    3972              : struct ObservabilityLayer;
    3973              : 
    3974              : impl<S: tonic::server::NamedService> tower::Layer<S> for ObservabilityLayer {
    3975              :     type Service = ObservabilityLayerService<S>;
    3976              : 
    3977            0 :     fn layer(&self, inner: S) -> Self::Service {
    3978            0 :         Self::Service { inner }
    3979            0 :     }
    3980              : }
    3981              : 
    3982              : #[derive(Clone)]
    3983              : struct ObservabilityLayerService<S> {
    3984              :     inner: S,
    3985              : }
    3986              : 
    3987              : #[derive(Clone, Copy)]
    3988              : struct ReceivedAt(Instant);
    3989              : 
    3990              : impl<S: tonic::server::NamedService> tonic::server::NamedService for ObservabilityLayerService<S> {
    3991              :     const NAME: &'static str = S::NAME; // propagate inner service name
    3992              : }
    3993              : 
    3994              : impl<S, Req, Resp> tower::Service<http::Request<Req>> for ObservabilityLayerService<S>
    3995              : where
    3996              :     S: tower::Service<http::Request<Req>, Response = http::Response<Resp>> + Send,
    3997              :     S::Future: Send + 'static,
    3998              : {
    3999              :     type Response = S::Response;
    4000              :     type Error = S::Error;
    4001              :     type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;
    4002              : 
    4003            0 :     fn call(&mut self, mut req: http::Request<Req>) -> Self::Future {
    4004              :         // Record the request start time as a request extension.
    4005              :         //
    4006              :         // TODO: we should start a timer here instead, but it currently requires a timeline handle
    4007              :         // and SmgrQueryType, which we don't have yet. Refactor it to provide it later.
    4008            0 :         req.extensions_mut().insert(ReceivedAt(Instant::now()));
    4009              : 
    4010              :         // Extract the peer address and gRPC method.
    4011            0 :         let peer = req
    4012            0 :             .extensions()
    4013            0 :             .get::<TcpConnectInfo>()
    4014            0 :             .and_then(|info| info.remote_addr())
    4015            0 :             .map(|addr| addr.to_string())
    4016            0 :             .unwrap_or_default();
    4017              : 
    4018            0 :         let method = req
    4019            0 :             .uri()
    4020            0 :             .path()
    4021            0 :             .split('/')
    4022            0 :             .nth(2)
    4023            0 :             .unwrap_or(req.uri().path())
    4024            0 :             .to_string();
    4025              : 
    4026              :         // Create a basic tracing span.
    4027              :         //
    4028              :         // Enter the span for the current thread and instrument the future. It is not sufficient to
    4029              :         // only instrument the future, since it only takes effect after the future is returned and
    4030              :         // polled, not when the inner service is called below (e.g. during interceptor execution).
    4031            0 :         let span = info_span!(
    4032              :             "grpc:pageservice",
    4033              :             // These will be populated by TenantMetadataInterceptor.
    4034              :             tenant_id = field::Empty,
    4035              :             timeline_id = field::Empty,
    4036              :             shard_id = field::Empty,
    4037              :             // NB: empty fields must be listed first above. Otherwise, the field names will be
    4038              :             // clobbered when the empty fields are populated. They will be output last regardless.
    4039              :             %peer,
    4040              :             %method,
    4041              :         );
    4042            0 :         let _guard = span.enter();
    4043              : 
    4044              :         // Construct a future for calling the inner service, but don't await it. This avoids having
    4045              :         // to clone the inner service into the future below.
    4046            0 :         let call = self.inner.call(req);
    4047              : 
    4048            0 :         async move {
    4049              :             // Await the inner service call.
    4050            0 :             let result = call.await;
    4051              : 
    4052              :             // Log gRPC error statuses. This won't include request info from handler spans, but it
    4053              :             // will catch all errors (even those emitted before handler spans are constructed). Only
    4054              :             // unary request errors are logged here, not streaming response errors.
    4055            0 :             if let Ok(ref resp) = result
    4056            0 :                 && let Some(status) = tonic::Status::from_header_map(resp.headers())
    4057            0 :                 && status.code() != tonic::Code::Ok
    4058              :             {
    4059              :                 // TODO: it would be nice if we could propagate the handler span's request fields
    4060              :                 // here. This could e.g. be done by attaching the request fields to
    4061              :                 // tonic::Status::metadata via a proc macro.
    4062            0 :                 warn!(
    4063            0 :                     "request failed with {:?}: {}",
    4064            0 :                     status.code(),
    4065            0 :                     status.message()
    4066              :                 );
    4067            0 :             }
    4068              : 
    4069            0 :             result
    4070            0 :         }
    4071            0 :         .instrument(span.clone())
    4072            0 :         .boxed()
    4073            0 :     }
    4074              : 
    4075            0 :     fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
    4076            0 :         self.inner.poll_ready(cx)
    4077            0 :     }
    4078              : }
    4079              : 
    4080              : /// gRPC interceptor that decodes tenant metadata and stores it as request extensions of type
    4081              : /// TenantTimelineId and ShardIndex.
    4082              : #[derive(Clone)]
    4083              : struct TenantMetadataInterceptor;
    4084              : 
    4085              : impl tonic::service::Interceptor for TenantMetadataInterceptor {
    4086            0 :     fn call(&mut self, mut req: tonic::Request<()>) -> Result<tonic::Request<()>, tonic::Status> {
    4087              :         // Decode the tenant ID.
    4088            0 :         let tenant_id = req
    4089            0 :             .metadata()
    4090            0 :             .get("neon-tenant-id")
    4091            0 :             .ok_or_else(|| tonic::Status::invalid_argument("missing neon-tenant-id"))?
    4092            0 :             .to_str()
    4093            0 :             .map_err(|_| tonic::Status::invalid_argument("invalid neon-tenant-id"))?;
    4094            0 :         let tenant_id = TenantId::from_str(tenant_id)
    4095            0 :             .map_err(|_| tonic::Status::invalid_argument("invalid neon-tenant-id"))?;
    4096              : 
    4097              :         // Decode the timeline ID.
    4098            0 :         let timeline_id = req
    4099            0 :             .metadata()
    4100            0 :             .get("neon-timeline-id")
    4101            0 :             .ok_or_else(|| tonic::Status::invalid_argument("missing neon-timeline-id"))?
    4102            0 :             .to_str()
    4103            0 :             .map_err(|_| tonic::Status::invalid_argument("invalid neon-timeline-id"))?;
    4104            0 :         let timeline_id = TimelineId::from_str(timeline_id)
    4105            0 :             .map_err(|_| tonic::Status::invalid_argument("invalid neon-timeline-id"))?;
    4106              : 
    4107              :         // Decode the shard ID.
    4108            0 :         let shard_id = req
    4109            0 :             .metadata()
    4110            0 :             .get("neon-shard-id")
    4111            0 :             .ok_or_else(|| tonic::Status::invalid_argument("missing neon-shard-id"))?
    4112            0 :             .to_str()
    4113            0 :             .map_err(|_| tonic::Status::invalid_argument("invalid neon-shard-id"))?;
    4114            0 :         let shard_id = ShardIndex::from_str(shard_id)
    4115            0 :             .map_err(|_| tonic::Status::invalid_argument("invalid neon-shard-id"))?;
    4116              : 
    4117              :         // Stash them in the request.
    4118            0 :         let extensions = req.extensions_mut();
    4119            0 :         extensions.insert(TenantTimelineId::new(tenant_id, timeline_id));
    4120            0 :         extensions.insert(shard_id);
    4121              : 
    4122              :         // Decorate the tracing span.
    4123            0 :         span_record!(%tenant_id, %timeline_id, %shard_id);
    4124              : 
    4125            0 :         Ok(req)
    4126            0 :     }
    4127              : }
    4128              : 
    4129              : /// Authenticates gRPC page service requests.
    4130              : #[derive(Clone)]
    4131              : struct TenantAuthInterceptor {
    4132              :     auth: Option<Arc<SwappableJwtAuth>>,
    4133              : }
    4134              : 
    4135              : impl TenantAuthInterceptor {
    4136            0 :     fn new(auth: Option<Arc<SwappableJwtAuth>>) -> Self {
    4137            0 :         Self { auth }
    4138            0 :     }
    4139              : }
    4140              : 
    4141              : impl tonic::service::Interceptor for TenantAuthInterceptor {
    4142            0 :     fn call(&mut self, req: tonic::Request<()>) -> Result<tonic::Request<()>, tonic::Status> {
    4143              :         // Do nothing if auth is disabled.
    4144            0 :         let Some(auth) = self.auth.as_ref() else {
    4145            0 :             return Ok(req);
    4146              :         };
    4147              : 
    4148              :         // Fetch the tenant ID from the request extensions (set by TenantMetadataInterceptor).
    4149            0 :         let TenantTimelineId { tenant_id, .. } = *extract::<TenantTimelineId>(&req);
    4150              : 
    4151              :         // Fetch and decode the JWT token.
    4152            0 :         let jwt = req
    4153            0 :             .metadata()
    4154            0 :             .get("authorization")
    4155            0 :             .ok_or_else(|| tonic::Status::unauthenticated("no authorization header"))?
    4156            0 :             .to_str()
    4157            0 :             .map_err(|_| tonic::Status::invalid_argument("invalid authorization header"))?
    4158            0 :             .strip_prefix("Bearer ")
    4159            0 :             .ok_or_else(|| tonic::Status::invalid_argument("invalid authorization header"))?
    4160            0 :             .trim();
    4161            0 :         let jwtdata: TokenData<Claims> = auth
    4162            0 :             .decode(jwt)
    4163            0 :             .map_err(|err| tonic::Status::invalid_argument(format!("invalid JWT token: {err}")))?;
    4164            0 :         let claims = jwtdata.claims;
    4165              : 
    4166              :         // Check if the token is valid for this tenant.
    4167            0 :         check_permission(&claims, Some(tenant_id))
    4168            0 :             .map_err(|err| tonic::Status::permission_denied(err.to_string()))?;
    4169              : 
    4170              :         // TODO: consider stashing the claims in the request extensions, if needed.
    4171              : 
    4172            0 :         Ok(req)
    4173            0 :     }
    4174              : }
    4175              : 
    4176              : /// Extracts the given type from the request extensions, or panics if it is missing.
    4177            0 : fn extract<T: Send + Sync + 'static>(req: &tonic::Request<impl Any>) -> &T {
    4178            0 :     extract_from(req.extensions())
    4179            0 : }
    4180              : 
    4181              : /// Extract the given type from the request extensions, or panics if it is missing. This variant
    4182              : /// can extract both from a tonic::Request and http::Request.
    4183            0 : fn extract_from<T: Send + Sync + 'static>(ext: &http::Extensions) -> &T {
    4184            0 :     let Some(value) = ext.get::<T>() else {
    4185            0 :         let name = std::any::type_name::<T>();
    4186            0 :         panic!("extension {name} should be set by middleware");
    4187              :     };
    4188            0 :     value
    4189            0 : }
    4190              : 
    4191              : #[derive(Debug, thiserror::Error)]
    4192              : pub(crate) enum GetActiveTimelineError {
    4193              :     #[error(transparent)]
    4194              :     Tenant(GetActiveTenantError),
    4195              :     #[error(transparent)]
    4196              :     Timeline(#[from] GetTimelineError),
    4197              : }
    4198              : 
    4199              : impl From<GetActiveTimelineError> for QueryError {
    4200            0 :     fn from(e: GetActiveTimelineError) -> Self {
    4201            0 :         match e {
    4202            0 :             GetActiveTimelineError::Tenant(GetActiveTenantError::Cancelled) => QueryError::Shutdown,
    4203            0 :             GetActiveTimelineError::Tenant(e) => e.into(),
    4204            0 :             GetActiveTimelineError::Timeline(e) => QueryError::NotFound(format!("{e}").into()),
    4205              :         }
    4206            0 :     }
    4207              : }
    4208              : 
    4209              : impl From<GetActiveTimelineError> for tonic::Status {
    4210            0 :     fn from(err: GetActiveTimelineError) -> Self {
    4211            0 :         let message = err.to_string();
    4212            0 :         let code = match err {
    4213            0 :             GetActiveTimelineError::Tenant(err) => tonic::Status::from(err).code(),
    4214            0 :             GetActiveTimelineError::Timeline(err) => tonic::Status::from(err).code(),
    4215              :         };
    4216            0 :         tonic::Status::new(code, message)
    4217            0 :     }
    4218              : }
    4219              : 
    4220              : impl From<GetTimelineError> for tonic::Status {
    4221            0 :     fn from(err: GetTimelineError) -> Self {
    4222              :         use tonic::Code;
    4223            0 :         let code = match &err {
    4224            0 :             GetTimelineError::NotFound { .. } => Code::NotFound,
    4225            0 :             GetTimelineError::NotActive { .. } => Code::Unavailable,
    4226            0 :             GetTimelineError::ShuttingDown => Code::Unavailable,
    4227              :         };
    4228            0 :         tonic::Status::new(code, err.to_string())
    4229            0 :     }
    4230              : }
    4231              : 
    4232              : impl From<GetActiveTenantError> for QueryError {
    4233            0 :     fn from(e: GetActiveTenantError) -> Self {
    4234            0 :         match e {
    4235            0 :             GetActiveTenantError::WaitForActiveTimeout { .. } => QueryError::Disconnected(
    4236            0 :                 ConnectionError::Io(io::Error::new(io::ErrorKind::TimedOut, e.to_string())),
    4237            0 :             ),
    4238              :             GetActiveTenantError::Cancelled
    4239              :             | GetActiveTenantError::WillNotBecomeActive(TenantState::Stopping { .. }) => {
    4240            0 :                 QueryError::Shutdown
    4241              :             }
    4242            0 :             e @ GetActiveTenantError::NotFound(_) => QueryError::NotFound(format!("{e}").into()),
    4243            0 :             e => QueryError::Other(anyhow::anyhow!(e)),
    4244              :         }
    4245            0 :     }
    4246              : }
    4247              : 
    4248              : impl From<GetActiveTenantError> for tonic::Status {
    4249            0 :     fn from(err: GetActiveTenantError) -> Self {
    4250              :         use tonic::Code;
    4251            0 :         let code = match &err {
    4252            0 :             GetActiveTenantError::Broken(_) => Code::Internal,
    4253            0 :             GetActiveTenantError::Cancelled => Code::Unavailable,
    4254            0 :             GetActiveTenantError::NotFound(_) => Code::NotFound,
    4255            0 :             GetActiveTenantError::SwitchedTenant => Code::Unavailable,
    4256            0 :             GetActiveTenantError::WaitForActiveTimeout { .. } => Code::Unavailable,
    4257            0 :             GetActiveTenantError::WillNotBecomeActive(_) => Code::Unavailable,
    4258              :         };
    4259            0 :         tonic::Status::new(code, err.to_string())
    4260            0 :     }
    4261              : }
    4262              : 
    4263              : impl From<HandleUpgradeError> for QueryError {
    4264            0 :     fn from(e: HandleUpgradeError) -> Self {
    4265            0 :         match e {
    4266            0 :             HandleUpgradeError::ShutDown => QueryError::Shutdown,
    4267              :         }
    4268            0 :     }
    4269              : }
    4270              : 
    4271              : impl From<HandleUpgradeError> for tonic::Status {
    4272            0 :     fn from(err: HandleUpgradeError) -> Self {
    4273            0 :         match err {
    4274            0 :             HandleUpgradeError::ShutDown => tonic::Status::unavailable("timeline is shutting down"),
    4275              :         }
    4276            0 :     }
    4277              : }
    4278              : 
    4279            0 : fn set_tracing_field_shard_id(timeline: &Timeline) {
    4280            0 :     debug_assert_current_span_has_tenant_and_timeline_id_no_shard_id();
    4281            0 :     tracing::Span::current().record(
    4282            0 :         "shard_id",
    4283            0 :         tracing::field::display(timeline.tenant_shard_id.shard_slug()),
    4284              :     );
    4285            0 :     debug_assert_current_span_has_tenant_and_timeline_id();
    4286            0 : }
    4287              : 
    4288              : struct WaitedForLsn(Lsn);
    4289              : impl From<WaitedForLsn> for Lsn {
    4290            0 :     fn from(WaitedForLsn(lsn): WaitedForLsn) -> Self {
    4291            0 :         lsn
    4292            0 :     }
    4293              : }
    4294              : 
    4295              : #[cfg(test)]
    4296              : mod tests {
    4297              :     use utils::shard::ShardCount;
    4298              : 
    4299              :     use super::*;
    4300              : 
    4301              :     #[test]
    4302            1 :     fn pageservice_cmd_parse() {
    4303            1 :         let tenant_id = TenantId::generate();
    4304            1 :         let timeline_id = TimelineId::generate();
    4305            1 :         let cmd =
    4306            1 :             PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id} {timeline_id}")).unwrap();
    4307            1 :         assert_eq!(
    4308              :             cmd,
    4309            1 :             PageServiceCmd::PageStream(PageStreamCmd {
    4310            1 :                 tenant_id,
    4311            1 :                 timeline_id,
    4312            1 :                 protocol_version: PagestreamProtocolVersion::V2,
    4313            1 :             })
    4314              :         );
    4315            1 :         let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id}")).unwrap();
    4316            1 :         assert_eq!(
    4317              :             cmd,
    4318            1 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    4319            1 :                 tenant_id,
    4320            1 :                 timeline_id,
    4321            1 :                 lsn: None,
    4322            1 :                 gzip: false,
    4323            1 :                 replica: false
    4324            1 :             })
    4325              :         );
    4326            1 :         let cmd =
    4327            1 :             PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} --gzip")).unwrap();
    4328            1 :         assert_eq!(
    4329              :             cmd,
    4330            1 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    4331            1 :                 tenant_id,
    4332            1 :                 timeline_id,
    4333            1 :                 lsn: None,
    4334            1 :                 gzip: true,
    4335            1 :                 replica: false
    4336            1 :             })
    4337              :         );
    4338            1 :         let cmd =
    4339            1 :             PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} latest")).unwrap();
    4340            1 :         assert_eq!(
    4341              :             cmd,
    4342            1 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    4343            1 :                 tenant_id,
    4344            1 :                 timeline_id,
    4345            1 :                 lsn: None,
    4346            1 :                 gzip: false,
    4347            1 :                 replica: false
    4348            1 :             })
    4349              :         );
    4350            1 :         let cmd = PageServiceCmd::parse(&format!("basebackup {tenant_id} {timeline_id} 0/16ABCDE"))
    4351            1 :             .unwrap();
    4352            1 :         assert_eq!(
    4353              :             cmd,
    4354            1 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    4355            1 :                 tenant_id,
    4356            1 :                 timeline_id,
    4357            1 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    4358            1 :                 gzip: false,
    4359            1 :                 replica: false
    4360            1 :             })
    4361              :         );
    4362            1 :         let cmd = PageServiceCmd::parse(&format!(
    4363            1 :             "basebackup {tenant_id} {timeline_id} --replica --gzip"
    4364            1 :         ))
    4365            1 :         .unwrap();
    4366            1 :         assert_eq!(
    4367              :             cmd,
    4368            1 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    4369            1 :                 tenant_id,
    4370            1 :                 timeline_id,
    4371            1 :                 lsn: None,
    4372            1 :                 gzip: true,
    4373            1 :                 replica: true
    4374            1 :             })
    4375              :         );
    4376            1 :         let cmd = PageServiceCmd::parse(&format!(
    4377            1 :             "basebackup {tenant_id} {timeline_id} 0/16ABCDE --replica --gzip"
    4378            1 :         ))
    4379            1 :         .unwrap();
    4380            1 :         assert_eq!(
    4381              :             cmd,
    4382            1 :             PageServiceCmd::BaseBackup(BaseBackupCmd {
    4383            1 :                 tenant_id,
    4384            1 :                 timeline_id,
    4385            1 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    4386            1 :                 gzip: true,
    4387            1 :                 replica: true
    4388            1 :             })
    4389              :         );
    4390            1 :         let cmd = PageServiceCmd::parse(&format!("fullbackup {tenant_id} {timeline_id}")).unwrap();
    4391            1 :         assert_eq!(
    4392              :             cmd,
    4393            1 :             PageServiceCmd::FullBackup(FullBackupCmd {
    4394            1 :                 tenant_id,
    4395            1 :                 timeline_id,
    4396            1 :                 lsn: None,
    4397            1 :                 prev_lsn: None
    4398            1 :             })
    4399              :         );
    4400            1 :         let cmd = PageServiceCmd::parse(&format!(
    4401            1 :             "fullbackup {tenant_id} {timeline_id} 0/16ABCDE 0/16ABCDF"
    4402            1 :         ))
    4403            1 :         .unwrap();
    4404            1 :         assert_eq!(
    4405              :             cmd,
    4406            1 :             PageServiceCmd::FullBackup(FullBackupCmd {
    4407            1 :                 tenant_id,
    4408            1 :                 timeline_id,
    4409            1 :                 lsn: Some(Lsn::from_str("0/16ABCDE").unwrap()),
    4410            1 :                 prev_lsn: Some(Lsn::from_str("0/16ABCDF").unwrap()),
    4411            1 :             })
    4412              :         );
    4413            1 :         let tenant_shard_id = TenantShardId::unsharded(tenant_id);
    4414            1 :         let cmd = PageServiceCmd::parse(&format!(
    4415            1 :             "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
    4416            1 :         ))
    4417            1 :         .unwrap();
    4418            1 :         assert_eq!(
    4419              :             cmd,
    4420            1 :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    4421            1 :                 tenant_shard_id,
    4422            1 :                 timeline_id,
    4423            1 :                 lsn: Lsn::from_str("0/16ABCDE").unwrap(),
    4424            1 :             })
    4425              :         );
    4426            1 :         let tenant_shard_id = TenantShardId::split(&tenant_shard_id, ShardCount(8))[1];
    4427            1 :         let cmd = PageServiceCmd::parse(&format!(
    4428            1 :             "lease lsn {tenant_shard_id} {timeline_id} 0/16ABCDE"
    4429            1 :         ))
    4430            1 :         .unwrap();
    4431            1 :         assert_eq!(
    4432              :             cmd,
    4433            1 :             PageServiceCmd::LeaseLsn(LeaseLsnCmd {
    4434            1 :                 tenant_shard_id,
    4435            1 :                 timeline_id,
    4436            1 :                 lsn: Lsn::from_str("0/16ABCDE").unwrap(),
    4437            1 :             })
    4438              :         );
    4439            1 :         let cmd = PageServiceCmd::parse("set a = b").unwrap();
    4440            1 :         assert_eq!(cmd, PageServiceCmd::Set);
    4441            1 :         let cmd = PageServiceCmd::parse("SET foo").unwrap();
    4442            1 :         assert_eq!(cmd, PageServiceCmd::Set);
    4443            1 :     }
    4444              : 
    4445              :     #[test]
    4446            1 :     fn pageservice_cmd_err_handling() {
    4447            1 :         let tenant_id = TenantId::generate();
    4448            1 :         let timeline_id = TimelineId::generate();
    4449            1 :         let cmd = PageServiceCmd::parse("unknown_command");
    4450            1 :         assert!(cmd.is_err());
    4451            1 :         let cmd = PageServiceCmd::parse("pagestream_v2");
    4452            1 :         assert!(cmd.is_err());
    4453            1 :         let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx"));
    4454            1 :         assert!(cmd.is_err());
    4455            1 :         let cmd = PageServiceCmd::parse(&format!("pagestream_v2 {tenant_id}xxx {timeline_id}xxx"));
    4456            1 :         assert!(cmd.is_err());
    4457            1 :         let cmd = PageServiceCmd::parse(&format!(
    4458            1 :             "basebackup {tenant_id} {timeline_id} --gzip --gzip"
    4459            1 :         ));
    4460            1 :         assert!(cmd.is_err());
    4461            1 :         let cmd = PageServiceCmd::parse(&format!(
    4462            1 :             "basebackup {tenant_id} {timeline_id} --gzip --unknown"
    4463            1 :         ));
    4464            1 :         assert!(cmd.is_err());
    4465            1 :         let cmd = PageServiceCmd::parse(&format!(
    4466            1 :             "basebackup {tenant_id} {timeline_id} --gzip 0/16ABCDE"
    4467            1 :         ));
    4468            1 :         assert!(cmd.is_err());
    4469            1 :         let cmd = PageServiceCmd::parse(&format!("lease {tenant_id} {timeline_id} gzip 0/16ABCDE"));
    4470            1 :         assert!(cmd.is_err());
    4471            1 :     }
    4472              : 
    4473              :     #[test]
    4474            1 :     fn test_parse_options() {
    4475            1 :         let (config, has_error) = parse_options(" -c neon.compute_mode=primary ");
    4476            1 :         assert!(!has_error);
    4477            1 :         assert_eq!(
    4478              :             config,
    4479            1 :             vec![("neon.compute_mode".to_string(), "primary".to_string())]
    4480              :         );
    4481              : 
    4482            1 :         let (config, has_error) = parse_options(" -c neon.compute_mode=primary -c foo=bar ");
    4483            1 :         assert!(!has_error);
    4484            1 :         assert_eq!(
    4485              :             config,
    4486            1 :             vec![
    4487            1 :                 ("neon.compute_mode".to_string(), "primary".to_string()),
    4488            1 :                 ("foo".to_string(), "bar".to_string()),
    4489              :             ]
    4490              :         );
    4491              : 
    4492            1 :         let (config, has_error) = parse_options(" -c neon.compute_mode=primary -cfoo=bar");
    4493            1 :         assert!(!has_error);
    4494            1 :         assert_eq!(
    4495              :             config,
    4496            1 :             vec![
    4497            1 :                 ("neon.compute_mode".to_string(), "primary".to_string()),
    4498            1 :                 ("foo".to_string(), "bar".to_string()),
    4499              :             ]
    4500              :         );
    4501              : 
    4502            1 :         let (_, has_error) = parse_options("-c");
    4503            1 :         assert!(has_error);
    4504              : 
    4505            1 :         let (_, has_error) = parse_options("-c foo=bar -c -c");
    4506            1 :         assert!(has_error);
    4507              : 
    4508            1 :         let (_, has_error) = parse_options("    ");
    4509            1 :         assert!(!has_error);
    4510              : 
    4511            1 :         let (_, has_error) = parse_options(" -c neon.compute_mode");
    4512            1 :         assert!(has_error);
    4513            1 :     }
    4514              : }
        

Generated by: LCOV version 2.1-beta