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