LCOV - code coverage report
Current view: top level - libs/pageserver_api/src - models.rs (source / functions) Coverage Total Hit
Test: 98683a8629f0f7f0031d02e04512998d589d76ea.info Lines: 52.0 % 1234 642
Test Date: 2025-04-11 16:58:57 Functions: 7.3 % 1032 75

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

Generated by: LCOV version 2.1-beta