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