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