LCOV - code coverage report
Current view: top level - libs/pageserver_api/src - models.rs (source / functions) Coverage Total Hit
Test: 727bdccc1d7d53837da843959afb612f56da4e79.info Lines: 55.4 % 1069 592
Test Date: 2025-01-30 15:18:43 Functions: 6.9 % 896 62

            Line data    Source code
       1              : pub mod detach_ancestor;
       2              : pub mod partitioning;
       3              : pub mod utilization;
       4              : 
       5              : #[cfg(feature = "testing")]
       6              : use camino::Utf8PathBuf;
       7              : pub use utilization::PageserverUtilization;
       8              : 
       9              : use core::ops::Range;
      10              : use std::{
      11              :     collections::HashMap,
      12              :     fmt::Display,
      13              :     io::{BufRead, Read},
      14              :     num::{NonZeroU32, NonZeroU64, NonZeroUsize},
      15              :     str::FromStr,
      16              :     time::{Duration, SystemTime},
      17              : };
      18              : 
      19              : use byteorder::{BigEndian, ReadBytesExt};
      20              : use postgres_ffi::BLCKSZ;
      21              : use serde::{Deserialize, Deserializer, Serialize, Serializer};
      22              : use serde_with::serde_as;
      23              : use utils::{
      24              :     completion,
      25              :     id::{NodeId, TenantId, TimelineId},
      26              :     lsn::Lsn,
      27              :     postgres_client::PostgresClientProtocol,
      28              :     serde_system_time,
      29              : };
      30              : 
      31              : use crate::{
      32              :     key::{CompactKey, Key},
      33              :     reltag::RelTag,
      34              :     shard::{ShardCount, ShardStripeSize, TenantShardId},
      35              : };
      36              : use bytes::{Buf, BufMut, Bytes, BytesMut};
      37              : 
      38              : /// The state of a tenant in this pageserver.
      39              : ///
      40              : /// ```mermaid
      41              : /// stateDiagram-v2
      42              : ///
      43              : ///     [*] --> Attaching: spawn_attach()
      44              : ///
      45              : ///     Attaching --> Activating: activate()
      46              : ///     Activating --> Active: infallible
      47              : ///
      48              : ///     Attaching --> Broken: attach() failure
      49              : ///
      50              : ///     Active --> Stopping: set_stopping(), part of shutdown & detach
      51              : ///     Stopping --> Broken: late error in remove_tenant_from_memory
      52              : ///
      53              : ///     Broken --> [*]: ignore / detach / shutdown
      54              : ///     Stopping --> [*]: remove_from_memory complete
      55              : ///
      56              : ///     Active --> Broken: cfg(testing)-only tenant break point
      57              : /// ```
      58              : #[derive(
      59              :     Clone,
      60              :     PartialEq,
      61              :     Eq,
      62            0 :     serde::Serialize,
      63            1 :     serde::Deserialize,
      64              :     strum_macros::Display,
      65              :     strum_macros::VariantNames,
      66              :     strum_macros::AsRefStr,
      67              :     strum_macros::IntoStaticStr,
      68              : )]
      69              : #[serde(tag = "slug", content = "data")]
      70              : pub enum TenantState {
      71              :     /// This tenant is being attached to the pageserver.
      72              :     ///
      73              :     /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
      74              :     Attaching,
      75              :     /// The tenant is transitioning from Loading/Attaching to Active.
      76              :     ///
      77              :     /// While in this state, the individual timelines are being activated.
      78              :     ///
      79              :     /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
      80              :     Activating(ActivatingFrom),
      81              :     /// The tenant has finished activating and is open for business.
      82              :     ///
      83              :     /// Transitions out of this state are possible through `set_stopping()` and `set_broken()`.
      84              :     Active,
      85              :     /// The tenant is recognized by pageserver, but it is being detached or the
      86              :     /// system is being shut down.
      87              :     ///
      88              :     /// Transitions out of this state are possible through `set_broken()`.
      89              :     Stopping {
      90              :         // Because of https://github.com/serde-rs/serde/issues/2105 this has to be a named field,
      91              :         // otherwise it will not be skipped during deserialization
      92              :         #[serde(skip)]
      93              :         progress: completion::Barrier,
      94              :     },
      95              :     /// The tenant is recognized by the pageserver, but can no longer be used for
      96              :     /// any operations.
      97              :     ///
      98              :     /// If the tenant fails to load or attach, it will transition to this state
      99              :     /// and it is guaranteed that no background tasks are running in its name.
     100              :     ///
     101              :     /// The other way to transition into this state is from `Stopping` state
     102              :     /// through `set_broken()` called from `remove_tenant_from_memory()`. That happens
     103              :     /// if the cleanup future executed by `remove_tenant_from_memory()` fails.
     104              :     Broken { reason: String, backtrace: String },
     105              : }
     106              : 
     107              : impl TenantState {
     108            0 :     pub fn attachment_status(&self) -> TenantAttachmentStatus {
     109              :         use TenantAttachmentStatus::*;
     110              : 
     111              :         // Below TenantState::Activating is used as "transient" or "transparent" state for
     112              :         // attachment_status determining.
     113            0 :         match self {
     114              :             // The attach procedure writes the marker file before adding the Attaching tenant to the tenants map.
     115              :             // So, technically, we can return Attached here.
     116              :             // However, as soon as Console observes Attached, it will proceed with the Postgres-level health check.
     117              :             // But, our attach task might still be fetching the remote timelines, etc.
     118              :             // So, return `Maybe` while Attaching, making Console wait for the attach task to finish.
     119            0 :             Self::Attaching | Self::Activating(ActivatingFrom::Attaching) => Maybe,
     120              :             // We only reach Active after successful load / attach.
     121              :             // So, call atttachment status Attached.
     122            0 :             Self::Active => Attached,
     123              :             // If the (initial or resumed) attach procedure fails, the tenant becomes Broken.
     124              :             // However, it also becomes Broken if the regular load fails.
     125              :             // From Console's perspective there's no practical difference
     126              :             // because attachment_status is polled by console only during attach operation execution.
     127            0 :             Self::Broken { reason, .. } => Failed {
     128            0 :                 reason: reason.to_owned(),
     129            0 :             },
     130              :             // Why is Stopping a Maybe case? Because, during pageserver shutdown,
     131              :             // we set the Stopping state irrespective of whether the tenant
     132              :             // has finished attaching or not.
     133            0 :             Self::Stopping { .. } => Maybe,
     134              :         }
     135            0 :     }
     136              : 
     137            0 :     pub fn broken_from_reason(reason: String) -> Self {
     138            0 :         let backtrace_str: String = format!("{}", std::backtrace::Backtrace::force_capture());
     139            0 :         Self::Broken {
     140            0 :             reason,
     141            0 :             backtrace: backtrace_str,
     142            0 :         }
     143            0 :     }
     144              : }
     145              : 
     146              : impl std::fmt::Debug for TenantState {
     147            2 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     148            2 :         match self {
     149            2 :             Self::Broken { reason, backtrace } if !reason.is_empty() => {
     150            2 :                 write!(f, "Broken due to: {reason}. Backtrace:\n{backtrace}")
     151              :             }
     152            0 :             _ => write!(f, "{self}"),
     153              :         }
     154            2 :     }
     155              : }
     156              : 
     157              : /// A temporary lease to a specific lsn inside a timeline.
     158              : /// Access to the lsn is guaranteed by the pageserver until the expiration indicated by `valid_until`.
     159              : #[serde_as]
     160            0 : #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
     161              : pub struct LsnLease {
     162              :     #[serde_as(as = "SystemTimeAsRfc3339Millis")]
     163              :     pub valid_until: SystemTime,
     164              : }
     165              : 
     166              : serde_with::serde_conv!(
     167              :     SystemTimeAsRfc3339Millis,
     168              :     SystemTime,
     169            0 :     |time: &SystemTime| humantime::format_rfc3339_millis(*time).to_string(),
     170            0 :     |value: String| -> Result<_, humantime::TimestampError> { humantime::parse_rfc3339(&value) }
     171              : );
     172              : 
     173              : impl LsnLease {
     174              :     /// The default length for an explicit LSN lease request (10 minutes).
     175              :     pub const DEFAULT_LENGTH: Duration = Duration::from_secs(10 * 60);
     176              : 
     177              :     /// The default length for an implicit LSN lease granted during
     178              :     /// `get_lsn_by_timestamp` request (1 minutes).
     179              :     pub const DEFAULT_LENGTH_FOR_TS: Duration = Duration::from_secs(60);
     180              : 
     181              :     /// Checks whether the lease is expired.
     182           12 :     pub fn is_expired(&self, now: &SystemTime) -> bool {
     183           12 :         now > &self.valid_until
     184           12 :     }
     185              : }
     186              : 
     187              : /// The only [`TenantState`] variants we could be `TenantState::Activating` from.
     188              : ///
     189              : /// XXX: We used to have more variants here, but now it's just one, which makes this rather
     190              : /// useless. Remove, once we've checked that there's no client code left that looks at this.
     191            1 : #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
     192              : pub enum ActivatingFrom {
     193              :     /// Arrived to [`TenantState::Activating`] from [`TenantState::Attaching`]
     194              :     Attaching,
     195              : }
     196              : 
     197              : /// A state of a timeline in pageserver's memory.
     198            0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
     199              : pub enum TimelineState {
     200              :     /// The timeline is recognized by the pageserver but is not yet operational.
     201              :     /// In particular, the walreceiver connection loop is not running for this timeline.
     202              :     /// It will eventually transition to state Active or Broken.
     203              :     Loading,
     204              :     /// The timeline is fully operational.
     205              :     /// It can be queried, and the walreceiver connection loop is running.
     206              :     Active,
     207              :     /// The timeline was previously Loading or Active but is shutting down.
     208              :     /// It cannot transition back into any other state.
     209              :     Stopping,
     210              :     /// The timeline is broken and not operational (previous states: Loading or Active).
     211              :     Broken { reason: String, backtrace: String },
     212              : }
     213              : 
     214              : #[serde_with::serde_as]
     215            0 : #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
     216              : pub struct CompactLsnRange {
     217              :     pub start: Lsn,
     218              :     pub end: Lsn,
     219              : }
     220              : 
     221              : #[serde_with::serde_as]
     222            0 : #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
     223              : pub struct CompactKeyRange {
     224              :     #[serde_as(as = "serde_with::DisplayFromStr")]
     225              :     pub start: Key,
     226              :     #[serde_as(as = "serde_with::DisplayFromStr")]
     227              :     pub end: Key,
     228              : }
     229              : 
     230              : impl From<Range<Lsn>> for CompactLsnRange {
     231           12 :     fn from(range: Range<Lsn>) -> Self {
     232           12 :         Self {
     233           12 :             start: range.start,
     234           12 :             end: range.end,
     235           12 :         }
     236           12 :     }
     237              : }
     238              : 
     239              : impl From<Range<Key>> for CompactKeyRange {
     240           32 :     fn from(range: Range<Key>) -> Self {
     241           32 :         Self {
     242           32 :             start: range.start,
     243           32 :             end: range.end,
     244           32 :         }
     245           32 :     }
     246              : }
     247              : 
     248              : impl From<CompactLsnRange> for Range<Lsn> {
     249           20 :     fn from(range: CompactLsnRange) -> Self {
     250           20 :         range.start..range.end
     251           20 :     }
     252              : }
     253              : 
     254              : impl From<CompactKeyRange> for Range<Key> {
     255           32 :     fn from(range: CompactKeyRange) -> Self {
     256           32 :         range.start..range.end
     257           32 :     }
     258              : }
     259              : 
     260              : impl CompactLsnRange {
     261            8 :     pub fn above(lsn: Lsn) -> Self {
     262            8 :         Self {
     263            8 :             start: lsn,
     264            8 :             end: Lsn::MAX,
     265            8 :         }
     266            8 :     }
     267              : }
     268              : 
     269              : #[derive(Debug, Clone, Serialize)]
     270              : pub struct CompactInfoResponse {
     271              :     pub compact_key_range: Option<CompactKeyRange>,
     272              :     pub compact_lsn_range: Option<CompactLsnRange>,
     273              :     pub sub_compaction: bool,
     274              :     pub running: bool,
     275              :     pub job_id: usize,
     276              : }
     277              : 
     278            0 : #[derive(Serialize, Deserialize, Clone)]
     279              : pub struct TimelineCreateRequest {
     280              :     pub new_timeline_id: TimelineId,
     281              :     #[serde(flatten)]
     282              :     pub mode: TimelineCreateRequestMode,
     283              : }
     284              : 
     285            0 : #[derive(Serialize, Deserialize, Clone)]
     286              : #[serde(untagged)]
     287              : pub enum TimelineCreateRequestMode {
     288              :     Branch {
     289              :         ancestor_timeline_id: TimelineId,
     290              :         #[serde(default)]
     291              :         ancestor_start_lsn: Option<Lsn>,
     292              :         // TODO: cplane sets this, but, the branching code always
     293              :         // inherits the ancestor's pg_version. Earlier code wasn't
     294              :         // using a flattened enum, so, it was an accepted field, and
     295              :         // we continue to accept it by having it here.
     296              :         pg_version: Option<u32>,
     297              :     },
     298              :     ImportPgdata {
     299              :         import_pgdata: TimelineCreateRequestModeImportPgdata,
     300              :     },
     301              :     // NB: Bootstrap is all-optional, and thus the serde(untagged) will cause serde to stop at Bootstrap.
     302              :     // (serde picks the first matching enum variant, in declaration order).
     303              :     Bootstrap {
     304              :         #[serde(default)]
     305              :         existing_initdb_timeline_id: Option<TimelineId>,
     306              :         pg_version: Option<u32>,
     307              :     },
     308              : }
     309              : 
     310            0 : #[derive(Serialize, Deserialize, Clone)]
     311              : pub struct TimelineCreateRequestModeImportPgdata {
     312              :     pub location: ImportPgdataLocation,
     313              :     pub idempotency_key: ImportPgdataIdempotencyKey,
     314              : }
     315              : 
     316            0 : #[derive(Serialize, Deserialize, Clone, Debug)]
     317              : pub enum ImportPgdataLocation {
     318              :     #[cfg(feature = "testing")]
     319              :     LocalFs { path: Utf8PathBuf },
     320              :     AwsS3 {
     321              :         region: String,
     322              :         bucket: String,
     323              :         /// A better name for this would be `prefix`; changing requires coordination with cplane.
     324              :         /// See <https://github.com/neondatabase/cloud/issues/20646>.
     325              :         key: String,
     326              :     },
     327              : }
     328              : 
     329            0 : #[derive(Serialize, Deserialize, Clone)]
     330              : #[serde(transparent)]
     331              : pub struct ImportPgdataIdempotencyKey(pub String);
     332              : 
     333              : impl ImportPgdataIdempotencyKey {
     334            0 :     pub fn random() -> Self {
     335              :         use rand::{distributions::Alphanumeric, Rng};
     336            0 :         Self(
     337            0 :             rand::thread_rng()
     338            0 :                 .sample_iter(&Alphanumeric)
     339            0 :                 .take(20)
     340            0 :                 .map(char::from)
     341            0 :                 .collect(),
     342            0 :         )
     343            0 :     }
     344              : }
     345              : 
     346            0 : #[derive(Serialize, Deserialize, Clone)]
     347              : pub struct LsnLeaseRequest {
     348              :     pub lsn: Lsn,
     349              : }
     350              : 
     351            0 : #[derive(Serialize, Deserialize)]
     352              : pub struct TenantShardSplitRequest {
     353              :     pub new_shard_count: u8,
     354              : 
     355              :     // A tenant's stripe size is only meaningful the first time their shard count goes
     356              :     // above 1: therefore during a split from 1->N shards, we may modify the stripe size.
     357              :     //
     358              :     // If this is set while the stripe count is being increased from an already >1 value,
     359              :     // then the request will fail with 400.
     360              :     pub new_stripe_size: Option<ShardStripeSize>,
     361              : }
     362              : 
     363            0 : #[derive(Serialize, Deserialize)]
     364              : pub struct TenantShardSplitResponse {
     365              :     pub new_shards: Vec<TenantShardId>,
     366              : }
     367              : 
     368              : /// Parameters that apply to all shards in a tenant.  Used during tenant creation.
     369            0 : #[derive(Serialize, Deserialize, Debug)]
     370              : #[serde(deny_unknown_fields)]
     371              : pub struct ShardParameters {
     372              :     pub count: ShardCount,
     373              :     pub stripe_size: ShardStripeSize,
     374              : }
     375              : 
     376              : impl ShardParameters {
     377              :     pub const DEFAULT_STRIPE_SIZE: ShardStripeSize = ShardStripeSize(256 * 1024 / 8);
     378              : 
     379            0 :     pub fn is_unsharded(&self) -> bool {
     380            0 :         self.count.is_unsharded()
     381            0 :     }
     382              : }
     383              : 
     384              : impl Default for ShardParameters {
     385          441 :     fn default() -> Self {
     386          441 :         Self {
     387          441 :             count: ShardCount::new(0),
     388          441 :             stripe_size: Self::DEFAULT_STRIPE_SIZE,
     389          441 :         }
     390          441 :     }
     391              : }
     392              : 
     393              : #[derive(Debug, Default, Clone, Eq, PartialEq)]
     394              : pub enum FieldPatch<T> {
     395              :     Upsert(T),
     396              :     Remove,
     397              :     #[default]
     398              :     Noop,
     399              : }
     400              : 
     401              : impl<T> FieldPatch<T> {
     402           64 :     fn is_noop(&self) -> bool {
     403           64 :         matches!(self, FieldPatch::Noop)
     404           64 :     }
     405              : 
     406           32 :     pub fn apply(self, target: &mut Option<T>) {
     407           32 :         match self {
     408            1 :             Self::Upsert(v) => *target = Some(v),
     409            1 :             Self::Remove => *target = None,
     410           30 :             Self::Noop => {}
     411              :         }
     412           32 :     }
     413              : 
     414            0 :     pub fn map<U, E, F: FnOnce(T) -> Result<U, E>>(self, map: F) -> Result<FieldPatch<U>, E> {
     415            0 :         match self {
     416            0 :             Self::Upsert(v) => Ok(FieldPatch::<U>::Upsert(map(v)?)),
     417            0 :             Self::Remove => Ok(FieldPatch::<U>::Remove),
     418            0 :             Self::Noop => Ok(FieldPatch::<U>::Noop),
     419              :         }
     420            0 :     }
     421              : }
     422              : 
     423              : impl<'de, T: Deserialize<'de>> Deserialize<'de> for FieldPatch<T> {
     424            2 :     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
     425            2 :     where
     426            2 :         D: Deserializer<'de>,
     427            2 :     {
     428            2 :         Option::deserialize(deserializer).map(|opt| match opt {
     429            1 :             None => FieldPatch::Remove,
     430            1 :             Some(val) => FieldPatch::Upsert(val),
     431            2 :         })
     432            2 :     }
     433              : }
     434              : 
     435              : impl<T: Serialize> Serialize for FieldPatch<T> {
     436            2 :     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
     437            2 :     where
     438            2 :         S: Serializer,
     439            2 :     {
     440            2 :         match self {
     441            1 :             FieldPatch::Upsert(val) => serializer.serialize_some(val),
     442            1 :             FieldPatch::Remove => serializer.serialize_none(),
     443            0 :             FieldPatch::Noop => unreachable!(),
     444              :         }
     445            2 :     }
     446              : }
     447              : 
     448            2 : #[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
     449              : #[serde(default)]
     450              : pub struct TenantConfigPatch {
     451              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     452              :     pub checkpoint_distance: FieldPatch<u64>,
     453              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     454              :     pub checkpoint_timeout: FieldPatch<String>,
     455              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     456              :     pub compaction_target_size: FieldPatch<u64>,
     457              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     458              :     pub compaction_period: FieldPatch<String>,
     459              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     460              :     pub compaction_threshold: FieldPatch<usize>,
     461              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     462              :     pub compaction_upper_limit: FieldPatch<usize>,
     463              :     // defer parsing compaction_algorithm, like eviction_policy
     464              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     465              :     pub compaction_algorithm: FieldPatch<CompactionAlgorithmSettings>,
     466              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     467              :     pub l0_flush_delay_threshold: FieldPatch<usize>,
     468              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     469              :     pub l0_flush_stall_threshold: FieldPatch<usize>,
     470              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     471              :     pub l0_flush_wait_upload: FieldPatch<bool>,
     472              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     473              :     pub gc_horizon: FieldPatch<u64>,
     474              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     475              :     pub gc_period: FieldPatch<String>,
     476              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     477              :     pub image_creation_threshold: FieldPatch<usize>,
     478              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     479              :     pub pitr_interval: FieldPatch<String>,
     480              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     481              :     pub walreceiver_connect_timeout: FieldPatch<String>,
     482              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     483              :     pub lagging_wal_timeout: FieldPatch<String>,
     484              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     485              :     pub max_lsn_wal_lag: FieldPatch<NonZeroU64>,
     486              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     487              :     pub eviction_policy: FieldPatch<EvictionPolicy>,
     488              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     489              :     pub min_resident_size_override: FieldPatch<u64>,
     490              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     491              :     pub evictions_low_residence_duration_metric_threshold: FieldPatch<String>,
     492              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     493              :     pub heatmap_period: FieldPatch<String>,
     494              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     495              :     pub lazy_slru_download: FieldPatch<bool>,
     496              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     497              :     pub timeline_get_throttle: FieldPatch<ThrottleConfig>,
     498              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     499              :     pub image_layer_creation_check_threshold: FieldPatch<u8>,
     500              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     501              :     pub lsn_lease_length: FieldPatch<String>,
     502              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     503              :     pub lsn_lease_length_for_ts: FieldPatch<String>,
     504              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     505              :     pub timeline_offloading: FieldPatch<bool>,
     506              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     507              :     pub wal_receiver_protocol_override: FieldPatch<PostgresClientProtocol>,
     508              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     509              :     pub rel_size_v2_enabled: FieldPatch<bool>,
     510              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     511              :     pub gc_compaction_enabled: FieldPatch<bool>,
     512              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     513              :     pub gc_compaction_initial_threshold_kb: FieldPatch<u64>,
     514              :     #[serde(skip_serializing_if = "FieldPatch::is_noop")]
     515              :     pub gc_compaction_ratio_percent: FieldPatch<u64>,
     516              : }
     517              : 
     518              : /// An alternative representation of `pageserver::tenant::TenantConf` with
     519              : /// simpler types.
     520            0 : #[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
     521              : pub struct TenantConfig {
     522              :     pub checkpoint_distance: Option<u64>,
     523              :     pub checkpoint_timeout: Option<String>,
     524              :     pub compaction_target_size: Option<u64>,
     525              :     pub compaction_period: Option<String>,
     526              :     pub compaction_threshold: Option<usize>,
     527              :     pub compaction_upper_limit: Option<usize>,
     528              :     // defer parsing compaction_algorithm, like eviction_policy
     529              :     pub compaction_algorithm: Option<CompactionAlgorithmSettings>,
     530              :     pub l0_flush_delay_threshold: Option<usize>,
     531              :     pub l0_flush_stall_threshold: Option<usize>,
     532              :     pub l0_flush_wait_upload: Option<bool>,
     533              :     pub gc_horizon: Option<u64>,
     534              :     pub gc_period: Option<String>,
     535              :     pub image_creation_threshold: Option<usize>,
     536              :     pub pitr_interval: Option<String>,
     537              :     pub walreceiver_connect_timeout: Option<String>,
     538              :     pub lagging_wal_timeout: Option<String>,
     539              :     pub max_lsn_wal_lag: Option<NonZeroU64>,
     540              :     pub eviction_policy: Option<EvictionPolicy>,
     541              :     pub min_resident_size_override: Option<u64>,
     542              :     pub evictions_low_residence_duration_metric_threshold: Option<String>,
     543              :     pub heatmap_period: Option<String>,
     544              :     pub lazy_slru_download: Option<bool>,
     545              :     pub timeline_get_throttle: Option<ThrottleConfig>,
     546              :     pub image_layer_creation_check_threshold: Option<u8>,
     547              :     pub lsn_lease_length: Option<String>,
     548              :     pub lsn_lease_length_for_ts: Option<String>,
     549              :     pub timeline_offloading: Option<bool>,
     550              :     pub wal_receiver_protocol_override: Option<PostgresClientProtocol>,
     551              :     pub rel_size_v2_enabled: Option<bool>,
     552              :     pub gc_compaction_enabled: Option<bool>,
     553              :     pub gc_compaction_initial_threshold_kb: Option<u64>,
     554              :     pub gc_compaction_ratio_percent: Option<u64>,
     555              : }
     556              : 
     557              : impl TenantConfig {
     558            1 :     pub fn apply_patch(self, patch: TenantConfigPatch) -> TenantConfig {
     559            1 :         let Self {
     560            1 :             mut checkpoint_distance,
     561            1 :             mut checkpoint_timeout,
     562            1 :             mut compaction_target_size,
     563            1 :             mut compaction_period,
     564            1 :             mut compaction_threshold,
     565            1 :             mut compaction_upper_limit,
     566            1 :             mut compaction_algorithm,
     567            1 :             mut l0_flush_delay_threshold,
     568            1 :             mut l0_flush_stall_threshold,
     569            1 :             mut l0_flush_wait_upload,
     570            1 :             mut gc_horizon,
     571            1 :             mut gc_period,
     572            1 :             mut image_creation_threshold,
     573            1 :             mut pitr_interval,
     574            1 :             mut walreceiver_connect_timeout,
     575            1 :             mut lagging_wal_timeout,
     576            1 :             mut max_lsn_wal_lag,
     577            1 :             mut eviction_policy,
     578            1 :             mut min_resident_size_override,
     579            1 :             mut evictions_low_residence_duration_metric_threshold,
     580            1 :             mut heatmap_period,
     581            1 :             mut lazy_slru_download,
     582            1 :             mut timeline_get_throttle,
     583            1 :             mut image_layer_creation_check_threshold,
     584            1 :             mut lsn_lease_length,
     585            1 :             mut lsn_lease_length_for_ts,
     586            1 :             mut timeline_offloading,
     587            1 :             mut wal_receiver_protocol_override,
     588            1 :             mut rel_size_v2_enabled,
     589            1 :             mut gc_compaction_enabled,
     590            1 :             mut gc_compaction_initial_threshold_kb,
     591            1 :             mut gc_compaction_ratio_percent,
     592            1 :         } = self;
     593            1 : 
     594            1 :         patch.checkpoint_distance.apply(&mut checkpoint_distance);
     595            1 :         patch.checkpoint_timeout.apply(&mut checkpoint_timeout);
     596            1 :         patch
     597            1 :             .compaction_target_size
     598            1 :             .apply(&mut compaction_target_size);
     599            1 :         patch.compaction_period.apply(&mut compaction_period);
     600            1 :         patch.compaction_threshold.apply(&mut compaction_threshold);
     601            1 :         patch
     602            1 :             .compaction_upper_limit
     603            1 :             .apply(&mut compaction_upper_limit);
     604            1 :         patch.compaction_algorithm.apply(&mut compaction_algorithm);
     605            1 :         patch
     606            1 :             .l0_flush_delay_threshold
     607            1 :             .apply(&mut l0_flush_delay_threshold);
     608            1 :         patch
     609            1 :             .l0_flush_stall_threshold
     610            1 :             .apply(&mut l0_flush_stall_threshold);
     611            1 :         patch.l0_flush_wait_upload.apply(&mut l0_flush_wait_upload);
     612            1 :         patch.gc_horizon.apply(&mut gc_horizon);
     613            1 :         patch.gc_period.apply(&mut gc_period);
     614            1 :         patch
     615            1 :             .image_creation_threshold
     616            1 :             .apply(&mut image_creation_threshold);
     617            1 :         patch.pitr_interval.apply(&mut pitr_interval);
     618            1 :         patch
     619            1 :             .walreceiver_connect_timeout
     620            1 :             .apply(&mut walreceiver_connect_timeout);
     621            1 :         patch.lagging_wal_timeout.apply(&mut lagging_wal_timeout);
     622            1 :         patch.max_lsn_wal_lag.apply(&mut max_lsn_wal_lag);
     623            1 :         patch.eviction_policy.apply(&mut eviction_policy);
     624            1 :         patch
     625            1 :             .min_resident_size_override
     626            1 :             .apply(&mut min_resident_size_override);
     627            1 :         patch
     628            1 :             .evictions_low_residence_duration_metric_threshold
     629            1 :             .apply(&mut evictions_low_residence_duration_metric_threshold);
     630            1 :         patch.heatmap_period.apply(&mut heatmap_period);
     631            1 :         patch.lazy_slru_download.apply(&mut lazy_slru_download);
     632            1 :         patch
     633            1 :             .timeline_get_throttle
     634            1 :             .apply(&mut timeline_get_throttle);
     635            1 :         patch
     636            1 :             .image_layer_creation_check_threshold
     637            1 :             .apply(&mut image_layer_creation_check_threshold);
     638            1 :         patch.lsn_lease_length.apply(&mut lsn_lease_length);
     639            1 :         patch
     640            1 :             .lsn_lease_length_for_ts
     641            1 :             .apply(&mut lsn_lease_length_for_ts);
     642            1 :         patch.timeline_offloading.apply(&mut timeline_offloading);
     643            1 :         patch
     644            1 :             .wal_receiver_protocol_override
     645            1 :             .apply(&mut wal_receiver_protocol_override);
     646            1 :         patch.rel_size_v2_enabled.apply(&mut rel_size_v2_enabled);
     647            1 :         patch
     648            1 :             .gc_compaction_enabled
     649            1 :             .apply(&mut gc_compaction_enabled);
     650            1 :         patch
     651            1 :             .gc_compaction_initial_threshold_kb
     652            1 :             .apply(&mut gc_compaction_initial_threshold_kb);
     653            1 :         patch
     654            1 :             .gc_compaction_ratio_percent
     655            1 :             .apply(&mut gc_compaction_ratio_percent);
     656            1 : 
     657            1 :         Self {
     658            1 :             checkpoint_distance,
     659            1 :             checkpoint_timeout,
     660            1 :             compaction_target_size,
     661            1 :             compaction_period,
     662            1 :             compaction_threshold,
     663            1 :             compaction_upper_limit,
     664            1 :             compaction_algorithm,
     665            1 :             l0_flush_delay_threshold,
     666            1 :             l0_flush_stall_threshold,
     667            1 :             l0_flush_wait_upload,
     668            1 :             gc_horizon,
     669            1 :             gc_period,
     670            1 :             image_creation_threshold,
     671            1 :             pitr_interval,
     672            1 :             walreceiver_connect_timeout,
     673            1 :             lagging_wal_timeout,
     674            1 :             max_lsn_wal_lag,
     675            1 :             eviction_policy,
     676            1 :             min_resident_size_override,
     677            1 :             evictions_low_residence_duration_metric_threshold,
     678            1 :             heatmap_period,
     679            1 :             lazy_slru_download,
     680            1 :             timeline_get_throttle,
     681            1 :             image_layer_creation_check_threshold,
     682            1 :             lsn_lease_length,
     683            1 :             lsn_lease_length_for_ts,
     684            1 :             timeline_offloading,
     685            1 :             wal_receiver_protocol_override,
     686            1 :             rel_size_v2_enabled,
     687            1 :             gc_compaction_enabled,
     688            1 :             gc_compaction_initial_threshold_kb,
     689            1 :             gc_compaction_ratio_percent,
     690            1 :         }
     691            1 :     }
     692              : }
     693              : 
     694              : /// The policy for the aux file storage.
     695              : ///
     696              : /// It can be switched through `switch_aux_file_policy` tenant config.
     697              : /// When the first aux file written, the policy will be persisted in the
     698              : /// `index_part.json` file and has a limited migration path.
     699              : ///
     700              : /// Currently, we only allow the following migration path:
     701              : ///
     702              : /// Unset -> V1
     703              : ///       -> V2
     704              : ///       -> CrossValidation -> V2
     705              : #[derive(
     706              :     Eq,
     707              :     PartialEq,
     708              :     Debug,
     709              :     Copy,
     710              :     Clone,
     711            0 :     strum_macros::EnumString,
     712              :     strum_macros::Display,
     713            4 :     serde_with::DeserializeFromStr,
     714              :     serde_with::SerializeDisplay,
     715              : )]
     716              : #[strum(serialize_all = "kebab-case")]
     717              : pub enum AuxFilePolicy {
     718              :     /// V1 aux file policy: store everything in AUX_FILE_KEY
     719              :     #[strum(ascii_case_insensitive)]
     720              :     V1,
     721              :     /// V2 aux file policy: store in the AUX_FILE keyspace
     722              :     #[strum(ascii_case_insensitive)]
     723              :     V2,
     724              :     /// Cross validation runs both formats on the write path and does validation
     725              :     /// on the read path.
     726              :     #[strum(ascii_case_insensitive)]
     727              :     CrossValidation,
     728              : }
     729              : 
     730            0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
     731              : #[serde(tag = "kind")]
     732              : pub enum EvictionPolicy {
     733              :     NoEviction,
     734              :     LayerAccessThreshold(EvictionPolicyLayerAccessThreshold),
     735              :     OnlyImitiate(EvictionPolicyLayerAccessThreshold),
     736              : }
     737              : 
     738              : impl EvictionPolicy {
     739            0 :     pub fn discriminant_str(&self) -> &'static str {
     740            0 :         match self {
     741            0 :             EvictionPolicy::NoEviction => "NoEviction",
     742            0 :             EvictionPolicy::LayerAccessThreshold(_) => "LayerAccessThreshold",
     743            0 :             EvictionPolicy::OnlyImitiate(_) => "OnlyImitiate",
     744              :         }
     745            0 :     }
     746              : }
     747              : 
     748              : #[derive(
     749              :     Eq,
     750              :     PartialEq,
     751              :     Debug,
     752              :     Copy,
     753              :     Clone,
     754            0 :     strum_macros::EnumString,
     755              :     strum_macros::Display,
     756            0 :     serde_with::DeserializeFromStr,
     757              :     serde_with::SerializeDisplay,
     758              : )]
     759              : #[strum(serialize_all = "kebab-case")]
     760              : pub enum CompactionAlgorithm {
     761              :     Legacy,
     762              :     Tiered,
     763              : }
     764              : 
     765              : #[derive(
     766            4 :     Debug, Clone, Copy, PartialEq, Eq, serde_with::DeserializeFromStr, serde_with::SerializeDisplay,
     767              : )]
     768              : pub enum ImageCompressionAlgorithm {
     769              :     // Disabled for writes, support decompressing during read path
     770              :     Disabled,
     771              :     /// Zstandard compression. Level 0 means and None mean the same (default level). Levels can be negative as well.
     772              :     /// For details, see the [manual](http://facebook.github.io/zstd/zstd_manual.html).
     773              :     Zstd {
     774              :         level: Option<i8>,
     775              :     },
     776              : }
     777              : 
     778              : impl FromStr for ImageCompressionAlgorithm {
     779              :     type Err = anyhow::Error;
     780            8 :     fn from_str(s: &str) -> Result<Self, Self::Err> {
     781            8 :         let mut components = s.split(['(', ')']);
     782            8 :         let first = components
     783            8 :             .next()
     784            8 :             .ok_or_else(|| anyhow::anyhow!("empty string"))?;
     785            8 :         match first {
     786            8 :             "disabled" => Ok(ImageCompressionAlgorithm::Disabled),
     787            6 :             "zstd" => {
     788            6 :                 let level = if let Some(v) = components.next() {
     789            4 :                     let v: i8 = v.parse()?;
     790            4 :                     Some(v)
     791              :                 } else {
     792            2 :                     None
     793              :                 };
     794              : 
     795            6 :                 Ok(ImageCompressionAlgorithm::Zstd { level })
     796              :             }
     797            0 :             _ => anyhow::bail!("invalid specifier '{first}'"),
     798              :         }
     799            8 :     }
     800              : }
     801              : 
     802              : impl Display for ImageCompressionAlgorithm {
     803           12 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     804           12 :         match self {
     805            3 :             ImageCompressionAlgorithm::Disabled => write!(f, "disabled"),
     806            9 :             ImageCompressionAlgorithm::Zstd { level } => {
     807            9 :                 if let Some(level) = level {
     808            6 :                     write!(f, "zstd({})", level)
     809              :                 } else {
     810            3 :                     write!(f, "zstd")
     811              :                 }
     812              :             }
     813              :         }
     814           12 :     }
     815              : }
     816              : 
     817            0 : #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)]
     818              : pub struct CompactionAlgorithmSettings {
     819              :     pub kind: CompactionAlgorithm,
     820              : }
     821              : 
     822            8 : #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
     823              : #[serde(tag = "mode", rename_all = "kebab-case", deny_unknown_fields)]
     824              : pub enum L0FlushConfig {
     825              :     #[serde(rename_all = "snake_case")]
     826              :     Direct { max_concurrency: NonZeroUsize },
     827              : }
     828              : 
     829            0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
     830              : pub struct EvictionPolicyLayerAccessThreshold {
     831              :     #[serde(with = "humantime_serde")]
     832              :     pub period: Duration,
     833              :     #[serde(with = "humantime_serde")]
     834              :     pub threshold: Duration,
     835              : }
     836              : 
     837            6 : #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
     838              : pub struct ThrottleConfig {
     839              :     /// See [`ThrottleConfigTaskKinds`] for why we do the serde `rename`.
     840              :     #[serde(rename = "task_kinds")]
     841              :     pub enabled: ThrottleConfigTaskKinds,
     842              :     pub initial: u32,
     843              :     #[serde(with = "humantime_serde")]
     844              :     pub refill_interval: Duration,
     845              :     pub refill_amount: NonZeroU32,
     846              :     pub max: u32,
     847              : }
     848              : 
     849              : /// Before <https://github.com/neondatabase/neon/pull/9962>
     850              : /// the throttle was a per `Timeline::get`/`Timeline::get_vectored` call.
     851              : /// The `task_kinds` field controlled which Pageserver "Task Kind"s
     852              : /// were subject to the throttle.
     853              : ///
     854              : /// After that PR, the throttle is applied at pagestream request level
     855              : /// and the `task_kinds` field does not apply since the only task kind
     856              : /// that us subject to the throttle is that of the page service.
     857              : ///
     858              : /// However, we don't want to make a breaking config change right now
     859              : /// because it means we have to migrate all the tenant configs.
     860              : /// This will be done in a future PR.
     861              : ///
     862              : /// In the meantime, we use emptiness / non-emptsiness of the `task_kinds`
     863              : /// field to determine if the throttle is enabled or not.
     864            1 : #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
     865              : #[serde(transparent)]
     866              : pub struct ThrottleConfigTaskKinds(Vec<String>);
     867              : 
     868              : impl ThrottleConfigTaskKinds {
     869          901 :     pub fn disabled() -> Self {
     870          901 :         Self(vec![])
     871          901 :     }
     872          442 :     pub fn is_enabled(&self) -> bool {
     873          442 :         !self.0.is_empty()
     874          442 :     }
     875              : }
     876              : 
     877              : impl ThrottleConfig {
     878          901 :     pub fn disabled() -> Self {
     879          901 :         Self {
     880          901 :             enabled: ThrottleConfigTaskKinds::disabled(),
     881          901 :             // other values don't matter with emtpy `task_kinds`.
     882          901 :             initial: 0,
     883          901 :             refill_interval: Duration::from_millis(1),
     884          901 :             refill_amount: NonZeroU32::new(1).unwrap(),
     885          901 :             max: 1,
     886          901 :         }
     887          901 :     }
     888              :     /// The requests per second allowed  by the given config.
     889            0 :     pub fn steady_rps(&self) -> f64 {
     890            0 :         (self.refill_amount.get() as f64) / (self.refill_interval.as_secs_f64())
     891            0 :     }
     892              : }
     893              : 
     894              : #[cfg(test)]
     895              : mod throttle_config_tests {
     896              :     use super::*;
     897              : 
     898              :     #[test]
     899            1 :     fn test_disabled_is_disabled() {
     900            1 :         let config = ThrottleConfig::disabled();
     901            1 :         assert!(!config.enabled.is_enabled());
     902            1 :     }
     903              :     #[test]
     904            1 :     fn test_enabled_backwards_compat() {
     905            1 :         let input = serde_json::json!({
     906            1 :             "task_kinds": ["PageRequestHandler"],
     907            1 :             "initial": 40000,
     908            1 :             "refill_interval": "50ms",
     909            1 :             "refill_amount": 1000,
     910            1 :             "max": 40000,
     911            1 :             "fair": true
     912            1 :         });
     913            1 :         let config: ThrottleConfig = serde_json::from_value(input).unwrap();
     914            1 :         assert!(config.enabled.is_enabled());
     915            1 :     }
     916              : }
     917              : 
     918              : /// A flattened analog of a `pagesever::tenant::LocationMode`, which
     919              : /// lists out all possible states (and the virtual "Detached" state)
     920              : /// in a flat form rather than using rust-style enums.
     921            0 : #[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
     922              : pub enum LocationConfigMode {
     923              :     AttachedSingle,
     924              :     AttachedMulti,
     925              :     AttachedStale,
     926              :     Secondary,
     927              :     Detached,
     928              : }
     929              : 
     930            0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
     931              : pub struct LocationConfigSecondary {
     932              :     pub warm: bool,
     933              : }
     934              : 
     935              : /// An alternative representation of `pageserver::tenant::LocationConf`,
     936              : /// for use in external-facing APIs.
     937            0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
     938              : pub struct LocationConfig {
     939              :     pub mode: LocationConfigMode,
     940              :     /// If attaching, in what generation?
     941              :     #[serde(default)]
     942              :     pub generation: Option<u32>,
     943              : 
     944              :     // If requesting mode `Secondary`, configuration for that.
     945              :     #[serde(default)]
     946              :     pub secondary_conf: Option<LocationConfigSecondary>,
     947              : 
     948              :     // Shard parameters: if shard_count is nonzero, then other shard_* fields
     949              :     // must be set accurately.
     950              :     #[serde(default)]
     951              :     pub shard_number: u8,
     952              :     #[serde(default)]
     953              :     pub shard_count: u8,
     954              :     #[serde(default)]
     955              :     pub shard_stripe_size: u32,
     956              : 
     957              :     // This configuration only affects attached mode, but should be provided irrespective
     958              :     // of the mode, as a secondary location might transition on startup if the response
     959              :     // to the `/re-attach` control plane API requests it.
     960              :     pub tenant_conf: TenantConfig,
     961              : }
     962              : 
     963            0 : #[derive(Serialize, Deserialize)]
     964              : pub struct LocationConfigListResponse {
     965              :     pub tenant_shards: Vec<(TenantShardId, Option<LocationConfig>)>,
     966              : }
     967              : 
     968              : #[derive(Serialize)]
     969              : pub struct StatusResponse {
     970              :     pub id: NodeId,
     971              : }
     972              : 
     973            0 : #[derive(Serialize, Deserialize, Debug)]
     974              : #[serde(deny_unknown_fields)]
     975              : pub struct TenantLocationConfigRequest {
     976              :     #[serde(flatten)]
     977              :     pub config: LocationConfig, // as we have a flattened field, we should reject all unknown fields in it
     978              : }
     979              : 
     980            0 : #[derive(Serialize, Deserialize, Debug)]
     981              : #[serde(deny_unknown_fields)]
     982              : pub struct TenantTimeTravelRequest {
     983              :     pub shard_counts: Vec<ShardCount>,
     984              : }
     985              : 
     986            0 : #[derive(Serialize, Deserialize, Debug)]
     987              : #[serde(deny_unknown_fields)]
     988              : pub struct TenantShardLocation {
     989              :     pub shard_id: TenantShardId,
     990              :     pub node_id: NodeId,
     991              : }
     992              : 
     993            0 : #[derive(Serialize, Deserialize, Debug)]
     994              : #[serde(deny_unknown_fields)]
     995              : pub struct TenantLocationConfigResponse {
     996              :     pub shards: Vec<TenantShardLocation>,
     997              :     // If the shards' ShardCount count is >1, stripe_size will be set.
     998              :     pub stripe_size: Option<ShardStripeSize>,
     999              : }
    1000              : 
    1001            2 : #[derive(Serialize, Deserialize, Debug)]
    1002              : #[serde(deny_unknown_fields)]
    1003              : pub struct TenantConfigRequest {
    1004              :     pub tenant_id: TenantId,
    1005              :     #[serde(flatten)]
    1006              :     pub config: TenantConfig, // as we have a flattened field, we should reject all unknown fields in it
    1007              : }
    1008              : 
    1009              : impl std::ops::Deref for TenantConfigRequest {
    1010              :     type Target = TenantConfig;
    1011              : 
    1012            0 :     fn deref(&self) -> &Self::Target {
    1013            0 :         &self.config
    1014            0 :     }
    1015              : }
    1016              : 
    1017              : impl TenantConfigRequest {
    1018            0 :     pub fn new(tenant_id: TenantId) -> TenantConfigRequest {
    1019            0 :         let config = TenantConfig::default();
    1020            0 :         TenantConfigRequest { tenant_id, config }
    1021            0 :     }
    1022              : }
    1023              : 
    1024            3 : #[derive(Serialize, Deserialize, Debug)]
    1025              : #[serde(deny_unknown_fields)]
    1026              : pub struct TenantConfigPatchRequest {
    1027              :     pub tenant_id: TenantId,
    1028              :     #[serde(flatten)]
    1029              :     pub config: TenantConfigPatch, // as we have a flattened field, we should reject all unknown fields in it
    1030              : }
    1031              : 
    1032            0 : #[derive(Serialize, Deserialize, Debug)]
    1033              : pub struct TenantWaitLsnRequest {
    1034              :     #[serde(flatten)]
    1035              :     pub timelines: HashMap<TimelineId, Lsn>,
    1036              :     pub timeout: Duration,
    1037              : }
    1038              : 
    1039              : /// See [`TenantState::attachment_status`] and the OpenAPI docs for context.
    1040            0 : #[derive(Serialize, Deserialize, Clone)]
    1041              : #[serde(tag = "slug", content = "data", rename_all = "snake_case")]
    1042              : pub enum TenantAttachmentStatus {
    1043              :     Maybe,
    1044              :     Attached,
    1045              :     Failed { reason: String },
    1046              : }
    1047              : 
    1048            0 : #[derive(Serialize, Deserialize, Clone)]
    1049              : pub struct TenantInfo {
    1050              :     pub id: TenantShardId,
    1051              :     // NB: intentionally not part of OpenAPI, we don't want to commit to a specific set of TenantState's
    1052              :     pub state: TenantState,
    1053              :     /// Sum of the size of all layer files.
    1054              :     /// If a layer is present in both local FS and S3, it counts only once.
    1055              :     pub current_physical_size: Option<u64>, // physical size is only included in `tenant_status` endpoint
    1056              :     pub attachment_status: TenantAttachmentStatus,
    1057              :     pub generation: u32,
    1058              : 
    1059              :     /// Opaque explanation if gc is being blocked.
    1060              :     ///
    1061              :     /// Only looked up for the individual tenant detail, not the listing. This is purely for
    1062              :     /// debugging, not included in openapi.
    1063              :     #[serde(skip_serializing_if = "Option::is_none")]
    1064              :     pub gc_blocking: Option<String>,
    1065              : }
    1066              : 
    1067            0 : #[derive(Serialize, Deserialize, Clone)]
    1068              : pub struct TenantDetails {
    1069              :     #[serde(flatten)]
    1070              :     pub tenant_info: TenantInfo,
    1071              : 
    1072              :     pub walredo: Option<WalRedoManagerStatus>,
    1073              : 
    1074              :     pub timelines: Vec<TimelineId>,
    1075              : }
    1076              : 
    1077            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Debug)]
    1078              : pub enum TimelineArchivalState {
    1079              :     Archived,
    1080              :     Unarchived,
    1081              : }
    1082              : 
    1083            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
    1084              : pub struct TimelineArchivalConfigRequest {
    1085              :     pub state: TimelineArchivalState,
    1086              : }
    1087              : 
    1088            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
    1089              : pub struct TimelinesInfoAndOffloaded {
    1090              :     pub timelines: Vec<TimelineInfo>,
    1091              :     pub offloaded: Vec<OffloadedTimelineInfo>,
    1092              : }
    1093              : 
    1094              : /// Analog of [`TimelineInfo`] for offloaded timelines.
    1095            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
    1096              : pub struct OffloadedTimelineInfo {
    1097              :     pub tenant_id: TenantShardId,
    1098              :     pub timeline_id: TimelineId,
    1099              :     /// Whether the timeline has a parent it has been branched off from or not
    1100              :     pub ancestor_timeline_id: Option<TimelineId>,
    1101              :     /// Whether to retain the branch lsn at the ancestor or not
    1102              :     pub ancestor_retain_lsn: Option<Lsn>,
    1103              :     /// The time point when the timeline was archived
    1104              :     pub archived_at: chrono::DateTime<chrono::Utc>,
    1105              : }
    1106              : 
    1107              : /// This represents the output of the "timeline_detail" and "timeline_list" API calls.
    1108            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
    1109              : pub struct TimelineInfo {
    1110              :     pub tenant_id: TenantShardId,
    1111              :     pub timeline_id: TimelineId,
    1112              : 
    1113              :     pub ancestor_timeline_id: Option<TimelineId>,
    1114              :     pub ancestor_lsn: Option<Lsn>,
    1115              :     pub last_record_lsn: Lsn,
    1116              :     pub prev_record_lsn: Option<Lsn>,
    1117              :     pub latest_gc_cutoff_lsn: Lsn,
    1118              :     pub disk_consistent_lsn: Lsn,
    1119              : 
    1120              :     /// The LSN that we have succesfully uploaded to remote storage
    1121              :     pub remote_consistent_lsn: Lsn,
    1122              : 
    1123              :     /// The LSN that we are advertizing to safekeepers
    1124              :     pub remote_consistent_lsn_visible: Lsn,
    1125              : 
    1126              :     /// The LSN from the start of the root timeline (never changes)
    1127              :     pub initdb_lsn: Lsn,
    1128              : 
    1129              :     pub current_logical_size: u64,
    1130              :     pub current_logical_size_is_accurate: bool,
    1131              : 
    1132              :     pub directory_entries_counts: Vec<u64>,
    1133              : 
    1134              :     /// Sum of the size of all layer files.
    1135              :     /// If a layer is present in both local FS and S3, it counts only once.
    1136              :     pub current_physical_size: Option<u64>, // is None when timeline is Unloaded
    1137              :     pub current_logical_size_non_incremental: Option<u64>,
    1138              : 
    1139              :     /// How many bytes of WAL are within this branch's pitr_interval.  If the pitr_interval goes
    1140              :     /// beyond the branch's branch point, we only count up to the branch point.
    1141              :     pub pitr_history_size: u64,
    1142              : 
    1143              :     /// Whether this branch's branch point is within its ancestor's PITR interval (i.e. any
    1144              :     /// ancestor data used by this branch would have been retained anyway).  If this is false, then
    1145              :     /// this branch may be imposing a cost on the ancestor by causing it to retain layers that it would
    1146              :     /// otherwise be able to GC.
    1147              :     pub within_ancestor_pitr: bool,
    1148              : 
    1149              :     pub timeline_dir_layer_file_size_sum: Option<u64>,
    1150              : 
    1151              :     pub wal_source_connstr: Option<String>,
    1152              :     pub last_received_msg_lsn: Option<Lsn>,
    1153              :     /// the timestamp (in microseconds) of the last received message
    1154              :     pub last_received_msg_ts: Option<u128>,
    1155              :     pub pg_version: u32,
    1156              : 
    1157              :     pub state: TimelineState,
    1158              : 
    1159              :     pub walreceiver_status: String,
    1160              : 
    1161              :     // ALWAYS add new fields at the end of the struct with `Option` to ensure forward/backward compatibility.
    1162              :     // Backward compatibility: you will get a JSON not containing the newly-added field.
    1163              :     // Forward compatibility: a previous version of the pageserver will receive a JSON. serde::Deserialize does
    1164              :     // not deny unknown fields by default so it's safe to set the field to some value, though it won't be
    1165              :     // read.
    1166              :     pub is_archived: Option<bool>,
    1167              : }
    1168              : 
    1169            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
    1170              : pub struct LayerMapInfo {
    1171              :     pub in_memory_layers: Vec<InMemoryLayerInfo>,
    1172              :     pub historic_layers: Vec<HistoricLayerInfo>,
    1173              : }
    1174              : 
    1175              : /// The residence status of a layer
    1176            0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
    1177              : pub enum LayerResidenceStatus {
    1178              :     /// Residence status for a layer file that exists locally.
    1179              :     /// It may also exist on the remote, we don't care here.
    1180              :     Resident,
    1181              :     /// Residence status for a layer file that only exists on the remote.
    1182              :     Evicted,
    1183              : }
    1184              : 
    1185              : #[serde_as]
    1186            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
    1187              : pub struct LayerAccessStats {
    1188              :     #[serde_as(as = "serde_with::TimestampMilliSeconds")]
    1189              :     pub access_time: SystemTime,
    1190              : 
    1191              :     #[serde_as(as = "serde_with::TimestampMilliSeconds")]
    1192              :     pub residence_time: SystemTime,
    1193              : 
    1194              :     pub visible: bool,
    1195              : }
    1196              : 
    1197            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
    1198              : #[serde(tag = "kind")]
    1199              : pub enum InMemoryLayerInfo {
    1200              :     Open { lsn_start: Lsn },
    1201              :     Frozen { lsn_start: Lsn, lsn_end: Lsn },
    1202              : }
    1203              : 
    1204            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
    1205              : #[serde(tag = "kind")]
    1206              : pub enum HistoricLayerInfo {
    1207              :     Delta {
    1208              :         layer_file_name: String,
    1209              :         layer_file_size: u64,
    1210              : 
    1211              :         lsn_start: Lsn,
    1212              :         lsn_end: Lsn,
    1213              :         remote: bool,
    1214              :         access_stats: LayerAccessStats,
    1215              : 
    1216              :         l0: bool,
    1217              :     },
    1218              :     Image {
    1219              :         layer_file_name: String,
    1220              :         layer_file_size: u64,
    1221              : 
    1222              :         lsn_start: Lsn,
    1223              :         remote: bool,
    1224              :         access_stats: LayerAccessStats,
    1225              :     },
    1226              : }
    1227              : 
    1228              : impl HistoricLayerInfo {
    1229            0 :     pub fn layer_file_name(&self) -> &str {
    1230            0 :         match self {
    1231              :             HistoricLayerInfo::Delta {
    1232            0 :                 layer_file_name, ..
    1233            0 :             } => layer_file_name,
    1234              :             HistoricLayerInfo::Image {
    1235            0 :                 layer_file_name, ..
    1236            0 :             } => layer_file_name,
    1237              :         }
    1238            0 :     }
    1239            0 :     pub fn is_remote(&self) -> bool {
    1240            0 :         match self {
    1241            0 :             HistoricLayerInfo::Delta { remote, .. } => *remote,
    1242            0 :             HistoricLayerInfo::Image { remote, .. } => *remote,
    1243              :         }
    1244            0 :     }
    1245            0 :     pub fn set_remote(&mut self, value: bool) {
    1246            0 :         let field = match self {
    1247            0 :             HistoricLayerInfo::Delta { remote, .. } => remote,
    1248            0 :             HistoricLayerInfo::Image { remote, .. } => remote,
    1249              :         };
    1250            0 :         *field = value;
    1251            0 :     }
    1252            0 :     pub fn layer_file_size(&self) -> u64 {
    1253            0 :         match self {
    1254              :             HistoricLayerInfo::Delta {
    1255            0 :                 layer_file_size, ..
    1256            0 :             } => *layer_file_size,
    1257              :             HistoricLayerInfo::Image {
    1258            0 :                 layer_file_size, ..
    1259            0 :             } => *layer_file_size,
    1260              :         }
    1261            0 :     }
    1262              : }
    1263              : 
    1264            0 : #[derive(Debug, Serialize, Deserialize)]
    1265              : pub struct DownloadRemoteLayersTaskSpawnRequest {
    1266              :     pub max_concurrent_downloads: NonZeroUsize,
    1267              : }
    1268              : 
    1269            0 : #[derive(Debug, Serialize, Deserialize)]
    1270              : pub struct IngestAuxFilesRequest {
    1271              :     pub aux_files: HashMap<String, String>,
    1272              : }
    1273              : 
    1274            0 : #[derive(Debug, Serialize, Deserialize)]
    1275              : pub struct ListAuxFilesRequest {
    1276              :     pub lsn: Lsn,
    1277              : }
    1278              : 
    1279            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
    1280              : pub struct DownloadRemoteLayersTaskInfo {
    1281              :     pub task_id: String,
    1282              :     pub state: DownloadRemoteLayersTaskState,
    1283              :     pub total_layer_count: u64,         // stable once `completed`
    1284              :     pub successful_download_count: u64, // stable once `completed`
    1285              :     pub failed_download_count: u64,     // stable once `completed`
    1286              : }
    1287              : 
    1288            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
    1289              : pub enum DownloadRemoteLayersTaskState {
    1290              :     Running,
    1291              :     Completed,
    1292              :     ShutDown,
    1293              : }
    1294              : 
    1295            0 : #[derive(Debug, Serialize, Deserialize)]
    1296              : pub struct TimelineGcRequest {
    1297              :     pub gc_horizon: Option<u64>,
    1298              : }
    1299              : 
    1300            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
    1301              : pub struct WalRedoManagerProcessStatus {
    1302              :     pub pid: u32,
    1303              : }
    1304              : 
    1305            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
    1306              : pub struct WalRedoManagerStatus {
    1307              :     pub last_redo_at: Option<chrono::DateTime<chrono::Utc>>,
    1308              :     pub process: Option<WalRedoManagerProcessStatus>,
    1309              : }
    1310              : 
    1311              : /// The progress of a secondary tenant.
    1312              : ///
    1313              : /// It is mostly useful when doing a long running download: e.g. initiating
    1314              : /// a download job, timing out while waiting for it to run, and then inspecting this status to understand
    1315              : /// what's happening.
    1316            0 : #[derive(Default, Debug, Serialize, Deserialize, Clone)]
    1317              : pub struct SecondaryProgress {
    1318              :     /// The remote storage LastModified time of the heatmap object we last downloaded.
    1319              :     pub heatmap_mtime: Option<serde_system_time::SystemTime>,
    1320              : 
    1321              :     /// The number of layers currently on-disk
    1322              :     pub layers_downloaded: usize,
    1323              :     /// The number of layers in the most recently seen heatmap
    1324              :     pub layers_total: usize,
    1325              : 
    1326              :     /// The number of layer bytes currently on-disk
    1327              :     pub bytes_downloaded: u64,
    1328              :     /// The number of layer bytes in the most recently seen heatmap
    1329              :     pub bytes_total: u64,
    1330              : }
    1331              : 
    1332            0 : #[derive(Serialize, Deserialize, Debug)]
    1333              : pub struct TenantScanRemoteStorageShard {
    1334              :     pub tenant_shard_id: TenantShardId,
    1335              :     pub generation: Option<u32>,
    1336              : }
    1337              : 
    1338            0 : #[derive(Serialize, Deserialize, Debug, Default)]
    1339              : pub struct TenantScanRemoteStorageResponse {
    1340              :     pub shards: Vec<TenantScanRemoteStorageShard>,
    1341              : }
    1342              : 
    1343            0 : #[derive(Serialize, Deserialize, Debug, Clone)]
    1344              : #[serde(rename_all = "snake_case")]
    1345              : pub enum TenantSorting {
    1346              :     ResidentSize,
    1347              :     MaxLogicalSize,
    1348              : }
    1349              : 
    1350              : impl Default for TenantSorting {
    1351            0 :     fn default() -> Self {
    1352            0 :         Self::ResidentSize
    1353            0 :     }
    1354              : }
    1355              : 
    1356            0 : #[derive(Serialize, Deserialize, Debug, Clone)]
    1357              : pub struct TopTenantShardsRequest {
    1358              :     // How would you like to sort the tenants?
    1359              :     pub order_by: TenantSorting,
    1360              : 
    1361              :     // How many results?
    1362              :     pub limit: usize,
    1363              : 
    1364              :     // Omit tenants with more than this many shards (e.g. if this is the max number of shards
    1365              :     // that the caller would ever split to)
    1366              :     pub where_shards_lt: Option<ShardCount>,
    1367              : 
    1368              :     // Omit tenants where the ordering metric is less than this (this is an optimization to
    1369              :     // let us quickly exclude numerous tiny shards)
    1370              :     pub where_gt: Option<u64>,
    1371              : }
    1372              : 
    1373            0 : #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
    1374              : pub struct TopTenantShardItem {
    1375              :     pub id: TenantShardId,
    1376              : 
    1377              :     /// Total size of layers on local disk for all timelines in this tenant
    1378              :     pub resident_size: u64,
    1379              : 
    1380              :     /// Total size of layers in remote storage for all timelines in this tenant
    1381              :     pub physical_size: u64,
    1382              : 
    1383              :     /// The largest logical size of a timeline within this tenant
    1384              :     pub max_logical_size: u64,
    1385              : }
    1386              : 
    1387            0 : #[derive(Serialize, Deserialize, Debug, Default)]
    1388              : pub struct TopTenantShardsResponse {
    1389              :     pub shards: Vec<TopTenantShardItem>,
    1390              : }
    1391              : 
    1392              : pub mod virtual_file {
    1393              :     #[derive(
    1394              :         Copy,
    1395              :         Clone,
    1396              :         PartialEq,
    1397              :         Eq,
    1398              :         Hash,
    1399            0 :         strum_macros::EnumString,
    1400              :         strum_macros::Display,
    1401            0 :         serde_with::DeserializeFromStr,
    1402              :         serde_with::SerializeDisplay,
    1403              :         Debug,
    1404              :     )]
    1405              :     #[strum(serialize_all = "kebab-case")]
    1406              :     pub enum IoEngineKind {
    1407              :         StdFs,
    1408              :         #[cfg(target_os = "linux")]
    1409              :         TokioEpollUring,
    1410              :     }
    1411              : 
    1412              :     /// Direct IO modes for a pageserver.
    1413              :     #[derive(
    1414              :         Copy,
    1415              :         Clone,
    1416              :         PartialEq,
    1417              :         Eq,
    1418              :         Hash,
    1419            0 :         strum_macros::EnumString,
    1420              :         strum_macros::Display,
    1421            0 :         serde_with::DeserializeFromStr,
    1422              :         serde_with::SerializeDisplay,
    1423              :         Debug,
    1424              :     )]
    1425              :     #[strum(serialize_all = "kebab-case")]
    1426              :     #[repr(u8)]
    1427              :     pub enum IoMode {
    1428              :         /// Uses buffered IO.
    1429              :         Buffered,
    1430              :         /// Uses direct IO, error out if the operation fails.
    1431              :         #[cfg(target_os = "linux")]
    1432              :         Direct,
    1433              :     }
    1434              : 
    1435              :     impl IoMode {
    1436          476 :         pub const fn preferred() -> Self {
    1437          476 :             Self::Buffered
    1438          476 :         }
    1439              :     }
    1440              : 
    1441              :     impl TryFrom<u8> for IoMode {
    1442              :         type Error = u8;
    1443              : 
    1444         5064 :         fn try_from(value: u8) -> Result<Self, Self::Error> {
    1445         5064 :             Ok(match value {
    1446         5064 :                 v if v == (IoMode::Buffered as u8) => IoMode::Buffered,
    1447              :                 #[cfg(target_os = "linux")]
    1448            0 :                 v if v == (IoMode::Direct as u8) => IoMode::Direct,
    1449            0 :                 x => return Err(x),
    1450              :             })
    1451         5064 :         }
    1452              :     }
    1453              : }
    1454              : 
    1455            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
    1456              : pub struct ScanDisposableKeysResponse {
    1457              :     pub disposable_count: usize,
    1458              :     pub not_disposable_count: usize,
    1459              : }
    1460              : 
    1461              : // Wrapped in libpq CopyData
    1462              : #[derive(PartialEq, Eq, Debug)]
    1463              : pub enum PagestreamFeMessage {
    1464              :     Exists(PagestreamExistsRequest),
    1465              :     Nblocks(PagestreamNblocksRequest),
    1466              :     GetPage(PagestreamGetPageRequest),
    1467              :     DbSize(PagestreamDbSizeRequest),
    1468              :     GetSlruSegment(PagestreamGetSlruSegmentRequest),
    1469              :     #[cfg(feature = "testing")]
    1470              :     Test(PagestreamTestRequest),
    1471              : }
    1472              : 
    1473              : // Wrapped in libpq CopyData
    1474              : #[derive(strum_macros::EnumProperty)]
    1475              : pub enum PagestreamBeMessage {
    1476              :     Exists(PagestreamExistsResponse),
    1477              :     Nblocks(PagestreamNblocksResponse),
    1478              :     GetPage(PagestreamGetPageResponse),
    1479              :     Error(PagestreamErrorResponse),
    1480              :     DbSize(PagestreamDbSizeResponse),
    1481              :     GetSlruSegment(PagestreamGetSlruSegmentResponse),
    1482              :     #[cfg(feature = "testing")]
    1483              :     Test(PagestreamTestResponse),
    1484              : }
    1485              : 
    1486              : // Keep in sync with `pagestore_client.h`
    1487              : #[repr(u8)]
    1488              : enum PagestreamFeMessageTag {
    1489              :     Exists = 0,
    1490              :     Nblocks = 1,
    1491              :     GetPage = 2,
    1492              :     DbSize = 3,
    1493              :     GetSlruSegment = 4,
    1494              :     /* future tags above this line */
    1495              :     /// For testing purposes, not available in production.
    1496              :     #[cfg(feature = "testing")]
    1497              :     Test = 99,
    1498              : }
    1499              : 
    1500              : // Keep in sync with `pagestore_client.h`
    1501              : #[repr(u8)]
    1502              : enum PagestreamBeMessageTag {
    1503              :     Exists = 100,
    1504              :     Nblocks = 101,
    1505              :     GetPage = 102,
    1506              :     Error = 103,
    1507              :     DbSize = 104,
    1508              :     GetSlruSegment = 105,
    1509              :     /* future tags above this line */
    1510              :     /// For testing purposes, not available in production.
    1511              :     #[cfg(feature = "testing")]
    1512              :     Test = 199,
    1513              : }
    1514              : 
    1515              : impl TryFrom<u8> for PagestreamFeMessageTag {
    1516              :     type Error = u8;
    1517            4 :     fn try_from(value: u8) -> Result<Self, u8> {
    1518            4 :         match value {
    1519            1 :             0 => Ok(PagestreamFeMessageTag::Exists),
    1520            1 :             1 => Ok(PagestreamFeMessageTag::Nblocks),
    1521            1 :             2 => Ok(PagestreamFeMessageTag::GetPage),
    1522            1 :             3 => Ok(PagestreamFeMessageTag::DbSize),
    1523            0 :             4 => Ok(PagestreamFeMessageTag::GetSlruSegment),
    1524              :             #[cfg(feature = "testing")]
    1525            0 :             99 => Ok(PagestreamFeMessageTag::Test),
    1526            0 :             _ => Err(value),
    1527              :         }
    1528            4 :     }
    1529              : }
    1530              : 
    1531              : impl TryFrom<u8> for PagestreamBeMessageTag {
    1532              :     type Error = u8;
    1533            0 :     fn try_from(value: u8) -> Result<Self, u8> {
    1534            0 :         match value {
    1535            0 :             100 => Ok(PagestreamBeMessageTag::Exists),
    1536            0 :             101 => Ok(PagestreamBeMessageTag::Nblocks),
    1537            0 :             102 => Ok(PagestreamBeMessageTag::GetPage),
    1538            0 :             103 => Ok(PagestreamBeMessageTag::Error),
    1539            0 :             104 => Ok(PagestreamBeMessageTag::DbSize),
    1540            0 :             105 => Ok(PagestreamBeMessageTag::GetSlruSegment),
    1541              :             #[cfg(feature = "testing")]
    1542            0 :             199 => Ok(PagestreamBeMessageTag::Test),
    1543            0 :             _ => Err(value),
    1544              :         }
    1545            0 :     }
    1546              : }
    1547              : 
    1548              : // A GetPage request contains two LSN values:
    1549              : //
    1550              : // request_lsn: Get the page version at this point in time.  Lsn::Max is a special value that means
    1551              : // "get the latest version present". It's used by the primary server, which knows that no one else
    1552              : // is writing WAL. 'not_modified_since' must be set to a proper value even if request_lsn is
    1553              : // Lsn::Max. Standby servers use the current replay LSN as the request LSN.
    1554              : //
    1555              : // not_modified_since: Hint to the pageserver that the client knows that the page has not been
    1556              : // modified between 'not_modified_since' and the request LSN. It's always correct to set
    1557              : // 'not_modified_since equal' to 'request_lsn' (unless Lsn::Max is used as the 'request_lsn'), but
    1558              : // passing an earlier LSN can speed up the request, by allowing the pageserver to process the
    1559              : // request without waiting for 'request_lsn' to arrive.
    1560              : //
    1561              : // The now-defunct V1 interface contained only one LSN, and a boolean 'latest' flag. The V1 interface was
    1562              : // sufficient for the primary; the 'lsn' was equivalent to the 'not_modified_since' value, and
    1563              : // 'latest' was set to true. The V2 interface was added because there was no correct way for a
    1564              : // standby to request a page at a particular non-latest LSN, and also include the
    1565              : // 'not_modified_since' hint. That led to an awkward choice of either using an old LSN in the
    1566              : // request, if the standby knows that the page hasn't been modified since, and risk getting an error
    1567              : // if that LSN has fallen behind the GC horizon, or requesting the current replay LSN, which could
    1568              : // require the pageserver unnecessarily to wait for the WAL to arrive up to that point. The new V2
    1569              : // interface allows sending both LSNs, and let the pageserver do the right thing. There was no
    1570              : // difference in the responses between V1 and V2.
    1571              : //
    1572              : // V3 version of protocol adds request ID to all requests. This request ID is also included in response
    1573              : // as well as other fields from requests, which allows to verify that we receive response for our request.
    1574              : // We copy fields from request to response to make checking more reliable: request ID is formed from process ID
    1575              : // and local counter, so in principle there can be duplicated requests IDs if process PID is reused.
    1576              : //
    1577              : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    1578              : pub enum PagestreamProtocolVersion {
    1579              :     V2,
    1580              :     V3,
    1581              : }
    1582              : 
    1583              : pub type RequestId = u64;
    1584              : 
    1585              : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    1586              : pub struct PagestreamRequest {
    1587              :     pub reqid: RequestId,
    1588              :     pub request_lsn: Lsn,
    1589              :     pub not_modified_since: Lsn,
    1590              : }
    1591              : 
    1592              : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    1593              : pub struct PagestreamExistsRequest {
    1594              :     pub hdr: PagestreamRequest,
    1595              :     pub rel: RelTag,
    1596              : }
    1597              : 
    1598              : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    1599              : pub struct PagestreamNblocksRequest {
    1600              :     pub hdr: PagestreamRequest,
    1601              :     pub rel: RelTag,
    1602              : }
    1603              : 
    1604              : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    1605              : pub struct PagestreamGetPageRequest {
    1606              :     pub hdr: PagestreamRequest,
    1607              :     pub rel: RelTag,
    1608              :     pub blkno: u32,
    1609              : }
    1610              : 
    1611              : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    1612              : pub struct PagestreamDbSizeRequest {
    1613              :     pub hdr: PagestreamRequest,
    1614              :     pub dbnode: u32,
    1615              : }
    1616              : 
    1617              : #[derive(Debug, PartialEq, Eq, Clone, Copy)]
    1618              : pub struct PagestreamGetSlruSegmentRequest {
    1619              :     pub hdr: PagestreamRequest,
    1620              :     pub kind: u8,
    1621              :     pub segno: u32,
    1622              : }
    1623              : 
    1624              : #[derive(Debug)]
    1625              : pub struct PagestreamExistsResponse {
    1626              :     pub req: PagestreamExistsRequest,
    1627              :     pub exists: bool,
    1628              : }
    1629              : 
    1630              : #[derive(Debug)]
    1631              : pub struct PagestreamNblocksResponse {
    1632              :     pub req: PagestreamNblocksRequest,
    1633              :     pub n_blocks: u32,
    1634              : }
    1635              : 
    1636              : #[derive(Debug)]
    1637              : pub struct PagestreamGetPageResponse {
    1638              :     pub req: PagestreamGetPageRequest,
    1639              :     pub page: Bytes,
    1640              : }
    1641              : 
    1642              : #[derive(Debug)]
    1643              : pub struct PagestreamGetSlruSegmentResponse {
    1644              :     pub req: PagestreamGetSlruSegmentRequest,
    1645              :     pub segment: Bytes,
    1646              : }
    1647              : 
    1648              : #[derive(Debug)]
    1649              : pub struct PagestreamErrorResponse {
    1650              :     pub req: PagestreamRequest,
    1651              :     pub message: String,
    1652              : }
    1653              : 
    1654              : #[derive(Debug)]
    1655              : pub struct PagestreamDbSizeResponse {
    1656              :     pub req: PagestreamDbSizeRequest,
    1657              :     pub db_size: i64,
    1658              : }
    1659              : 
    1660              : #[cfg(feature = "testing")]
    1661              : #[derive(Debug, PartialEq, Eq, Clone)]
    1662              : pub struct PagestreamTestRequest {
    1663              :     pub hdr: PagestreamRequest,
    1664              :     pub batch_key: u64,
    1665              :     pub message: String,
    1666              : }
    1667              : 
    1668              : #[cfg(feature = "testing")]
    1669              : #[derive(Debug)]
    1670              : pub struct PagestreamTestResponse {
    1671              :     pub req: PagestreamTestRequest,
    1672              : }
    1673              : 
    1674              : // This is a cut-down version of TenantHistorySize from the pageserver crate, omitting fields
    1675              : // that require pageserver-internal types.  It is sufficient to get the total size.
    1676            0 : #[derive(Serialize, Deserialize, Debug)]
    1677              : pub struct TenantHistorySize {
    1678              :     pub id: TenantId,
    1679              :     /// Size is a mixture of WAL and logical size, so the unit is bytes.
    1680              :     ///
    1681              :     /// Will be none if `?inputs_only=true` was given.
    1682              :     pub size: Option<u64>,
    1683              : }
    1684              : 
    1685              : impl PagestreamFeMessage {
    1686              :     /// Serialize a compute -> pageserver message. This is currently only used in testing
    1687              :     /// tools. Always uses protocol version 3.
    1688            4 :     pub fn serialize(&self) -> Bytes {
    1689            4 :         let mut bytes = BytesMut::new();
    1690            4 : 
    1691            4 :         match self {
    1692            1 :             Self::Exists(req) => {
    1693            1 :                 bytes.put_u8(PagestreamFeMessageTag::Exists as u8);
    1694            1 :                 bytes.put_u64(req.hdr.reqid);
    1695            1 :                 bytes.put_u64(req.hdr.request_lsn.0);
    1696            1 :                 bytes.put_u64(req.hdr.not_modified_since.0);
    1697            1 :                 bytes.put_u32(req.rel.spcnode);
    1698            1 :                 bytes.put_u32(req.rel.dbnode);
    1699            1 :                 bytes.put_u32(req.rel.relnode);
    1700            1 :                 bytes.put_u8(req.rel.forknum);
    1701            1 :             }
    1702              : 
    1703            1 :             Self::Nblocks(req) => {
    1704            1 :                 bytes.put_u8(PagestreamFeMessageTag::Nblocks as u8);
    1705            1 :                 bytes.put_u64(req.hdr.reqid);
    1706            1 :                 bytes.put_u64(req.hdr.request_lsn.0);
    1707            1 :                 bytes.put_u64(req.hdr.not_modified_since.0);
    1708            1 :                 bytes.put_u32(req.rel.spcnode);
    1709            1 :                 bytes.put_u32(req.rel.dbnode);
    1710            1 :                 bytes.put_u32(req.rel.relnode);
    1711            1 :                 bytes.put_u8(req.rel.forknum);
    1712            1 :             }
    1713              : 
    1714            1 :             Self::GetPage(req) => {
    1715            1 :                 bytes.put_u8(PagestreamFeMessageTag::GetPage as u8);
    1716            1 :                 bytes.put_u64(req.hdr.reqid);
    1717            1 :                 bytes.put_u64(req.hdr.request_lsn.0);
    1718            1 :                 bytes.put_u64(req.hdr.not_modified_since.0);
    1719            1 :                 bytes.put_u32(req.rel.spcnode);
    1720            1 :                 bytes.put_u32(req.rel.dbnode);
    1721            1 :                 bytes.put_u32(req.rel.relnode);
    1722            1 :                 bytes.put_u8(req.rel.forknum);
    1723            1 :                 bytes.put_u32(req.blkno);
    1724            1 :             }
    1725              : 
    1726            1 :             Self::DbSize(req) => {
    1727            1 :                 bytes.put_u8(PagestreamFeMessageTag::DbSize as u8);
    1728            1 :                 bytes.put_u64(req.hdr.reqid);
    1729            1 :                 bytes.put_u64(req.hdr.request_lsn.0);
    1730            1 :                 bytes.put_u64(req.hdr.not_modified_since.0);
    1731            1 :                 bytes.put_u32(req.dbnode);
    1732            1 :             }
    1733              : 
    1734            0 :             Self::GetSlruSegment(req) => {
    1735            0 :                 bytes.put_u8(PagestreamFeMessageTag::GetSlruSegment as u8);
    1736            0 :                 bytes.put_u64(req.hdr.reqid);
    1737            0 :                 bytes.put_u64(req.hdr.request_lsn.0);
    1738            0 :                 bytes.put_u64(req.hdr.not_modified_since.0);
    1739            0 :                 bytes.put_u8(req.kind);
    1740            0 :                 bytes.put_u32(req.segno);
    1741            0 :             }
    1742              :             #[cfg(feature = "testing")]
    1743            0 :             Self::Test(req) => {
    1744            0 :                 bytes.put_u8(PagestreamFeMessageTag::Test as u8);
    1745            0 :                 bytes.put_u64(req.hdr.reqid);
    1746            0 :                 bytes.put_u64(req.hdr.request_lsn.0);
    1747            0 :                 bytes.put_u64(req.hdr.not_modified_since.0);
    1748            0 :                 bytes.put_u64(req.batch_key);
    1749            0 :                 let message = req.message.as_bytes();
    1750            0 :                 bytes.put_u64(message.len() as u64);
    1751            0 :                 bytes.put_slice(message);
    1752            0 :             }
    1753              :         }
    1754              : 
    1755            4 :         bytes.into()
    1756            4 :     }
    1757              : 
    1758            4 :     pub fn parse<R: std::io::Read>(
    1759            4 :         body: &mut R,
    1760            4 :         protocol_version: PagestreamProtocolVersion,
    1761            4 :     ) -> anyhow::Result<PagestreamFeMessage> {
    1762              :         // these correspond to the NeonMessageTag enum in pagestore_client.h
    1763              :         //
    1764              :         // TODO: consider using protobuf or serde bincode for less error prone
    1765              :         // serialization.
    1766            4 :         let msg_tag = body.read_u8()?;
    1767            4 :         let (reqid, request_lsn, not_modified_since) = match protocol_version {
    1768              :             PagestreamProtocolVersion::V2 => (
    1769              :                 0,
    1770            0 :                 Lsn::from(body.read_u64::<BigEndian>()?),
    1771            0 :                 Lsn::from(body.read_u64::<BigEndian>()?),
    1772              :             ),
    1773              :             PagestreamProtocolVersion::V3 => (
    1774            4 :                 body.read_u64::<BigEndian>()?,
    1775            4 :                 Lsn::from(body.read_u64::<BigEndian>()?),
    1776            4 :                 Lsn::from(body.read_u64::<BigEndian>()?),
    1777              :             ),
    1778              :         };
    1779              : 
    1780            4 :         match PagestreamFeMessageTag::try_from(msg_tag)
    1781            4 :             .map_err(|tag: u8| anyhow::anyhow!("invalid tag {tag}"))?
    1782              :         {
    1783              :             PagestreamFeMessageTag::Exists => {
    1784              :                 Ok(PagestreamFeMessage::Exists(PagestreamExistsRequest {
    1785            1 :                     hdr: PagestreamRequest {
    1786            1 :                         reqid,
    1787            1 :                         request_lsn,
    1788            1 :                         not_modified_since,
    1789            1 :                     },
    1790            1 :                     rel: RelTag {
    1791            1 :                         spcnode: body.read_u32::<BigEndian>()?,
    1792            1 :                         dbnode: body.read_u32::<BigEndian>()?,
    1793            1 :                         relnode: body.read_u32::<BigEndian>()?,
    1794            1 :                         forknum: body.read_u8()?,
    1795              :                     },
    1796              :                 }))
    1797              :             }
    1798              :             PagestreamFeMessageTag::Nblocks => {
    1799              :                 Ok(PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
    1800            1 :                     hdr: PagestreamRequest {
    1801            1 :                         reqid,
    1802            1 :                         request_lsn,
    1803            1 :                         not_modified_since,
    1804            1 :                     },
    1805            1 :                     rel: RelTag {
    1806            1 :                         spcnode: body.read_u32::<BigEndian>()?,
    1807            1 :                         dbnode: body.read_u32::<BigEndian>()?,
    1808            1 :                         relnode: body.read_u32::<BigEndian>()?,
    1809            1 :                         forknum: body.read_u8()?,
    1810              :                     },
    1811              :                 }))
    1812              :             }
    1813              :             PagestreamFeMessageTag::GetPage => {
    1814              :                 Ok(PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
    1815            1 :                     hdr: PagestreamRequest {
    1816            1 :                         reqid,
    1817            1 :                         request_lsn,
    1818            1 :                         not_modified_since,
    1819            1 :                     },
    1820            1 :                     rel: RelTag {
    1821            1 :                         spcnode: body.read_u32::<BigEndian>()?,
    1822            1 :                         dbnode: body.read_u32::<BigEndian>()?,
    1823            1 :                         relnode: body.read_u32::<BigEndian>()?,
    1824            1 :                         forknum: body.read_u8()?,
    1825              :                     },
    1826            1 :                     blkno: body.read_u32::<BigEndian>()?,
    1827              :                 }))
    1828              :             }
    1829              :             PagestreamFeMessageTag::DbSize => {
    1830              :                 Ok(PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
    1831            1 :                     hdr: PagestreamRequest {
    1832            1 :                         reqid,
    1833            1 :                         request_lsn,
    1834            1 :                         not_modified_since,
    1835            1 :                     },
    1836            1 :                     dbnode: body.read_u32::<BigEndian>()?,
    1837              :                 }))
    1838              :             }
    1839              :             PagestreamFeMessageTag::GetSlruSegment => Ok(PagestreamFeMessage::GetSlruSegment(
    1840              :                 PagestreamGetSlruSegmentRequest {
    1841            0 :                     hdr: PagestreamRequest {
    1842            0 :                         reqid,
    1843            0 :                         request_lsn,
    1844            0 :                         not_modified_since,
    1845            0 :                     },
    1846            0 :                     kind: body.read_u8()?,
    1847            0 :                     segno: body.read_u32::<BigEndian>()?,
    1848              :                 },
    1849              :             )),
    1850              :             #[cfg(feature = "testing")]
    1851              :             PagestreamFeMessageTag::Test => Ok(PagestreamFeMessage::Test(PagestreamTestRequest {
    1852            0 :                 hdr: PagestreamRequest {
    1853            0 :                     reqid,
    1854            0 :                     request_lsn,
    1855            0 :                     not_modified_since,
    1856            0 :                 },
    1857            0 :                 batch_key: body.read_u64::<BigEndian>()?,
    1858              :                 message: {
    1859            0 :                     let len = body.read_u64::<BigEndian>()?;
    1860            0 :                     let mut buf = vec![0; len as usize];
    1861            0 :                     body.read_exact(&mut buf)?;
    1862            0 :                     String::from_utf8(buf)?
    1863              :                 },
    1864              :             })),
    1865              :         }
    1866            4 :     }
    1867              : }
    1868              : 
    1869              : impl PagestreamBeMessage {
    1870            0 :     pub fn serialize(&self, protocol_version: PagestreamProtocolVersion) -> Bytes {
    1871            0 :         let mut bytes = BytesMut::new();
    1872              : 
    1873              :         use PagestreamBeMessageTag as Tag;
    1874            0 :         match protocol_version {
    1875              :             PagestreamProtocolVersion::V2 => {
    1876            0 :                 match self {
    1877            0 :                     Self::Exists(resp) => {
    1878            0 :                         bytes.put_u8(Tag::Exists as u8);
    1879            0 :                         bytes.put_u8(resp.exists as u8);
    1880            0 :                     }
    1881              : 
    1882            0 :                     Self::Nblocks(resp) => {
    1883            0 :                         bytes.put_u8(Tag::Nblocks as u8);
    1884            0 :                         bytes.put_u32(resp.n_blocks);
    1885            0 :                     }
    1886              : 
    1887            0 :                     Self::GetPage(resp) => {
    1888            0 :                         bytes.put_u8(Tag::GetPage as u8);
    1889            0 :                         bytes.put(&resp.page[..])
    1890              :                     }
    1891              : 
    1892            0 :                     Self::Error(resp) => {
    1893            0 :                         bytes.put_u8(Tag::Error as u8);
    1894            0 :                         bytes.put(resp.message.as_bytes());
    1895            0 :                         bytes.put_u8(0); // null terminator
    1896            0 :                     }
    1897            0 :                     Self::DbSize(resp) => {
    1898            0 :                         bytes.put_u8(Tag::DbSize as u8);
    1899            0 :                         bytes.put_i64(resp.db_size);
    1900            0 :                     }
    1901              : 
    1902            0 :                     Self::GetSlruSegment(resp) => {
    1903            0 :                         bytes.put_u8(Tag::GetSlruSegment as u8);
    1904            0 :                         bytes.put_u32((resp.segment.len() / BLCKSZ as usize) as u32);
    1905            0 :                         bytes.put(&resp.segment[..]);
    1906            0 :                     }
    1907              : 
    1908              :                     #[cfg(feature = "testing")]
    1909            0 :                     Self::Test(resp) => {
    1910            0 :                         bytes.put_u8(Tag::Test as u8);
    1911            0 :                         bytes.put_u64(resp.req.batch_key);
    1912            0 :                         let message = resp.req.message.as_bytes();
    1913            0 :                         bytes.put_u64(message.len() as u64);
    1914            0 :                         bytes.put_slice(message);
    1915            0 :                     }
    1916              :                 }
    1917              :             }
    1918              :             PagestreamProtocolVersion::V3 => {
    1919            0 :                 match self {
    1920            0 :                     Self::Exists(resp) => {
    1921            0 :                         bytes.put_u8(Tag::Exists as u8);
    1922            0 :                         bytes.put_u64(resp.req.hdr.reqid);
    1923            0 :                         bytes.put_u64(resp.req.hdr.request_lsn.0);
    1924            0 :                         bytes.put_u64(resp.req.hdr.not_modified_since.0);
    1925            0 :                         bytes.put_u32(resp.req.rel.spcnode);
    1926            0 :                         bytes.put_u32(resp.req.rel.dbnode);
    1927            0 :                         bytes.put_u32(resp.req.rel.relnode);
    1928            0 :                         bytes.put_u8(resp.req.rel.forknum);
    1929            0 :                         bytes.put_u8(resp.exists as u8);
    1930            0 :                     }
    1931              : 
    1932            0 :                     Self::Nblocks(resp) => {
    1933            0 :                         bytes.put_u8(Tag::Nblocks as u8);
    1934            0 :                         bytes.put_u64(resp.req.hdr.reqid);
    1935            0 :                         bytes.put_u64(resp.req.hdr.request_lsn.0);
    1936            0 :                         bytes.put_u64(resp.req.hdr.not_modified_since.0);
    1937            0 :                         bytes.put_u32(resp.req.rel.spcnode);
    1938            0 :                         bytes.put_u32(resp.req.rel.dbnode);
    1939            0 :                         bytes.put_u32(resp.req.rel.relnode);
    1940            0 :                         bytes.put_u8(resp.req.rel.forknum);
    1941            0 :                         bytes.put_u32(resp.n_blocks);
    1942            0 :                     }
    1943              : 
    1944            0 :                     Self::GetPage(resp) => {
    1945            0 :                         bytes.put_u8(Tag::GetPage as u8);
    1946            0 :                         bytes.put_u64(resp.req.hdr.reqid);
    1947            0 :                         bytes.put_u64(resp.req.hdr.request_lsn.0);
    1948            0 :                         bytes.put_u64(resp.req.hdr.not_modified_since.0);
    1949            0 :                         bytes.put_u32(resp.req.rel.spcnode);
    1950            0 :                         bytes.put_u32(resp.req.rel.dbnode);
    1951            0 :                         bytes.put_u32(resp.req.rel.relnode);
    1952            0 :                         bytes.put_u8(resp.req.rel.forknum);
    1953            0 :                         bytes.put_u32(resp.req.blkno);
    1954            0 :                         bytes.put(&resp.page[..])
    1955              :                     }
    1956              : 
    1957            0 :                     Self::Error(resp) => {
    1958            0 :                         bytes.put_u8(Tag::Error as u8);
    1959            0 :                         bytes.put_u64(resp.req.reqid);
    1960            0 :                         bytes.put_u64(resp.req.request_lsn.0);
    1961            0 :                         bytes.put_u64(resp.req.not_modified_since.0);
    1962            0 :                         bytes.put(resp.message.as_bytes());
    1963            0 :                         bytes.put_u8(0); // null terminator
    1964            0 :                     }
    1965            0 :                     Self::DbSize(resp) => {
    1966            0 :                         bytes.put_u8(Tag::DbSize as u8);
    1967            0 :                         bytes.put_u64(resp.req.hdr.reqid);
    1968            0 :                         bytes.put_u64(resp.req.hdr.request_lsn.0);
    1969            0 :                         bytes.put_u64(resp.req.hdr.not_modified_since.0);
    1970            0 :                         bytes.put_u32(resp.req.dbnode);
    1971            0 :                         bytes.put_i64(resp.db_size);
    1972            0 :                     }
    1973              : 
    1974            0 :                     Self::GetSlruSegment(resp) => {
    1975            0 :                         bytes.put_u8(Tag::GetSlruSegment as u8);
    1976            0 :                         bytes.put_u64(resp.req.hdr.reqid);
    1977            0 :                         bytes.put_u64(resp.req.hdr.request_lsn.0);
    1978            0 :                         bytes.put_u64(resp.req.hdr.not_modified_since.0);
    1979            0 :                         bytes.put_u8(resp.req.kind);
    1980            0 :                         bytes.put_u32(resp.req.segno);
    1981            0 :                         bytes.put_u32((resp.segment.len() / BLCKSZ as usize) as u32);
    1982            0 :                         bytes.put(&resp.segment[..]);
    1983            0 :                     }
    1984              : 
    1985              :                     #[cfg(feature = "testing")]
    1986            0 :                     Self::Test(resp) => {
    1987            0 :                         bytes.put_u8(Tag::Test as u8);
    1988            0 :                         bytes.put_u64(resp.req.hdr.reqid);
    1989            0 :                         bytes.put_u64(resp.req.hdr.request_lsn.0);
    1990            0 :                         bytes.put_u64(resp.req.hdr.not_modified_since.0);
    1991            0 :                         bytes.put_u64(resp.req.batch_key);
    1992            0 :                         let message = resp.req.message.as_bytes();
    1993            0 :                         bytes.put_u64(message.len() as u64);
    1994            0 :                         bytes.put_slice(message);
    1995            0 :                     }
    1996              :                 }
    1997              :             }
    1998              :         }
    1999            0 :         bytes.into()
    2000            0 :     }
    2001              : 
    2002            0 :     pub fn deserialize(buf: Bytes) -> anyhow::Result<Self> {
    2003            0 :         let mut buf = buf.reader();
    2004            0 :         let msg_tag = buf.read_u8()?;
    2005              : 
    2006              :         use PagestreamBeMessageTag as Tag;
    2007            0 :         let ok =
    2008            0 :             match Tag::try_from(msg_tag).map_err(|tag: u8| anyhow::anyhow!("invalid tag {tag}"))? {
    2009              :                 Tag::Exists => {
    2010            0 :                     let reqid = buf.read_u64::<BigEndian>()?;
    2011            0 :                     let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
    2012            0 :                     let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
    2013            0 :                     let rel = RelTag {
    2014            0 :                         spcnode: buf.read_u32::<BigEndian>()?,
    2015            0 :                         dbnode: buf.read_u32::<BigEndian>()?,
    2016            0 :                         relnode: buf.read_u32::<BigEndian>()?,
    2017            0 :                         forknum: buf.read_u8()?,
    2018              :                     };
    2019            0 :                     let exists = buf.read_u8()? != 0;
    2020            0 :                     Self::Exists(PagestreamExistsResponse {
    2021            0 :                         req: PagestreamExistsRequest {
    2022            0 :                             hdr: PagestreamRequest {
    2023            0 :                                 reqid,
    2024            0 :                                 request_lsn,
    2025            0 :                                 not_modified_since,
    2026            0 :                             },
    2027            0 :                             rel,
    2028            0 :                         },
    2029            0 :                         exists,
    2030            0 :                     })
    2031              :                 }
    2032              :                 Tag::Nblocks => {
    2033            0 :                     let reqid = buf.read_u64::<BigEndian>()?;
    2034            0 :                     let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
    2035            0 :                     let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
    2036            0 :                     let rel = RelTag {
    2037            0 :                         spcnode: buf.read_u32::<BigEndian>()?,
    2038            0 :                         dbnode: buf.read_u32::<BigEndian>()?,
    2039            0 :                         relnode: buf.read_u32::<BigEndian>()?,
    2040            0 :                         forknum: buf.read_u8()?,
    2041              :                     };
    2042            0 :                     let n_blocks = buf.read_u32::<BigEndian>()?;
    2043            0 :                     Self::Nblocks(PagestreamNblocksResponse {
    2044            0 :                         req: PagestreamNblocksRequest {
    2045            0 :                             hdr: PagestreamRequest {
    2046            0 :                                 reqid,
    2047            0 :                                 request_lsn,
    2048            0 :                                 not_modified_since,
    2049            0 :                             },
    2050            0 :                             rel,
    2051            0 :                         },
    2052            0 :                         n_blocks,
    2053            0 :                     })
    2054              :                 }
    2055              :                 Tag::GetPage => {
    2056            0 :                     let reqid = buf.read_u64::<BigEndian>()?;
    2057            0 :                     let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
    2058            0 :                     let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
    2059            0 :                     let rel = RelTag {
    2060            0 :                         spcnode: buf.read_u32::<BigEndian>()?,
    2061            0 :                         dbnode: buf.read_u32::<BigEndian>()?,
    2062            0 :                         relnode: buf.read_u32::<BigEndian>()?,
    2063            0 :                         forknum: buf.read_u8()?,
    2064              :                     };
    2065            0 :                     let blkno = buf.read_u32::<BigEndian>()?;
    2066            0 :                     let mut page = vec![0; 8192]; // TODO: use MaybeUninit
    2067            0 :                     buf.read_exact(&mut page)?;
    2068            0 :                     Self::GetPage(PagestreamGetPageResponse {
    2069            0 :                         req: PagestreamGetPageRequest {
    2070            0 :                             hdr: PagestreamRequest {
    2071            0 :                                 reqid,
    2072            0 :                                 request_lsn,
    2073            0 :                                 not_modified_since,
    2074            0 :                             },
    2075            0 :                             rel,
    2076            0 :                             blkno,
    2077            0 :                         },
    2078            0 :                         page: page.into(),
    2079            0 :                     })
    2080              :                 }
    2081              :                 Tag::Error => {
    2082            0 :                     let reqid = buf.read_u64::<BigEndian>()?;
    2083            0 :                     let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
    2084            0 :                     let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
    2085            0 :                     let mut msg = Vec::new();
    2086            0 :                     buf.read_until(0, &mut msg)?;
    2087            0 :                     let cstring = std::ffi::CString::from_vec_with_nul(msg)?;
    2088            0 :                     let rust_str = cstring.to_str()?;
    2089            0 :                     Self::Error(PagestreamErrorResponse {
    2090            0 :                         req: PagestreamRequest {
    2091            0 :                             reqid,
    2092            0 :                             request_lsn,
    2093            0 :                             not_modified_since,
    2094            0 :                         },
    2095            0 :                         message: rust_str.to_owned(),
    2096            0 :                     })
    2097              :                 }
    2098              :                 Tag::DbSize => {
    2099            0 :                     let reqid = buf.read_u64::<BigEndian>()?;
    2100            0 :                     let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
    2101            0 :                     let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
    2102            0 :                     let dbnode = buf.read_u32::<BigEndian>()?;
    2103            0 :                     let db_size = buf.read_i64::<BigEndian>()?;
    2104            0 :                     Self::DbSize(PagestreamDbSizeResponse {
    2105            0 :                         req: PagestreamDbSizeRequest {
    2106            0 :                             hdr: PagestreamRequest {
    2107            0 :                                 reqid,
    2108            0 :                                 request_lsn,
    2109            0 :                                 not_modified_since,
    2110            0 :                             },
    2111            0 :                             dbnode,
    2112            0 :                         },
    2113            0 :                         db_size,
    2114            0 :                     })
    2115              :                 }
    2116              :                 Tag::GetSlruSegment => {
    2117            0 :                     let reqid = buf.read_u64::<BigEndian>()?;
    2118            0 :                     let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
    2119            0 :                     let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
    2120            0 :                     let kind = buf.read_u8()?;
    2121            0 :                     let segno = buf.read_u32::<BigEndian>()?;
    2122            0 :                     let n_blocks = buf.read_u32::<BigEndian>()?;
    2123            0 :                     let mut segment = vec![0; n_blocks as usize * BLCKSZ as usize];
    2124            0 :                     buf.read_exact(&mut segment)?;
    2125            0 :                     Self::GetSlruSegment(PagestreamGetSlruSegmentResponse {
    2126            0 :                         req: PagestreamGetSlruSegmentRequest {
    2127            0 :                             hdr: PagestreamRequest {
    2128            0 :                                 reqid,
    2129            0 :                                 request_lsn,
    2130            0 :                                 not_modified_since,
    2131            0 :                             },
    2132            0 :                             kind,
    2133            0 :                             segno,
    2134            0 :                         },
    2135            0 :                         segment: segment.into(),
    2136            0 :                     })
    2137              :                 }
    2138              :                 #[cfg(feature = "testing")]
    2139              :                 Tag::Test => {
    2140            0 :                     let reqid = buf.read_u64::<BigEndian>()?;
    2141            0 :                     let request_lsn = Lsn(buf.read_u64::<BigEndian>()?);
    2142            0 :                     let not_modified_since = Lsn(buf.read_u64::<BigEndian>()?);
    2143            0 :                     let batch_key = buf.read_u64::<BigEndian>()?;
    2144            0 :                     let len = buf.read_u64::<BigEndian>()?;
    2145            0 :                     let mut msg = vec![0; len as usize];
    2146            0 :                     buf.read_exact(&mut msg)?;
    2147            0 :                     let message = String::from_utf8(msg)?;
    2148            0 :                     Self::Test(PagestreamTestResponse {
    2149            0 :                         req: PagestreamTestRequest {
    2150            0 :                             hdr: PagestreamRequest {
    2151            0 :                                 reqid,
    2152            0 :                                 request_lsn,
    2153            0 :                                 not_modified_since,
    2154            0 :                             },
    2155            0 :                             batch_key,
    2156            0 :                             message,
    2157            0 :                         },
    2158            0 :                     })
    2159              :                 }
    2160              :             };
    2161            0 :         let remaining = buf.into_inner();
    2162            0 :         if !remaining.is_empty() {
    2163            0 :             anyhow::bail!(
    2164            0 :                 "remaining bytes in msg with tag={msg_tag}: {}",
    2165            0 :                 remaining.len()
    2166            0 :             );
    2167            0 :         }
    2168            0 :         Ok(ok)
    2169            0 :     }
    2170              : 
    2171            0 :     pub fn kind(&self) -> &'static str {
    2172            0 :         match self {
    2173            0 :             Self::Exists(_) => "Exists",
    2174            0 :             Self::Nblocks(_) => "Nblocks",
    2175            0 :             Self::GetPage(_) => "GetPage",
    2176            0 :             Self::Error(_) => "Error",
    2177            0 :             Self::DbSize(_) => "DbSize",
    2178            0 :             Self::GetSlruSegment(_) => "GetSlruSegment",
    2179              :             #[cfg(feature = "testing")]
    2180            0 :             Self::Test(_) => "Test",
    2181              :         }
    2182            0 :     }
    2183              : }
    2184              : 
    2185            0 : #[derive(Debug, Serialize, Deserialize)]
    2186              : pub struct PageTraceEvent {
    2187              :     pub key: CompactKey,
    2188              :     pub effective_lsn: Lsn,
    2189              :     pub time: SystemTime,
    2190              : }
    2191              : 
    2192              : impl Default for PageTraceEvent {
    2193            0 :     fn default() -> Self {
    2194            0 :         Self {
    2195            0 :             key: Default::default(),
    2196            0 :             effective_lsn: Default::default(),
    2197            0 :             time: std::time::UNIX_EPOCH,
    2198            0 :         }
    2199            0 :     }
    2200              : }
    2201              : 
    2202              : #[cfg(test)]
    2203              : mod tests {
    2204              :     use serde_json::json;
    2205              :     use std::str::FromStr;
    2206              : 
    2207              :     use super::*;
    2208              : 
    2209              :     #[test]
    2210            1 :     fn test_pagestream() {
    2211            1 :         // Test serialization/deserialization of PagestreamFeMessage
    2212            1 :         let messages = vec![
    2213            1 :             PagestreamFeMessage::Exists(PagestreamExistsRequest {
    2214            1 :                 hdr: PagestreamRequest {
    2215            1 :                     reqid: 0,
    2216            1 :                     request_lsn: Lsn(4),
    2217            1 :                     not_modified_since: Lsn(3),
    2218            1 :                 },
    2219            1 :                 rel: RelTag {
    2220            1 :                     forknum: 1,
    2221            1 :                     spcnode: 2,
    2222            1 :                     dbnode: 3,
    2223            1 :                     relnode: 4,
    2224            1 :                 },
    2225            1 :             }),
    2226            1 :             PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
    2227            1 :                 hdr: PagestreamRequest {
    2228            1 :                     reqid: 0,
    2229            1 :                     request_lsn: Lsn(4),
    2230            1 :                     not_modified_since: Lsn(4),
    2231            1 :                 },
    2232            1 :                 rel: RelTag {
    2233            1 :                     forknum: 1,
    2234            1 :                     spcnode: 2,
    2235            1 :                     dbnode: 3,
    2236            1 :                     relnode: 4,
    2237            1 :                 },
    2238            1 :             }),
    2239            1 :             PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
    2240            1 :                 hdr: PagestreamRequest {
    2241            1 :                     reqid: 0,
    2242            1 :                     request_lsn: Lsn(4),
    2243            1 :                     not_modified_since: Lsn(3),
    2244            1 :                 },
    2245            1 :                 rel: RelTag {
    2246            1 :                     forknum: 1,
    2247            1 :                     spcnode: 2,
    2248            1 :                     dbnode: 3,
    2249            1 :                     relnode: 4,
    2250            1 :                 },
    2251            1 :                 blkno: 7,
    2252            1 :             }),
    2253            1 :             PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
    2254            1 :                 hdr: PagestreamRequest {
    2255            1 :                     reqid: 0,
    2256            1 :                     request_lsn: Lsn(4),
    2257            1 :                     not_modified_since: Lsn(3),
    2258            1 :                 },
    2259            1 :                 dbnode: 7,
    2260            1 :             }),
    2261            1 :         ];
    2262            5 :         for msg in messages {
    2263            4 :             let bytes = msg.serialize();
    2264            4 :             let reconstructed =
    2265            4 :                 PagestreamFeMessage::parse(&mut bytes.reader(), PagestreamProtocolVersion::V3)
    2266            4 :                     .unwrap();
    2267            4 :             assert!(msg == reconstructed);
    2268              :         }
    2269            1 :     }
    2270              : 
    2271              :     #[test]
    2272            1 :     fn test_tenantinfo_serde() {
    2273            1 :         // Test serialization/deserialization of TenantInfo
    2274            1 :         let original_active = TenantInfo {
    2275            1 :             id: TenantShardId::unsharded(TenantId::generate()),
    2276            1 :             state: TenantState::Active,
    2277            1 :             current_physical_size: Some(42),
    2278            1 :             attachment_status: TenantAttachmentStatus::Attached,
    2279            1 :             generation: 1,
    2280            1 :             gc_blocking: None,
    2281            1 :         };
    2282            1 :         let expected_active = json!({
    2283            1 :             "id": original_active.id.to_string(),
    2284            1 :             "state": {
    2285            1 :                 "slug": "Active",
    2286            1 :             },
    2287            1 :             "current_physical_size": 42,
    2288            1 :             "attachment_status": {
    2289            1 :                 "slug":"attached",
    2290            1 :             },
    2291            1 :             "generation" : 1
    2292            1 :         });
    2293            1 : 
    2294            1 :         let original_broken = TenantInfo {
    2295            1 :             id: TenantShardId::unsharded(TenantId::generate()),
    2296            1 :             state: TenantState::Broken {
    2297            1 :                 reason: "reason".into(),
    2298            1 :                 backtrace: "backtrace info".into(),
    2299            1 :             },
    2300            1 :             current_physical_size: Some(42),
    2301            1 :             attachment_status: TenantAttachmentStatus::Attached,
    2302            1 :             generation: 1,
    2303            1 :             gc_blocking: None,
    2304            1 :         };
    2305            1 :         let expected_broken = json!({
    2306            1 :             "id": original_broken.id.to_string(),
    2307            1 :             "state": {
    2308            1 :                 "slug": "Broken",
    2309            1 :                 "data": {
    2310            1 :                     "backtrace": "backtrace info",
    2311            1 :                     "reason": "reason",
    2312            1 :                 }
    2313            1 :             },
    2314            1 :             "current_physical_size": 42,
    2315            1 :             "attachment_status": {
    2316            1 :                 "slug":"attached",
    2317            1 :             },
    2318            1 :             "generation" : 1
    2319            1 :         });
    2320            1 : 
    2321            1 :         assert_eq!(
    2322            1 :             serde_json::to_value(&original_active).unwrap(),
    2323            1 :             expected_active
    2324            1 :         );
    2325              : 
    2326            1 :         assert_eq!(
    2327            1 :             serde_json::to_value(&original_broken).unwrap(),
    2328            1 :             expected_broken
    2329            1 :         );
    2330            1 :         assert!(format!("{:?}", &original_broken.state).contains("reason"));
    2331            1 :         assert!(format!("{:?}", &original_broken.state).contains("backtrace info"));
    2332            1 :     }
    2333              : 
    2334              :     #[test]
    2335            1 :     fn test_reject_unknown_field() {
    2336            1 :         let id = TenantId::generate();
    2337            1 :         let config_request = json!({
    2338            1 :             "tenant_id": id.to_string(),
    2339            1 :             "unknown_field": "unknown_value".to_string(),
    2340            1 :         });
    2341            1 :         let err = serde_json::from_value::<TenantConfigRequest>(config_request).unwrap_err();
    2342            1 :         assert!(
    2343            1 :             err.to_string().contains("unknown field `unknown_field`"),
    2344            0 :             "expect unknown field `unknown_field` error, got: {}",
    2345              :             err
    2346              :         );
    2347            1 :     }
    2348              : 
    2349              :     #[test]
    2350            1 :     fn tenantstatus_activating_serde() {
    2351            1 :         let states = [TenantState::Activating(ActivatingFrom::Attaching)];
    2352            1 :         let expected = "[{\"slug\":\"Activating\",\"data\":\"Attaching\"}]";
    2353            1 : 
    2354            1 :         let actual = serde_json::to_string(&states).unwrap();
    2355            1 : 
    2356            1 :         assert_eq!(actual, expected);
    2357              : 
    2358            1 :         let parsed = serde_json::from_str::<Vec<TenantState>>(&actual).unwrap();
    2359            1 : 
    2360            1 :         assert_eq!(states.as_slice(), &parsed);
    2361            1 :     }
    2362              : 
    2363              :     #[test]
    2364            1 :     fn tenantstatus_activating_strum() {
    2365            1 :         // tests added, because we use these for metrics
    2366            1 :         let examples = [
    2367            1 :             (line!(), TenantState::Attaching, "Attaching"),
    2368            1 :             (
    2369            1 :                 line!(),
    2370            1 :                 TenantState::Activating(ActivatingFrom::Attaching),
    2371            1 :                 "Activating",
    2372            1 :             ),
    2373            1 :             (line!(), TenantState::Active, "Active"),
    2374            1 :             (
    2375            1 :                 line!(),
    2376            1 :                 TenantState::Stopping {
    2377            1 :                     progress: utils::completion::Barrier::default(),
    2378            1 :                 },
    2379            1 :                 "Stopping",
    2380            1 :             ),
    2381            1 :             (
    2382            1 :                 line!(),
    2383            1 :                 TenantState::Broken {
    2384            1 :                     reason: "Example".into(),
    2385            1 :                     backtrace: "Looooong backtrace".into(),
    2386            1 :                 },
    2387            1 :                 "Broken",
    2388            1 :             ),
    2389            1 :         ];
    2390              : 
    2391            6 :         for (line, rendered, expected) in examples {
    2392            5 :             let actual: &'static str = rendered.into();
    2393            5 :             assert_eq!(actual, expected, "example on {line}");
    2394              :         }
    2395            1 :     }
    2396              : 
    2397              :     #[test]
    2398            1 :     fn test_image_compression_algorithm_parsing() {
    2399              :         use ImageCompressionAlgorithm::*;
    2400            1 :         let cases = [
    2401            1 :             ("disabled", Disabled),
    2402            1 :             ("zstd", Zstd { level: None }),
    2403            1 :             ("zstd(18)", Zstd { level: Some(18) }),
    2404            1 :             ("zstd(-3)", Zstd { level: Some(-3) }),
    2405            1 :         ];
    2406              : 
    2407            5 :         for (display, expected) in cases {
    2408            4 :             assert_eq!(
    2409            4 :                 ImageCompressionAlgorithm::from_str(display).unwrap(),
    2410              :                 expected,
    2411            0 :                 "parsing works"
    2412              :             );
    2413            4 :             assert_eq!(format!("{expected}"), display, "Display FromStr roundtrip");
    2414              : 
    2415            4 :             let ser = serde_json::to_string(&expected).expect("serialization");
    2416            4 :             assert_eq!(
    2417            4 :                 serde_json::from_str::<ImageCompressionAlgorithm>(&ser).unwrap(),
    2418              :                 expected,
    2419            0 :                 "serde roundtrip"
    2420              :             );
    2421              : 
    2422            4 :             assert_eq!(
    2423            4 :                 serde_json::Value::String(display.to_string()),
    2424            4 :                 serde_json::to_value(expected).unwrap(),
    2425            0 :                 "Display is the serde serialization"
    2426              :             );
    2427              :         }
    2428            1 :     }
    2429              : 
    2430              :     #[test]
    2431            1 :     fn test_tenant_config_patch_request_serde() {
    2432            1 :         let patch_request = TenantConfigPatchRequest {
    2433            1 :             tenant_id: TenantId::from_str("17c6d121946a61e5ab0fe5a2fd4d8215").unwrap(),
    2434            1 :             config: TenantConfigPatch {
    2435            1 :                 checkpoint_distance: FieldPatch::Upsert(42),
    2436            1 :                 gc_horizon: FieldPatch::Remove,
    2437            1 :                 compaction_threshold: FieldPatch::Noop,
    2438            1 :                 ..TenantConfigPatch::default()
    2439            1 :             },
    2440            1 :         };
    2441            1 : 
    2442            1 :         let json = serde_json::to_string(&patch_request).unwrap();
    2443            1 : 
    2444            1 :         let expected = r#"{"tenant_id":"17c6d121946a61e5ab0fe5a2fd4d8215","checkpoint_distance":42,"gc_horizon":null}"#;
    2445            1 :         assert_eq!(json, expected);
    2446              : 
    2447            1 :         let decoded: TenantConfigPatchRequest = serde_json::from_str(&json).unwrap();
    2448            1 :         assert_eq!(decoded.tenant_id, patch_request.tenant_id);
    2449            1 :         assert_eq!(decoded.config, patch_request.config);
    2450              : 
    2451              :         // Now apply the patch to a config to demonstrate semantics
    2452              : 
    2453            1 :         let base = TenantConfig {
    2454            1 :             checkpoint_distance: Some(28),
    2455            1 :             gc_horizon: Some(100),
    2456            1 :             compaction_target_size: Some(1024),
    2457            1 :             ..Default::default()
    2458            1 :         };
    2459            1 : 
    2460            1 :         let expected = TenantConfig {
    2461            1 :             checkpoint_distance: Some(42),
    2462            1 :             gc_horizon: None,
    2463            1 :             ..base.clone()
    2464            1 :         };
    2465            1 : 
    2466            1 :         let patched = base.apply_patch(decoded.config);
    2467            1 : 
    2468            1 :         assert_eq!(patched, expected);
    2469            1 :     }
    2470              : }
        

Generated by: LCOV version 2.1-beta