LCOV - code coverage report
Current view: top level - libs/pageserver_api/src - models.rs (source / functions) Coverage Total Hit
Test: b4ae4c4857f9ef3e144e982a35ee23bc84c71983.info Lines: 58.2 % 639 372
Test Date: 2024-10-22 22:13:45 Functions: 4.1 % 1018 42

            Line data    Source code
       1              : pub mod detach_ancestor;
       2              : pub mod partitioning;
       3              : pub mod utilization;
       4              : 
       5              : pub use utilization::PageserverUtilization;
       6              : 
       7              : use std::{
       8              :     collections::HashMap,
       9              :     fmt::Display,
      10              :     io::{BufRead, Read},
      11              :     num::{NonZeroU32, NonZeroU64, NonZeroUsize},
      12              :     str::FromStr,
      13              :     sync::atomic::AtomicUsize,
      14              :     time::{Duration, SystemTime},
      15              : };
      16              : 
      17              : use byteorder::{BigEndian, ReadBytesExt};
      18              : use postgres_ffi::BLCKSZ;
      19              : use serde::{Deserialize, Serialize};
      20              : use serde_with::serde_as;
      21              : use utils::{
      22              :     completion,
      23              :     id::{NodeId, TenantId, TimelineId},
      24              :     lsn::Lsn,
      25              :     serde_system_time,
      26              : };
      27              : 
      28              : use crate::{
      29              :     reltag::RelTag,
      30              :     shard::{ShardCount, ShardStripeSize, TenantShardId},
      31              : };
      32              : use anyhow::bail;
      33              : use bytes::{Buf, BufMut, Bytes, BytesMut};
      34              : 
      35              : /// The state of a tenant in this pageserver.
      36              : ///
      37              : /// ```mermaid
      38              : /// stateDiagram-v2
      39              : ///
      40              : ///     [*] --> Attaching: spawn_attach()
      41              : ///
      42              : ///     Attaching --> Activating: activate()
      43              : ///     Activating --> Active: infallible
      44              : ///
      45              : ///     Attaching --> Broken: attach() failure
      46              : ///
      47              : ///     Active --> Stopping: set_stopping(), part of shutdown & detach
      48              : ///     Stopping --> Broken: late error in remove_tenant_from_memory
      49              : ///
      50              : ///     Broken --> [*]: ignore / detach / shutdown
      51              : ///     Stopping --> [*]: remove_from_memory complete
      52              : ///
      53              : ///     Active --> Broken: cfg(testing)-only tenant break point
      54              : /// ```
      55              : #[derive(
      56              :     Clone,
      57              :     PartialEq,
      58              :     Eq,
      59            1 :     serde::Serialize,
      60            3 :     serde::Deserialize,
      61            0 :     strum_macros::Display,
      62              :     strum_macros::VariantNames,
      63            0 :     strum_macros::AsRefStr,
      64          375 :     strum_macros::IntoStaticStr,
      65              : )]
      66              : #[serde(tag = "slug", content = "data")]
      67              : pub enum TenantState {
      68              :     /// This tenant is being attached to the pageserver.
      69              :     ///
      70              :     /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
      71              :     Attaching,
      72              :     /// The tenant is transitioning from Loading/Attaching to Active.
      73              :     ///
      74              :     /// While in this state, the individual timelines are being activated.
      75              :     ///
      76              :     /// `set_stopping()` and `set_broken()` do not work in this state and wait for it to pass.
      77              :     Activating(ActivatingFrom),
      78              :     /// The tenant has finished activating and is open for business.
      79              :     ///
      80              :     /// Transitions out of this state are possible through `set_stopping()` and `set_broken()`.
      81              :     Active,
      82              :     /// The tenant is recognized by pageserver, but it is being detached or the
      83              :     /// system is being shut down.
      84              :     ///
      85              :     /// Transitions out of this state are possible through `set_broken()`.
      86              :     Stopping {
      87              :         // Because of https://github.com/serde-rs/serde/issues/2105 this has to be a named field,
      88              :         // otherwise it will not be skipped during deserialization
      89              :         #[serde(skip)]
      90              :         progress: completion::Barrier,
      91              :     },
      92              :     /// The tenant is recognized by the pageserver, but can no longer be used for
      93              :     /// any operations.
      94              :     ///
      95              :     /// If the tenant fails to load or attach, it will transition to this state
      96              :     /// and it is guaranteed that no background tasks are running in its name.
      97              :     ///
      98              :     /// The other way to transition into this state is from `Stopping` state
      99              :     /// through `set_broken()` called from `remove_tenant_from_memory()`. That happens
     100              :     /// if the cleanup future executed by `remove_tenant_from_memory()` fails.
     101              :     Broken { reason: String, backtrace: String },
     102              : }
     103              : 
     104              : impl TenantState {
     105            0 :     pub fn attachment_status(&self) -> TenantAttachmentStatus {
     106              :         use TenantAttachmentStatus::*;
     107              : 
     108              :         // Below TenantState::Activating is used as "transient" or "transparent" state for
     109              :         // attachment_status determining.
     110            0 :         match self {
     111              :             // The attach procedure writes the marker file before adding the Attaching tenant to the tenants map.
     112              :             // So, technically, we can return Attached here.
     113              :             // However, as soon as Console observes Attached, it will proceed with the Postgres-level health check.
     114              :             // But, our attach task might still be fetching the remote timelines, etc.
     115              :             // So, return `Maybe` while Attaching, making Console wait for the attach task to finish.
     116            0 :             Self::Attaching | Self::Activating(ActivatingFrom::Attaching) => Maybe,
     117              :             // We only reach Active after successful load / attach.
     118              :             // So, call atttachment status Attached.
     119            0 :             Self::Active => Attached,
     120              :             // If the (initial or resumed) attach procedure fails, the tenant becomes Broken.
     121              :             // However, it also becomes Broken if the regular load fails.
     122              :             // From Console's perspective there's no practical difference
     123              :             // because attachment_status is polled by console only during attach operation execution.
     124            0 :             Self::Broken { reason, .. } => Failed {
     125            0 :                 reason: reason.to_owned(),
     126            0 :             },
     127              :             // Why is Stopping a Maybe case? Because, during pageserver shutdown,
     128              :             // we set the Stopping state irrespective of whether the tenant
     129              :             // has finished attaching or not.
     130            0 :             Self::Stopping { .. } => Maybe,
     131              :         }
     132            0 :     }
     133              : 
     134            0 :     pub fn broken_from_reason(reason: String) -> Self {
     135            0 :         let backtrace_str: String = format!("{}", std::backtrace::Backtrace::force_capture());
     136            0 :         Self::Broken {
     137            0 :             reason,
     138            0 :             backtrace: backtrace_str,
     139            0 :         }
     140            0 :     }
     141              : }
     142              : 
     143              : impl std::fmt::Debug for TenantState {
     144            2 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     145            2 :         match self {
     146            2 :             Self::Broken { reason, backtrace } if !reason.is_empty() => {
     147            2 :                 write!(f, "Broken due to: {reason}. Backtrace:\n{backtrace}")
     148              :             }
     149            0 :             _ => write!(f, "{self}"),
     150              :         }
     151            2 :     }
     152              : }
     153              : 
     154              : /// A temporary lease to a specific lsn inside a timeline.
     155              : /// Access to the lsn is guaranteed by the pageserver until the expiration indicated by `valid_until`.
     156              : #[serde_as]
     157            0 : #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
     158              : pub struct LsnLease {
     159              :     #[serde_as(as = "SystemTimeAsRfc3339Millis")]
     160              :     pub valid_until: SystemTime,
     161              : }
     162              : 
     163              : serde_with::serde_conv!(
     164              :     SystemTimeAsRfc3339Millis,
     165              :     SystemTime,
     166            0 :     |time: &SystemTime| humantime::format_rfc3339_millis(*time).to_string(),
     167            0 :     |value: String| -> Result<_, humantime::TimestampError> { humantime::parse_rfc3339(&value) }
     168              : );
     169              : 
     170              : impl LsnLease {
     171              :     /// The default length for an explicit LSN lease request (10 minutes).
     172              :     pub const DEFAULT_LENGTH: Duration = Duration::from_secs(10 * 60);
     173              : 
     174              :     /// The default length for an implicit LSN lease granted during
     175              :     /// `get_lsn_by_timestamp` request (1 minutes).
     176              :     pub const DEFAULT_LENGTH_FOR_TS: Duration = Duration::from_secs(60);
     177              : 
     178              :     /// Checks whether the lease is expired.
     179            6 :     pub fn is_expired(&self, now: &SystemTime) -> bool {
     180            6 :         now > &self.valid_until
     181            6 :     }
     182              : }
     183              : 
     184              : /// The only [`TenantState`] variants we could be `TenantState::Activating` from.
     185              : ///
     186              : /// XXX: We used to have more variants here, but now it's just one, which makes this rather
     187              : /// useless. Remove, once we've checked that there's no client code left that looks at this.
     188            2 : #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
     189              : pub enum ActivatingFrom {
     190              :     /// Arrived to [`TenantState::Activating`] from [`TenantState::Attaching`]
     191              :     Attaching,
     192              : }
     193              : 
     194              : /// A state of a timeline in pageserver's memory.
     195            0 : #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
     196              : pub enum TimelineState {
     197              :     /// The timeline is recognized by the pageserver but is not yet operational.
     198              :     /// In particular, the walreceiver connection loop is not running for this timeline.
     199              :     /// It will eventually transition to state Active or Broken.
     200              :     Loading,
     201              :     /// The timeline is fully operational.
     202              :     /// It can be queried, and the walreceiver connection loop is running.
     203              :     Active,
     204              :     /// The timeline was previously Loading or Active but is shutting down.
     205              :     /// It cannot transition back into any other state.
     206              :     Stopping,
     207              :     /// The timeline is broken and not operational (previous states: Loading or Active).
     208              :     Broken { reason: String, backtrace: String },
     209              : }
     210              : 
     211            0 : #[derive(Serialize, Deserialize, Clone)]
     212              : pub struct TimelineCreateRequest {
     213              :     pub new_timeline_id: TimelineId,
     214              :     #[serde(default)]
     215              :     pub ancestor_timeline_id: Option<TimelineId>,
     216              :     #[serde(default)]
     217              :     pub existing_initdb_timeline_id: Option<TimelineId>,
     218              :     #[serde(default)]
     219              :     pub ancestor_start_lsn: Option<Lsn>,
     220              :     pub pg_version: Option<u32>,
     221              : }
     222              : 
     223            0 : #[derive(Serialize, Deserialize, Clone)]
     224              : pub struct LsnLeaseRequest {
     225              :     pub lsn: Lsn,
     226              : }
     227              : 
     228            0 : #[derive(Serialize, Deserialize)]
     229              : pub struct TenantShardSplitRequest {
     230              :     pub new_shard_count: u8,
     231              : 
     232              :     // A tenant's stripe size is only meaningful the first time their shard count goes
     233              :     // above 1: therefore during a split from 1->N shards, we may modify the stripe size.
     234              :     //
     235              :     // If this is set while the stripe count is being increased from an already >1 value,
     236              :     // then the request will fail with 400.
     237              :     pub new_stripe_size: Option<ShardStripeSize>,
     238              : }
     239              : 
     240            0 : #[derive(Serialize, Deserialize)]
     241              : pub struct TenantShardSplitResponse {
     242              :     pub new_shards: Vec<TenantShardId>,
     243              : }
     244              : 
     245              : /// Parameters that apply to all shards in a tenant.  Used during tenant creation.
     246            0 : #[derive(Serialize, Deserialize, Debug)]
     247              : #[serde(deny_unknown_fields)]
     248              : pub struct ShardParameters {
     249              :     pub count: ShardCount,
     250              :     pub stripe_size: ShardStripeSize,
     251              : }
     252              : 
     253              : impl ShardParameters {
     254              :     pub const DEFAULT_STRIPE_SIZE: ShardStripeSize = ShardStripeSize(256 * 1024 / 8);
     255              : 
     256            0 :     pub fn is_unsharded(&self) -> bool {
     257            0 :         self.count.is_unsharded()
     258            0 :     }
     259              : }
     260              : 
     261              : impl Default for ShardParameters {
     262          187 :     fn default() -> Self {
     263          187 :         Self {
     264          187 :             count: ShardCount::new(0),
     265          187 :             stripe_size: Self::DEFAULT_STRIPE_SIZE,
     266          187 :         }
     267          187 :     }
     268              : }
     269              : 
     270              : /// An alternative representation of `pageserver::tenant::TenantConf` with
     271              : /// simpler types.
     272            2 : #[derive(Serialize, Deserialize, Debug, Default, Clone, Eq, PartialEq)]
     273              : pub struct TenantConfig {
     274              :     pub checkpoint_distance: Option<u64>,
     275              :     pub checkpoint_timeout: Option<String>,
     276              :     pub compaction_target_size: Option<u64>,
     277              :     pub compaction_period: Option<String>,
     278              :     pub compaction_threshold: Option<usize>,
     279              :     // defer parsing compaction_algorithm, like eviction_policy
     280              :     pub compaction_algorithm: Option<CompactionAlgorithmSettings>,
     281              :     pub gc_horizon: Option<u64>,
     282              :     pub gc_period: Option<String>,
     283              :     pub image_creation_threshold: Option<usize>,
     284              :     pub pitr_interval: Option<String>,
     285              :     pub walreceiver_connect_timeout: Option<String>,
     286              :     pub lagging_wal_timeout: Option<String>,
     287              :     pub max_lsn_wal_lag: Option<NonZeroU64>,
     288              :     pub eviction_policy: Option<EvictionPolicy>,
     289              :     pub min_resident_size_override: Option<u64>,
     290              :     pub evictions_low_residence_duration_metric_threshold: Option<String>,
     291              :     pub heatmap_period: Option<String>,
     292              :     pub lazy_slru_download: Option<bool>,
     293              :     pub timeline_get_throttle: Option<ThrottleConfig>,
     294              :     pub image_layer_creation_check_threshold: Option<u8>,
     295              :     pub switch_aux_file_policy: Option<AuxFilePolicy>,
     296              :     pub lsn_lease_length: Option<String>,
     297              :     pub lsn_lease_length_for_ts: Option<String>,
     298              : }
     299              : 
     300              : /// The policy for the aux file storage.
     301              : ///
     302              : /// It can be switched through `switch_aux_file_policy` tenant config.
     303              : /// When the first aux file written, the policy will be persisted in the
     304              : /// `index_part.json` file and has a limited migration path.
     305              : ///
     306              : /// Currently, we only allow the following migration path:
     307              : ///
     308              : /// Unset -> V1
     309              : ///       -> V2
     310              : ///       -> CrossValidation -> V2
     311              : #[derive(
     312              :     Eq,
     313              :     PartialEq,
     314              :     Debug,
     315              :     Copy,
     316              :     Clone,
     317            5 :     strum_macros::EnumString,
     318            0 :     strum_macros::Display,
     319            0 :     serde_with::DeserializeFromStr,
     320              :     serde_with::SerializeDisplay,
     321              : )]
     322              : #[strum(serialize_all = "kebab-case")]
     323              : pub enum AuxFilePolicy {
     324              :     /// V1 aux file policy: store everything in AUX_FILE_KEY
     325              :     #[strum(ascii_case_insensitive)]
     326              :     V1,
     327              :     /// V2 aux file policy: store in the AUX_FILE keyspace
     328              :     #[strum(ascii_case_insensitive)]
     329              :     V2,
     330              :     /// Cross validation runs both formats on the write path and does validation
     331              :     /// on the read path.
     332              :     #[strum(ascii_case_insensitive)]
     333              :     CrossValidation,
     334              : }
     335              : 
     336              : impl AuxFilePolicy {
     337           12 :     pub fn is_valid_migration_path(from: Option<Self>, to: Self) -> bool {
     338            8 :         matches!(
     339           12 :             (from, to),
     340              :             (None, _) | (Some(AuxFilePolicy::CrossValidation), AuxFilePolicy::V2)
     341              :         )
     342           12 :     }
     343              : 
     344              :     /// If a tenant writes aux files without setting `switch_aux_policy`, this value will be used.
     345          382 :     pub fn default_tenant_config() -> Self {
     346          382 :         Self::V2
     347          382 :     }
     348              : }
     349              : 
     350              : /// The aux file policy memory flag. Users can store `Option<AuxFilePolicy>` into this atomic flag. 0 == unspecified.
     351              : pub struct AtomicAuxFilePolicy(AtomicUsize);
     352              : 
     353              : impl AtomicAuxFilePolicy {
     354            0 :     pub fn new(policy: Option<AuxFilePolicy>) -> Self {
     355            0 :         Self(AtomicUsize::new(
     356            0 :             policy.map(AuxFilePolicy::to_usize).unwrap_or_default(),
     357            0 :         ))
     358            0 :     }
     359              : 
     360            0 :     pub fn load(&self) -> Option<AuxFilePolicy> {
     361            0 :         match self.0.load(std::sync::atomic::Ordering::Acquire) {
     362            0 :             0 => None,
     363            0 :             other => Some(AuxFilePolicy::from_usize(other)),
     364              :         }
     365            0 :     }
     366              : 
     367            0 :     pub fn store(&self, policy: Option<AuxFilePolicy>) {
     368            0 :         self.0.store(
     369            0 :             policy.map(AuxFilePolicy::to_usize).unwrap_or_default(),
     370            0 :             std::sync::atomic::Ordering::Release,
     371            0 :         );
     372            0 :     }
     373              : }
     374              : 
     375              : impl AuxFilePolicy {
     376            0 :     pub fn to_usize(self) -> usize {
     377            0 :         match self {
     378            0 :             Self::V1 => 1,
     379            0 :             Self::CrossValidation => 2,
     380            0 :             Self::V2 => 3,
     381              :         }
     382            0 :     }
     383              : 
     384            0 :     pub fn try_from_usize(this: usize) -> Option<Self> {
     385            0 :         match this {
     386            0 :             1 => Some(Self::V1),
     387            0 :             2 => Some(Self::CrossValidation),
     388            0 :             3 => Some(Self::V2),
     389            0 :             _ => None,
     390              :         }
     391            0 :     }
     392              : 
     393            0 :     pub fn from_usize(this: usize) -> Self {
     394            0 :         Self::try_from_usize(this).unwrap()
     395            0 :     }
     396              : }
     397              : 
     398            0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
     399              : #[serde(tag = "kind")]
     400              : pub enum EvictionPolicy {
     401              :     NoEviction,
     402              :     LayerAccessThreshold(EvictionPolicyLayerAccessThreshold),
     403              :     OnlyImitiate(EvictionPolicyLayerAccessThreshold),
     404              : }
     405              : 
     406              : impl EvictionPolicy {
     407            0 :     pub fn discriminant_str(&self) -> &'static str {
     408            0 :         match self {
     409            0 :             EvictionPolicy::NoEviction => "NoEviction",
     410            0 :             EvictionPolicy::LayerAccessThreshold(_) => "LayerAccessThreshold",
     411            0 :             EvictionPolicy::OnlyImitiate(_) => "OnlyImitiate",
     412              :         }
     413            0 :     }
     414              : }
     415              : 
     416              : #[derive(
     417              :     Eq,
     418              :     PartialEq,
     419              :     Debug,
     420              :     Copy,
     421              :     Clone,
     422            0 :     strum_macros::EnumString,
     423            0 :     strum_macros::Display,
     424            0 :     serde_with::DeserializeFromStr,
     425              :     serde_with::SerializeDisplay,
     426              : )]
     427              : #[strum(serialize_all = "kebab-case")]
     428              : pub enum CompactionAlgorithm {
     429              :     Legacy,
     430              :     Tiered,
     431              : }
     432              : 
     433              : #[derive(
     434            0 :     Debug, Clone, Copy, PartialEq, Eq, serde_with::DeserializeFromStr, serde_with::SerializeDisplay,
     435              : )]
     436              : pub enum ImageCompressionAlgorithm {
     437              :     // Disabled for writes, support decompressing during read path
     438              :     Disabled,
     439              :     /// Zstandard compression. Level 0 means and None mean the same (default level). Levels can be negative as well.
     440              :     /// For details, see the [manual](http://facebook.github.io/zstd/zstd_manual.html).
     441              :     Zstd {
     442              :         level: Option<i8>,
     443              :     },
     444              : }
     445              : 
     446              : impl FromStr for ImageCompressionAlgorithm {
     447              :     type Err = anyhow::Error;
     448            8 :     fn from_str(s: &str) -> Result<Self, Self::Err> {
     449            8 :         let mut components = s.split(['(', ')']);
     450            8 :         let first = components
     451            8 :             .next()
     452            8 :             .ok_or_else(|| anyhow::anyhow!("empty string"))?;
     453            8 :         match first {
     454            8 :             "disabled" => Ok(ImageCompressionAlgorithm::Disabled),
     455            6 :             "zstd" => {
     456            6 :                 let level = if let Some(v) = components.next() {
     457            4 :                     let v: i8 = v.parse()?;
     458            4 :                     Some(v)
     459              :                 } else {
     460            2 :                     None
     461              :                 };
     462              : 
     463            6 :                 Ok(ImageCompressionAlgorithm::Zstd { level })
     464              :             }
     465            0 :             _ => anyhow::bail!("invalid specifier '{first}'"),
     466              :         }
     467            8 :     }
     468              : }
     469              : 
     470              : impl Display for ImageCompressionAlgorithm {
     471           12 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
     472           12 :         match self {
     473            3 :             ImageCompressionAlgorithm::Disabled => write!(f, "disabled"),
     474            9 :             ImageCompressionAlgorithm::Zstd { level } => {
     475            9 :                 if let Some(level) = level {
     476            6 :                     write!(f, "zstd({})", level)
     477              :                 } else {
     478            3 :                     write!(f, "zstd")
     479              :                 }
     480              :             }
     481              :         }
     482           12 :     }
     483              : }
     484              : 
     485            0 : #[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize)]
     486              : pub struct CompactionAlgorithmSettings {
     487              :     pub kind: CompactionAlgorithm,
     488              : }
     489              : 
     490            6 : #[derive(Debug, PartialEq, Eq, Clone, Deserialize, Serialize)]
     491              : #[serde(tag = "mode", rename_all = "kebab-case", deny_unknown_fields)]
     492              : pub enum L0FlushConfig {
     493              :     #[serde(rename_all = "snake_case")]
     494              :     Direct { max_concurrency: NonZeroUsize },
     495              : }
     496              : 
     497            0 : #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
     498              : pub struct EvictionPolicyLayerAccessThreshold {
     499              :     #[serde(with = "humantime_serde")]
     500              :     pub period: Duration,
     501              :     #[serde(with = "humantime_serde")]
     502              :     pub threshold: Duration,
     503              : }
     504              : 
     505            0 : #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
     506              : pub struct ThrottleConfig {
     507              :     pub task_kinds: Vec<String>, // TaskKind
     508              :     pub initial: u32,
     509              :     #[serde(with = "humantime_serde")]
     510              :     pub refill_interval: Duration,
     511              :     pub refill_amount: NonZeroU32,
     512              :     pub max: u32,
     513              : }
     514              : 
     515              : impl ThrottleConfig {
     516          382 :     pub fn disabled() -> Self {
     517          382 :         Self {
     518          382 :             task_kinds: vec![], // effectively disables the throttle
     519          382 :             // other values don't matter with emtpy `task_kinds`.
     520          382 :             initial: 0,
     521          382 :             refill_interval: Duration::from_millis(1),
     522          382 :             refill_amount: NonZeroU32::new(1).unwrap(),
     523          382 :             max: 1,
     524          382 :         }
     525          382 :     }
     526              :     /// The requests per second allowed  by the given config.
     527            0 :     pub fn steady_rps(&self) -> f64 {
     528            0 :         (self.refill_amount.get() as f64) / (self.refill_interval.as_secs_f64())
     529            0 :     }
     530              : }
     531              : 
     532              : /// A flattened analog of a `pagesever::tenant::LocationMode`, which
     533              : /// lists out all possible states (and the virtual "Detached" state)
     534              : /// in a flat form rather than using rust-style enums.
     535            0 : #[derive(Serialize, Deserialize, Debug, Clone, Copy, Eq, PartialEq)]
     536              : pub enum LocationConfigMode {
     537              :     AttachedSingle,
     538              :     AttachedMulti,
     539              :     AttachedStale,
     540              :     Secondary,
     541              :     Detached,
     542              : }
     543              : 
     544            0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
     545              : pub struct LocationConfigSecondary {
     546              :     pub warm: bool,
     547              : }
     548              : 
     549              : /// An alternative representation of `pageserver::tenant::LocationConf`,
     550              : /// for use in external-facing APIs.
     551            0 : #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
     552              : pub struct LocationConfig {
     553              :     pub mode: LocationConfigMode,
     554              :     /// If attaching, in what generation?
     555              :     #[serde(default)]
     556              :     pub generation: Option<u32>,
     557              : 
     558              :     // If requesting mode `Secondary`, configuration for that.
     559              :     #[serde(default)]
     560              :     pub secondary_conf: Option<LocationConfigSecondary>,
     561              : 
     562              :     // Shard parameters: if shard_count is nonzero, then other shard_* fields
     563              :     // must be set accurately.
     564              :     #[serde(default)]
     565              :     pub shard_number: u8,
     566              :     #[serde(default)]
     567              :     pub shard_count: u8,
     568              :     #[serde(default)]
     569              :     pub shard_stripe_size: u32,
     570              : 
     571              :     // This configuration only affects attached mode, but should be provided irrespective
     572              :     // of the mode, as a secondary location might transition on startup if the response
     573              :     // to the `/re-attach` control plane API requests it.
     574              :     pub tenant_conf: TenantConfig,
     575              : }
     576              : 
     577            0 : #[derive(Serialize, Deserialize)]
     578              : pub struct LocationConfigListResponse {
     579              :     pub tenant_shards: Vec<(TenantShardId, Option<LocationConfig>)>,
     580              : }
     581              : 
     582              : #[derive(Serialize)]
     583              : pub struct StatusResponse {
     584              :     pub id: NodeId,
     585              : }
     586              : 
     587            0 : #[derive(Serialize, Deserialize, Debug)]
     588              : #[serde(deny_unknown_fields)]
     589              : pub struct TenantLocationConfigRequest {
     590              :     #[serde(flatten)]
     591              :     pub config: LocationConfig, // as we have a flattened field, we should reject all unknown fields in it
     592              : }
     593              : 
     594            0 : #[derive(Serialize, Deserialize, Debug)]
     595              : #[serde(deny_unknown_fields)]
     596              : pub struct TenantTimeTravelRequest {
     597              :     pub shard_counts: Vec<ShardCount>,
     598              : }
     599              : 
     600            0 : #[derive(Serialize, Deserialize, Debug)]
     601              : #[serde(deny_unknown_fields)]
     602              : pub struct TenantShardLocation {
     603              :     pub shard_id: TenantShardId,
     604              :     pub node_id: NodeId,
     605              : }
     606              : 
     607            0 : #[derive(Serialize, Deserialize, Debug)]
     608              : #[serde(deny_unknown_fields)]
     609              : pub struct TenantLocationConfigResponse {
     610              :     pub shards: Vec<TenantShardLocation>,
     611              :     // If the shards' ShardCount count is >1, stripe_size will be set.
     612              :     pub stripe_size: Option<ShardStripeSize>,
     613              : }
     614              : 
     615            3 : #[derive(Serialize, Deserialize, Debug)]
     616              : #[serde(deny_unknown_fields)]
     617              : pub struct TenantConfigRequest {
     618              :     pub tenant_id: TenantId,
     619              :     #[serde(flatten)]
     620              :     pub config: TenantConfig, // as we have a flattened field, we should reject all unknown fields in it
     621              : }
     622              : 
     623              : impl std::ops::Deref for TenantConfigRequest {
     624              :     type Target = TenantConfig;
     625              : 
     626            0 :     fn deref(&self) -> &Self::Target {
     627            0 :         &self.config
     628            0 :     }
     629              : }
     630              : 
     631              : impl TenantConfigRequest {
     632            0 :     pub fn new(tenant_id: TenantId) -> TenantConfigRequest {
     633            0 :         let config = TenantConfig::default();
     634            0 :         TenantConfigRequest { tenant_id, config }
     635            0 :     }
     636              : }
     637              : 
     638              : /// See [`TenantState::attachment_status`] and the OpenAPI docs for context.
     639            0 : #[derive(Serialize, Deserialize, Clone)]
     640              : #[serde(tag = "slug", content = "data", rename_all = "snake_case")]
     641              : pub enum TenantAttachmentStatus {
     642              :     Maybe,
     643              :     Attached,
     644              :     Failed { reason: String },
     645              : }
     646              : 
     647            0 : #[derive(Serialize, Deserialize, Clone)]
     648              : pub struct TenantInfo {
     649              :     pub id: TenantShardId,
     650              :     // NB: intentionally not part of OpenAPI, we don't want to commit to a specific set of TenantState's
     651              :     pub state: TenantState,
     652              :     /// Sum of the size of all layer files.
     653              :     /// If a layer is present in both local FS and S3, it counts only once.
     654              :     pub current_physical_size: Option<u64>, // physical size is only included in `tenant_status` endpoint
     655              :     pub attachment_status: TenantAttachmentStatus,
     656              :     pub generation: u32,
     657              : 
     658              :     /// Opaque explanation if gc is being blocked.
     659              :     ///
     660              :     /// Only looked up for the individual tenant detail, not the listing. This is purely for
     661              :     /// debugging, not included in openapi.
     662              :     #[serde(skip_serializing_if = "Option::is_none")]
     663              :     pub gc_blocking: Option<String>,
     664              : }
     665              : 
     666            0 : #[derive(Serialize, Deserialize, Clone)]
     667              : pub struct TenantDetails {
     668              :     #[serde(flatten)]
     669              :     pub tenant_info: TenantInfo,
     670              : 
     671              :     pub walredo: Option<WalRedoManagerStatus>,
     672              : 
     673              :     pub timelines: Vec<TimelineId>,
     674              : }
     675              : 
     676            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Copy, Debug)]
     677              : pub enum TimelineArchivalState {
     678              :     Archived,
     679              :     Unarchived,
     680              : }
     681              : 
     682            0 : #[derive(Serialize, Deserialize, PartialEq, Eq, Clone)]
     683              : pub struct TimelineArchivalConfigRequest {
     684              :     pub state: TimelineArchivalState,
     685              : }
     686              : 
     687            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
     688              : pub struct TimelinesInfoAndOffloaded {
     689              :     pub timelines: Vec<TimelineInfo>,
     690              :     pub offloaded: Vec<OffloadedTimelineInfo>,
     691              : }
     692              : 
     693              : /// Analog of [`TimelineInfo`] for offloaded timelines.
     694            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
     695              : pub struct OffloadedTimelineInfo {
     696              :     pub tenant_id: TenantShardId,
     697              :     pub timeline_id: TimelineId,
     698              :     /// Whether the timeline has a parent it has been branched off from or not
     699              :     pub ancestor_timeline_id: Option<TimelineId>,
     700              :     /// Whether to retain the branch lsn at the ancestor or not
     701              :     pub ancestor_retain_lsn: Option<Lsn>,
     702              : }
     703              : 
     704              : /// This represents the output of the "timeline_detail" and "timeline_list" API calls.
     705            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
     706              : pub struct TimelineInfo {
     707              :     pub tenant_id: TenantShardId,
     708              :     pub timeline_id: TimelineId,
     709              : 
     710              :     pub ancestor_timeline_id: Option<TimelineId>,
     711              :     pub ancestor_lsn: Option<Lsn>,
     712              :     pub last_record_lsn: Lsn,
     713              :     pub prev_record_lsn: Option<Lsn>,
     714              :     pub latest_gc_cutoff_lsn: Lsn,
     715              :     pub disk_consistent_lsn: Lsn,
     716              : 
     717              :     /// The LSN that we have succesfully uploaded to remote storage
     718              :     pub remote_consistent_lsn: Lsn,
     719              : 
     720              :     /// The LSN that we are advertizing to safekeepers
     721              :     pub remote_consistent_lsn_visible: Lsn,
     722              : 
     723              :     /// The LSN from the start of the root timeline (never changes)
     724              :     pub initdb_lsn: Lsn,
     725              : 
     726              :     pub current_logical_size: u64,
     727              :     pub current_logical_size_is_accurate: bool,
     728              : 
     729              :     pub directory_entries_counts: Vec<u64>,
     730              : 
     731              :     /// Sum of the size of all layer files.
     732              :     /// If a layer is present in both local FS and S3, it counts only once.
     733              :     pub current_physical_size: Option<u64>, // is None when timeline is Unloaded
     734              :     pub current_logical_size_non_incremental: Option<u64>,
     735              : 
     736              :     /// How many bytes of WAL are within this branch's pitr_interval.  If the pitr_interval goes
     737              :     /// beyond the branch's branch point, we only count up to the branch point.
     738              :     pub pitr_history_size: u64,
     739              : 
     740              :     /// Whether this branch's branch point is within its ancestor's PITR interval (i.e. any
     741              :     /// ancestor data used by this branch would have been retained anyway).  If this is false, then
     742              :     /// this branch may be imposing a cost on the ancestor by causing it to retain layers that it would
     743              :     /// otherwise be able to GC.
     744              :     pub within_ancestor_pitr: bool,
     745              : 
     746              :     pub timeline_dir_layer_file_size_sum: Option<u64>,
     747              : 
     748              :     pub wal_source_connstr: Option<String>,
     749              :     pub last_received_msg_lsn: Option<Lsn>,
     750              :     /// the timestamp (in microseconds) of the last received message
     751              :     pub last_received_msg_ts: Option<u128>,
     752              :     pub pg_version: u32,
     753              : 
     754              :     pub state: TimelineState,
     755              : 
     756              :     pub walreceiver_status: String,
     757              : 
     758              :     // ALWAYS add new fields at the end of the struct with `Option` to ensure forward/backward compatibility.
     759              :     // Backward compatibility: you will get a JSON not containing the newly-added field.
     760              :     // Forward compatibility: a previous version of the pageserver will receive a JSON. serde::Deserialize does
     761              :     // not deny unknown fields by default so it's safe to set the field to some value, though it won't be
     762              :     // read.
     763              :     pub is_archived: Option<bool>,
     764              : }
     765              : 
     766            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
     767              : pub struct LayerMapInfo {
     768              :     pub in_memory_layers: Vec<InMemoryLayerInfo>,
     769              :     pub historic_layers: Vec<HistoricLayerInfo>,
     770              : }
     771              : 
     772              : /// The residence status of a layer
     773            0 : #[derive(Debug, Clone, Copy, Serialize, Deserialize)]
     774              : pub enum LayerResidenceStatus {
     775              :     /// Residence status for a layer file that exists locally.
     776              :     /// It may also exist on the remote, we don't care here.
     777              :     Resident,
     778              :     /// Residence status for a layer file that only exists on the remote.
     779              :     Evicted,
     780              : }
     781              : 
     782              : #[serde_as]
     783            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
     784              : pub struct LayerAccessStats {
     785              :     #[serde_as(as = "serde_with::TimestampMilliSeconds")]
     786              :     pub access_time: SystemTime,
     787              : 
     788              :     #[serde_as(as = "serde_with::TimestampMilliSeconds")]
     789              :     pub residence_time: SystemTime,
     790              : 
     791              :     pub visible: bool,
     792              : }
     793              : 
     794            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
     795              : #[serde(tag = "kind")]
     796              : pub enum InMemoryLayerInfo {
     797              :     Open { lsn_start: Lsn },
     798              :     Frozen { lsn_start: Lsn, lsn_end: Lsn },
     799              : }
     800              : 
     801            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
     802              : #[serde(tag = "kind")]
     803              : pub enum HistoricLayerInfo {
     804              :     Delta {
     805              :         layer_file_name: String,
     806              :         layer_file_size: u64,
     807              : 
     808              :         lsn_start: Lsn,
     809              :         lsn_end: Lsn,
     810              :         remote: bool,
     811              :         access_stats: LayerAccessStats,
     812              : 
     813              :         l0: bool,
     814              :     },
     815              :     Image {
     816              :         layer_file_name: String,
     817              :         layer_file_size: u64,
     818              : 
     819              :         lsn_start: Lsn,
     820              :         remote: bool,
     821              :         access_stats: LayerAccessStats,
     822              :     },
     823              : }
     824              : 
     825              : impl HistoricLayerInfo {
     826            0 :     pub fn layer_file_name(&self) -> &str {
     827            0 :         match self {
     828              :             HistoricLayerInfo::Delta {
     829            0 :                 layer_file_name, ..
     830            0 :             } => layer_file_name,
     831              :             HistoricLayerInfo::Image {
     832            0 :                 layer_file_name, ..
     833            0 :             } => layer_file_name,
     834              :         }
     835            0 :     }
     836            0 :     pub fn is_remote(&self) -> bool {
     837            0 :         match self {
     838            0 :             HistoricLayerInfo::Delta { remote, .. } => *remote,
     839            0 :             HistoricLayerInfo::Image { remote, .. } => *remote,
     840              :         }
     841            0 :     }
     842            0 :     pub fn set_remote(&mut self, value: bool) {
     843            0 :         let field = match self {
     844            0 :             HistoricLayerInfo::Delta { remote, .. } => remote,
     845            0 :             HistoricLayerInfo::Image { remote, .. } => remote,
     846              :         };
     847            0 :         *field = value;
     848            0 :     }
     849            0 :     pub fn layer_file_size(&self) -> u64 {
     850            0 :         match self {
     851              :             HistoricLayerInfo::Delta {
     852            0 :                 layer_file_size, ..
     853            0 :             } => *layer_file_size,
     854              :             HistoricLayerInfo::Image {
     855            0 :                 layer_file_size, ..
     856            0 :             } => *layer_file_size,
     857              :         }
     858            0 :     }
     859              : }
     860              : 
     861            0 : #[derive(Debug, Serialize, Deserialize)]
     862              : pub struct DownloadRemoteLayersTaskSpawnRequest {
     863              :     pub max_concurrent_downloads: NonZeroUsize,
     864              : }
     865              : 
     866            0 : #[derive(Debug, Serialize, Deserialize)]
     867              : pub struct IngestAuxFilesRequest {
     868              :     pub aux_files: HashMap<String, String>,
     869              : }
     870              : 
     871            0 : #[derive(Debug, Serialize, Deserialize)]
     872              : pub struct ListAuxFilesRequest {
     873              :     pub lsn: Lsn,
     874              : }
     875              : 
     876            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
     877              : pub struct DownloadRemoteLayersTaskInfo {
     878              :     pub task_id: String,
     879              :     pub state: DownloadRemoteLayersTaskState,
     880              :     pub total_layer_count: u64,         // stable once `completed`
     881              :     pub successful_download_count: u64, // stable once `completed`
     882              :     pub failed_download_count: u64,     // stable once `completed`
     883              : }
     884              : 
     885            0 : #[derive(Debug, Serialize, Deserialize, Clone)]
     886              : pub enum DownloadRemoteLayersTaskState {
     887              :     Running,
     888              :     Completed,
     889              :     ShutDown,
     890              : }
     891              : 
     892            0 : #[derive(Debug, Serialize, Deserialize)]
     893              : pub struct TimelineGcRequest {
     894              :     pub gc_horizon: Option<u64>,
     895              : }
     896              : 
     897            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
     898              : pub struct WalRedoManagerProcessStatus {
     899              :     pub pid: u32,
     900              : }
     901              : 
     902            0 : #[derive(Debug, Clone, Serialize, Deserialize)]
     903              : pub struct WalRedoManagerStatus {
     904              :     pub last_redo_at: Option<chrono::DateTime<chrono::Utc>>,
     905              :     pub process: Option<WalRedoManagerProcessStatus>,
     906              : }
     907              : 
     908              : /// The progress of a secondary tenant.
     909              : ///
     910              : /// It is mostly useful when doing a long running download: e.g. initiating
     911              : /// a download job, timing out while waiting for it to run, and then inspecting this status to understand
     912              : /// what's happening.
     913            0 : #[derive(Default, Debug, Serialize, Deserialize, Clone)]
     914              : pub struct SecondaryProgress {
     915              :     /// The remote storage LastModified time of the heatmap object we last downloaded.
     916              :     pub heatmap_mtime: Option<serde_system_time::SystemTime>,
     917              : 
     918              :     /// The number of layers currently on-disk
     919              :     pub layers_downloaded: usize,
     920              :     /// The number of layers in the most recently seen heatmap
     921              :     pub layers_total: usize,
     922              : 
     923              :     /// The number of layer bytes currently on-disk
     924              :     pub bytes_downloaded: u64,
     925              :     /// The number of layer bytes in the most recently seen heatmap
     926              :     pub bytes_total: u64,
     927              : }
     928              : 
     929            0 : #[derive(Serialize, Deserialize, Debug)]
     930              : pub struct TenantScanRemoteStorageShard {
     931              :     pub tenant_shard_id: TenantShardId,
     932              :     pub generation: Option<u32>,
     933              : }
     934              : 
     935            0 : #[derive(Serialize, Deserialize, Debug, Default)]
     936              : pub struct TenantScanRemoteStorageResponse {
     937              :     pub shards: Vec<TenantScanRemoteStorageShard>,
     938              : }
     939              : 
     940            0 : #[derive(Serialize, Deserialize, Debug, Clone)]
     941              : #[serde(rename_all = "snake_case")]
     942              : pub enum TenantSorting {
     943              :     ResidentSize,
     944              :     MaxLogicalSize,
     945              : }
     946              : 
     947              : impl Default for TenantSorting {
     948            0 :     fn default() -> Self {
     949            0 :         Self::ResidentSize
     950            0 :     }
     951              : }
     952              : 
     953            0 : #[derive(Serialize, Deserialize, Debug, Clone)]
     954              : pub struct TopTenantShardsRequest {
     955              :     // How would you like to sort the tenants?
     956              :     pub order_by: TenantSorting,
     957              : 
     958              :     // How many results?
     959              :     pub limit: usize,
     960              : 
     961              :     // Omit tenants with more than this many shards (e.g. if this is the max number of shards
     962              :     // that the caller would ever split to)
     963              :     pub where_shards_lt: Option<ShardCount>,
     964              : 
     965              :     // Omit tenants where the ordering metric is less than this (this is an optimization to
     966              :     // let us quickly exclude numerous tiny shards)
     967              :     pub where_gt: Option<u64>,
     968              : }
     969              : 
     970            0 : #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
     971              : pub struct TopTenantShardItem {
     972              :     pub id: TenantShardId,
     973              : 
     974              :     /// Total size of layers on local disk for all timelines in this tenant
     975              :     pub resident_size: u64,
     976              : 
     977              :     /// Total size of layers in remote storage for all timelines in this tenant
     978              :     pub physical_size: u64,
     979              : 
     980              :     /// The largest logical size of a timeline within this tenant
     981              :     pub max_logical_size: u64,
     982              : }
     983              : 
     984            0 : #[derive(Serialize, Deserialize, Debug, Default)]
     985              : pub struct TopTenantShardsResponse {
     986              :     pub shards: Vec<TopTenantShardItem>,
     987              : }
     988              : 
     989              : pub mod virtual_file {
     990              :     #[derive(
     991              :         Copy,
     992              :         Clone,
     993              :         PartialEq,
     994              :         Eq,
     995              :         Hash,
     996          198 :         strum_macros::EnumString,
     997            0 :         strum_macros::Display,
     998            0 :         serde_with::DeserializeFromStr,
     999              :         serde_with::SerializeDisplay,
    1000              :         Debug,
    1001              :     )]
    1002              :     #[strum(serialize_all = "kebab-case")]
    1003              :     pub enum IoEngineKind {
    1004              :         StdFs,
    1005              :         #[cfg(target_os = "linux")]
    1006              :         TokioEpollUring,
    1007              :     }
    1008              : 
    1009              :     /// Direct IO modes for a pageserver.
    1010              :     #[derive(
    1011              :         Copy,
    1012              :         Clone,
    1013              :         PartialEq,
    1014              :         Eq,
    1015              :         Hash,
    1016            0 :         strum_macros::EnumString,
    1017            0 :         strum_macros::Display,
    1018            0 :         serde_with::DeserializeFromStr,
    1019              :         serde_with::SerializeDisplay,
    1020              :         Debug,
    1021              :     )]
    1022              :     #[strum(serialize_all = "kebab-case")]
    1023              :     #[repr(u8)]
    1024              :     pub enum IoMode {
    1025              :         /// Uses buffered IO.
    1026              :         Buffered,
    1027              :         /// Uses direct IO, error out if the operation fails.
    1028              :         #[cfg(target_os = "linux")]
    1029              :         Direct,
    1030              :     }
    1031              : 
    1032              :     impl IoMode {
    1033          204 :         pub const fn preferred() -> Self {
    1034          204 :             Self::Buffered
    1035          204 :         }
    1036              :     }
    1037              : 
    1038              :     impl TryFrom<u8> for IoMode {
    1039              :         type Error = u8;
    1040              : 
    1041         1148 :         fn try_from(value: u8) -> Result<Self, Self::Error> {
    1042         1148 :             Ok(match value {
    1043         1148 :                 v if v == (IoMode::Buffered as u8) => IoMode::Buffered,
    1044              :                 #[cfg(target_os = "linux")]
    1045            0 :                 v if v == (IoMode::Direct as u8) => IoMode::Direct,
    1046            0 :                 x => return Err(x),
    1047              :             })
    1048         1148 :         }
    1049              :     }
    1050              : }
    1051              : 
    1052              : // Wrapped in libpq CopyData
    1053              : #[derive(PartialEq, Eq, Debug)]
    1054              : pub enum PagestreamFeMessage {
    1055              :     Exists(PagestreamExistsRequest),
    1056              :     Nblocks(PagestreamNblocksRequest),
    1057              :     GetPage(PagestreamGetPageRequest),
    1058              :     DbSize(PagestreamDbSizeRequest),
    1059              :     GetSlruSegment(PagestreamGetSlruSegmentRequest),
    1060              : }
    1061              : 
    1062              : // Wrapped in libpq CopyData
    1063            0 : #[derive(strum_macros::EnumProperty)]
    1064              : pub enum PagestreamBeMessage {
    1065              :     Exists(PagestreamExistsResponse),
    1066              :     Nblocks(PagestreamNblocksResponse),
    1067              :     GetPage(PagestreamGetPageResponse),
    1068              :     Error(PagestreamErrorResponse),
    1069              :     DbSize(PagestreamDbSizeResponse),
    1070              :     GetSlruSegment(PagestreamGetSlruSegmentResponse),
    1071              : }
    1072              : 
    1073              : // Keep in sync with `pagestore_client.h`
    1074              : #[repr(u8)]
    1075              : enum PagestreamBeMessageTag {
    1076              :     Exists = 100,
    1077              :     Nblocks = 101,
    1078              :     GetPage = 102,
    1079              :     Error = 103,
    1080              :     DbSize = 104,
    1081              :     GetSlruSegment = 105,
    1082              : }
    1083              : impl TryFrom<u8> for PagestreamBeMessageTag {
    1084              :     type Error = u8;
    1085            0 :     fn try_from(value: u8) -> Result<Self, u8> {
    1086            0 :         match value {
    1087            0 :             100 => Ok(PagestreamBeMessageTag::Exists),
    1088            0 :             101 => Ok(PagestreamBeMessageTag::Nblocks),
    1089            0 :             102 => Ok(PagestreamBeMessageTag::GetPage),
    1090            0 :             103 => Ok(PagestreamBeMessageTag::Error),
    1091            0 :             104 => Ok(PagestreamBeMessageTag::DbSize),
    1092            0 :             105 => Ok(PagestreamBeMessageTag::GetSlruSegment),
    1093            0 :             _ => Err(value),
    1094              :         }
    1095            0 :     }
    1096              : }
    1097              : 
    1098              : // A GetPage request contains two LSN values:
    1099              : //
    1100              : // request_lsn: Get the page version at this point in time.  Lsn::Max is a special value that means
    1101              : // "get the latest version present". It's used by the primary server, which knows that no one else
    1102              : // is writing WAL. 'not_modified_since' must be set to a proper value even if request_lsn is
    1103              : // Lsn::Max. Standby servers use the current replay LSN as the request LSN.
    1104              : //
    1105              : // not_modified_since: Hint to the pageserver that the client knows that the page has not been
    1106              : // modified between 'not_modified_since' and the request LSN. It's always correct to set
    1107              : // 'not_modified_since equal' to 'request_lsn' (unless Lsn::Max is used as the 'request_lsn'), but
    1108              : // passing an earlier LSN can speed up the request, by allowing the pageserver to process the
    1109              : // request without waiting for 'request_lsn' to arrive.
    1110              : //
    1111              : // The now-defunct V1 interface contained only one LSN, and a boolean 'latest' flag. The V1 interface was
    1112              : // sufficient for the primary; the 'lsn' was equivalent to the 'not_modified_since' value, and
    1113              : // 'latest' was set to true. The V2 interface was added because there was no correct way for a
    1114              : // standby to request a page at a particular non-latest LSN, and also include the
    1115              : // 'not_modified_since' hint. That led to an awkward choice of either using an old LSN in the
    1116              : // request, if the standby knows that the page hasn't been modified since, and risk getting an error
    1117              : // if that LSN has fallen behind the GC horizon, or requesting the current replay LSN, which could
    1118              : // require the pageserver unnecessarily to wait for the WAL to arrive up to that point. The new V2
    1119              : // interface allows sending both LSNs, and let the pageserver do the right thing. There was no
    1120              : // difference in the responses between V1 and V2.
    1121              : //
    1122              : #[derive(Clone, Copy)]
    1123              : pub enum PagestreamProtocolVersion {
    1124              :     V2,
    1125              : }
    1126              : 
    1127              : #[derive(Debug, PartialEq, Eq)]
    1128              : pub struct PagestreamExistsRequest {
    1129              :     pub request_lsn: Lsn,
    1130              :     pub not_modified_since: Lsn,
    1131              :     pub rel: RelTag,
    1132              : }
    1133              : 
    1134              : #[derive(Debug, PartialEq, Eq)]
    1135              : pub struct PagestreamNblocksRequest {
    1136              :     pub request_lsn: Lsn,
    1137              :     pub not_modified_since: Lsn,
    1138              :     pub rel: RelTag,
    1139              : }
    1140              : 
    1141              : #[derive(Debug, PartialEq, Eq)]
    1142              : pub struct PagestreamGetPageRequest {
    1143              :     pub request_lsn: Lsn,
    1144              :     pub not_modified_since: Lsn,
    1145              :     pub rel: RelTag,
    1146              :     pub blkno: u32,
    1147              : }
    1148              : 
    1149              : #[derive(Debug, PartialEq, Eq)]
    1150              : pub struct PagestreamDbSizeRequest {
    1151              :     pub request_lsn: Lsn,
    1152              :     pub not_modified_since: Lsn,
    1153              :     pub dbnode: u32,
    1154              : }
    1155              : 
    1156              : #[derive(Debug, PartialEq, Eq)]
    1157              : pub struct PagestreamGetSlruSegmentRequest {
    1158              :     pub request_lsn: Lsn,
    1159              :     pub not_modified_since: Lsn,
    1160              :     pub kind: u8,
    1161              :     pub segno: u32,
    1162              : }
    1163              : 
    1164              : #[derive(Debug)]
    1165              : pub struct PagestreamExistsResponse {
    1166              :     pub exists: bool,
    1167              : }
    1168              : 
    1169              : #[derive(Debug)]
    1170              : pub struct PagestreamNblocksResponse {
    1171              :     pub n_blocks: u32,
    1172              : }
    1173              : 
    1174              : #[derive(Debug)]
    1175              : pub struct PagestreamGetPageResponse {
    1176              :     pub page: Bytes,
    1177              : }
    1178              : 
    1179              : #[derive(Debug)]
    1180              : pub struct PagestreamGetSlruSegmentResponse {
    1181              :     pub segment: Bytes,
    1182              : }
    1183              : 
    1184              : #[derive(Debug)]
    1185              : pub struct PagestreamErrorResponse {
    1186              :     pub message: String,
    1187              : }
    1188              : 
    1189              : #[derive(Debug)]
    1190              : pub struct PagestreamDbSizeResponse {
    1191              :     pub db_size: i64,
    1192              : }
    1193              : 
    1194              : // This is a cut-down version of TenantHistorySize from the pageserver crate, omitting fields
    1195              : // that require pageserver-internal types.  It is sufficient to get the total size.
    1196            0 : #[derive(Serialize, Deserialize, Debug)]
    1197              : pub struct TenantHistorySize {
    1198              :     pub id: TenantId,
    1199              :     /// Size is a mixture of WAL and logical size, so the unit is bytes.
    1200              :     ///
    1201              :     /// Will be none if `?inputs_only=true` was given.
    1202              :     pub size: Option<u64>,
    1203              : }
    1204              : 
    1205              : impl PagestreamFeMessage {
    1206              :     /// Serialize a compute -> pageserver message. This is currently only used in testing
    1207              :     /// tools. Always uses protocol version 2.
    1208            4 :     pub fn serialize(&self) -> Bytes {
    1209            4 :         let mut bytes = BytesMut::new();
    1210            4 : 
    1211            4 :         match self {
    1212            1 :             Self::Exists(req) => {
    1213            1 :                 bytes.put_u8(0);
    1214            1 :                 bytes.put_u64(req.request_lsn.0);
    1215            1 :                 bytes.put_u64(req.not_modified_since.0);
    1216            1 :                 bytes.put_u32(req.rel.spcnode);
    1217            1 :                 bytes.put_u32(req.rel.dbnode);
    1218            1 :                 bytes.put_u32(req.rel.relnode);
    1219            1 :                 bytes.put_u8(req.rel.forknum);
    1220            1 :             }
    1221              : 
    1222            1 :             Self::Nblocks(req) => {
    1223            1 :                 bytes.put_u8(1);
    1224            1 :                 bytes.put_u64(req.request_lsn.0);
    1225            1 :                 bytes.put_u64(req.not_modified_since.0);
    1226            1 :                 bytes.put_u32(req.rel.spcnode);
    1227            1 :                 bytes.put_u32(req.rel.dbnode);
    1228            1 :                 bytes.put_u32(req.rel.relnode);
    1229            1 :                 bytes.put_u8(req.rel.forknum);
    1230            1 :             }
    1231              : 
    1232            1 :             Self::GetPage(req) => {
    1233            1 :                 bytes.put_u8(2);
    1234            1 :                 bytes.put_u64(req.request_lsn.0);
    1235            1 :                 bytes.put_u64(req.not_modified_since.0);
    1236            1 :                 bytes.put_u32(req.rel.spcnode);
    1237            1 :                 bytes.put_u32(req.rel.dbnode);
    1238            1 :                 bytes.put_u32(req.rel.relnode);
    1239            1 :                 bytes.put_u8(req.rel.forknum);
    1240            1 :                 bytes.put_u32(req.blkno);
    1241            1 :             }
    1242              : 
    1243            1 :             Self::DbSize(req) => {
    1244            1 :                 bytes.put_u8(3);
    1245            1 :                 bytes.put_u64(req.request_lsn.0);
    1246            1 :                 bytes.put_u64(req.not_modified_since.0);
    1247            1 :                 bytes.put_u32(req.dbnode);
    1248            1 :             }
    1249              : 
    1250            0 :             Self::GetSlruSegment(req) => {
    1251            0 :                 bytes.put_u8(4);
    1252            0 :                 bytes.put_u64(req.request_lsn.0);
    1253            0 :                 bytes.put_u64(req.not_modified_since.0);
    1254            0 :                 bytes.put_u8(req.kind);
    1255            0 :                 bytes.put_u32(req.segno);
    1256            0 :             }
    1257              :         }
    1258              : 
    1259            4 :         bytes.into()
    1260            4 :     }
    1261              : 
    1262            4 :     pub fn parse<R: std::io::Read>(body: &mut R) -> anyhow::Result<PagestreamFeMessage> {
    1263              :         // these correspond to the NeonMessageTag enum in pagestore_client.h
    1264              :         //
    1265              :         // TODO: consider using protobuf or serde bincode for less error prone
    1266              :         // serialization.
    1267            4 :         let msg_tag = body.read_u8()?;
    1268              : 
    1269              :         // these two fields are the same for every request type
    1270            4 :         let request_lsn = Lsn::from(body.read_u64::<BigEndian>()?);
    1271            4 :         let not_modified_since = Lsn::from(body.read_u64::<BigEndian>()?);
    1272              : 
    1273            4 :         match msg_tag {
    1274              :             0 => Ok(PagestreamFeMessage::Exists(PagestreamExistsRequest {
    1275            1 :                 request_lsn,
    1276            1 :                 not_modified_since,
    1277            1 :                 rel: RelTag {
    1278            1 :                     spcnode: body.read_u32::<BigEndian>()?,
    1279            1 :                     dbnode: body.read_u32::<BigEndian>()?,
    1280            1 :                     relnode: body.read_u32::<BigEndian>()?,
    1281            1 :                     forknum: body.read_u8()?,
    1282              :                 },
    1283              :             })),
    1284              :             1 => Ok(PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
    1285            1 :                 request_lsn,
    1286            1 :                 not_modified_since,
    1287            1 :                 rel: RelTag {
    1288            1 :                     spcnode: body.read_u32::<BigEndian>()?,
    1289            1 :                     dbnode: body.read_u32::<BigEndian>()?,
    1290            1 :                     relnode: body.read_u32::<BigEndian>()?,
    1291            1 :                     forknum: body.read_u8()?,
    1292              :                 },
    1293              :             })),
    1294              :             2 => Ok(PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
    1295            1 :                 request_lsn,
    1296            1 :                 not_modified_since,
    1297            1 :                 rel: RelTag {
    1298            1 :                     spcnode: body.read_u32::<BigEndian>()?,
    1299            1 :                     dbnode: body.read_u32::<BigEndian>()?,
    1300            1 :                     relnode: body.read_u32::<BigEndian>()?,
    1301            1 :                     forknum: body.read_u8()?,
    1302              :                 },
    1303            1 :                 blkno: body.read_u32::<BigEndian>()?,
    1304              :             })),
    1305              :             3 => Ok(PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
    1306            1 :                 request_lsn,
    1307            1 :                 not_modified_since,
    1308            1 :                 dbnode: body.read_u32::<BigEndian>()?,
    1309              :             })),
    1310              :             4 => Ok(PagestreamFeMessage::GetSlruSegment(
    1311              :                 PagestreamGetSlruSegmentRequest {
    1312            0 :                     request_lsn,
    1313            0 :                     not_modified_since,
    1314            0 :                     kind: body.read_u8()?,
    1315            0 :                     segno: body.read_u32::<BigEndian>()?,
    1316              :                 },
    1317              :             )),
    1318            0 :             _ => bail!("unknown smgr message tag: {:?}", msg_tag),
    1319              :         }
    1320            4 :     }
    1321              : }
    1322              : 
    1323              : impl PagestreamBeMessage {
    1324            0 :     pub fn serialize(&self) -> Bytes {
    1325            0 :         let mut bytes = BytesMut::new();
    1326              : 
    1327              :         use PagestreamBeMessageTag as Tag;
    1328            0 :         match self {
    1329            0 :             Self::Exists(resp) => {
    1330            0 :                 bytes.put_u8(Tag::Exists as u8);
    1331            0 :                 bytes.put_u8(resp.exists as u8);
    1332            0 :             }
    1333              : 
    1334            0 :             Self::Nblocks(resp) => {
    1335            0 :                 bytes.put_u8(Tag::Nblocks as u8);
    1336            0 :                 bytes.put_u32(resp.n_blocks);
    1337            0 :             }
    1338              : 
    1339            0 :             Self::GetPage(resp) => {
    1340            0 :                 bytes.put_u8(Tag::GetPage as u8);
    1341            0 :                 bytes.put(&resp.page[..]);
    1342            0 :             }
    1343              : 
    1344            0 :             Self::Error(resp) => {
    1345            0 :                 bytes.put_u8(Tag::Error as u8);
    1346            0 :                 bytes.put(resp.message.as_bytes());
    1347            0 :                 bytes.put_u8(0); // null terminator
    1348            0 :             }
    1349            0 :             Self::DbSize(resp) => {
    1350            0 :                 bytes.put_u8(Tag::DbSize as u8);
    1351            0 :                 bytes.put_i64(resp.db_size);
    1352            0 :             }
    1353              : 
    1354            0 :             Self::GetSlruSegment(resp) => {
    1355            0 :                 bytes.put_u8(Tag::GetSlruSegment as u8);
    1356            0 :                 bytes.put_u32((resp.segment.len() / BLCKSZ as usize) as u32);
    1357            0 :                 bytes.put(&resp.segment[..]);
    1358            0 :             }
    1359              :         }
    1360              : 
    1361            0 :         bytes.into()
    1362            0 :     }
    1363              : 
    1364            0 :     pub fn deserialize(buf: Bytes) -> anyhow::Result<Self> {
    1365            0 :         let mut buf = buf.reader();
    1366            0 :         let msg_tag = buf.read_u8()?;
    1367              : 
    1368              :         use PagestreamBeMessageTag as Tag;
    1369            0 :         let ok =
    1370            0 :             match Tag::try_from(msg_tag).map_err(|tag: u8| anyhow::anyhow!("invalid tag {tag}"))? {
    1371              :                 Tag::Exists => {
    1372            0 :                     let exists = buf.read_u8()?;
    1373            0 :                     Self::Exists(PagestreamExistsResponse {
    1374            0 :                         exists: exists != 0,
    1375            0 :                     })
    1376              :                 }
    1377              :                 Tag::Nblocks => {
    1378            0 :                     let n_blocks = buf.read_u32::<BigEndian>()?;
    1379            0 :                     Self::Nblocks(PagestreamNblocksResponse { n_blocks })
    1380              :                 }
    1381              :                 Tag::GetPage => {
    1382            0 :                     let mut page = vec![0; 8192]; // TODO: use MaybeUninit
    1383            0 :                     buf.read_exact(&mut page)?;
    1384            0 :                     PagestreamBeMessage::GetPage(PagestreamGetPageResponse { page: page.into() })
    1385              :                 }
    1386              :                 Tag::Error => {
    1387            0 :                     let mut msg = Vec::new();
    1388            0 :                     buf.read_until(0, &mut msg)?;
    1389            0 :                     let cstring = std::ffi::CString::from_vec_with_nul(msg)?;
    1390            0 :                     let rust_str = cstring.to_str()?;
    1391            0 :                     PagestreamBeMessage::Error(PagestreamErrorResponse {
    1392            0 :                         message: rust_str.to_owned(),
    1393            0 :                     })
    1394              :                 }
    1395              :                 Tag::DbSize => {
    1396            0 :                     let db_size = buf.read_i64::<BigEndian>()?;
    1397            0 :                     Self::DbSize(PagestreamDbSizeResponse { db_size })
    1398              :                 }
    1399              :                 Tag::GetSlruSegment => {
    1400            0 :                     let n_blocks = buf.read_u32::<BigEndian>()?;
    1401            0 :                     let mut segment = vec![0; n_blocks as usize * BLCKSZ as usize];
    1402            0 :                     buf.read_exact(&mut segment)?;
    1403            0 :                     Self::GetSlruSegment(PagestreamGetSlruSegmentResponse {
    1404            0 :                         segment: segment.into(),
    1405            0 :                     })
    1406              :                 }
    1407              :             };
    1408            0 :         let remaining = buf.into_inner();
    1409            0 :         if !remaining.is_empty() {
    1410            0 :             anyhow::bail!(
    1411            0 :                 "remaining bytes in msg with tag={msg_tag}: {}",
    1412            0 :                 remaining.len()
    1413            0 :             );
    1414            0 :         }
    1415            0 :         Ok(ok)
    1416            0 :     }
    1417              : 
    1418            0 :     pub fn kind(&self) -> &'static str {
    1419            0 :         match self {
    1420            0 :             Self::Exists(_) => "Exists",
    1421            0 :             Self::Nblocks(_) => "Nblocks",
    1422            0 :             Self::GetPage(_) => "GetPage",
    1423            0 :             Self::Error(_) => "Error",
    1424            0 :             Self::DbSize(_) => "DbSize",
    1425            0 :             Self::GetSlruSegment(_) => "GetSlruSegment",
    1426              :         }
    1427            0 :     }
    1428              : }
    1429              : 
    1430              : #[cfg(test)]
    1431              : mod tests {
    1432              :     use serde_json::json;
    1433              :     use std::str::FromStr;
    1434              : 
    1435              :     use super::*;
    1436              : 
    1437              :     #[test]
    1438            1 :     fn test_pagestream() {
    1439            1 :         // Test serialization/deserialization of PagestreamFeMessage
    1440            1 :         let messages = vec![
    1441            1 :             PagestreamFeMessage::Exists(PagestreamExistsRequest {
    1442            1 :                 request_lsn: Lsn(4),
    1443            1 :                 not_modified_since: Lsn(3),
    1444            1 :                 rel: RelTag {
    1445            1 :                     forknum: 1,
    1446            1 :                     spcnode: 2,
    1447            1 :                     dbnode: 3,
    1448            1 :                     relnode: 4,
    1449            1 :                 },
    1450            1 :             }),
    1451            1 :             PagestreamFeMessage::Nblocks(PagestreamNblocksRequest {
    1452            1 :                 request_lsn: Lsn(4),
    1453            1 :                 not_modified_since: Lsn(4),
    1454            1 :                 rel: RelTag {
    1455            1 :                     forknum: 1,
    1456            1 :                     spcnode: 2,
    1457            1 :                     dbnode: 3,
    1458            1 :                     relnode: 4,
    1459            1 :                 },
    1460            1 :             }),
    1461            1 :             PagestreamFeMessage::GetPage(PagestreamGetPageRequest {
    1462            1 :                 request_lsn: Lsn(4),
    1463            1 :                 not_modified_since: Lsn(3),
    1464            1 :                 rel: RelTag {
    1465            1 :                     forknum: 1,
    1466            1 :                     spcnode: 2,
    1467            1 :                     dbnode: 3,
    1468            1 :                     relnode: 4,
    1469            1 :                 },
    1470            1 :                 blkno: 7,
    1471            1 :             }),
    1472            1 :             PagestreamFeMessage::DbSize(PagestreamDbSizeRequest {
    1473            1 :                 request_lsn: Lsn(4),
    1474            1 :                 not_modified_since: Lsn(3),
    1475            1 :                 dbnode: 7,
    1476            1 :             }),
    1477            1 :         ];
    1478            5 :         for msg in messages {
    1479            4 :             let bytes = msg.serialize();
    1480            4 :             let reconstructed = PagestreamFeMessage::parse(&mut bytes.reader()).unwrap();
    1481            4 :             assert!(msg == reconstructed);
    1482              :         }
    1483            1 :     }
    1484              : 
    1485              :     #[test]
    1486            1 :     fn test_tenantinfo_serde() {
    1487            1 :         // Test serialization/deserialization of TenantInfo
    1488            1 :         let original_active = TenantInfo {
    1489            1 :             id: TenantShardId::unsharded(TenantId::generate()),
    1490            1 :             state: TenantState::Active,
    1491            1 :             current_physical_size: Some(42),
    1492            1 :             attachment_status: TenantAttachmentStatus::Attached,
    1493            1 :             generation: 1,
    1494            1 :             gc_blocking: None,
    1495            1 :         };
    1496            1 :         let expected_active = json!({
    1497            1 :             "id": original_active.id.to_string(),
    1498            1 :             "state": {
    1499            1 :                 "slug": "Active",
    1500            1 :             },
    1501            1 :             "current_physical_size": 42,
    1502            1 :             "attachment_status": {
    1503            1 :                 "slug":"attached",
    1504            1 :             },
    1505            1 :             "generation" : 1
    1506            1 :         });
    1507            1 : 
    1508            1 :         let original_broken = TenantInfo {
    1509            1 :             id: TenantShardId::unsharded(TenantId::generate()),
    1510            1 :             state: TenantState::Broken {
    1511            1 :                 reason: "reason".into(),
    1512            1 :                 backtrace: "backtrace info".into(),
    1513            1 :             },
    1514            1 :             current_physical_size: Some(42),
    1515            1 :             attachment_status: TenantAttachmentStatus::Attached,
    1516            1 :             generation: 1,
    1517            1 :             gc_blocking: None,
    1518            1 :         };
    1519            1 :         let expected_broken = json!({
    1520            1 :             "id": original_broken.id.to_string(),
    1521            1 :             "state": {
    1522            1 :                 "slug": "Broken",
    1523            1 :                 "data": {
    1524            1 :                     "backtrace": "backtrace info",
    1525            1 :                     "reason": "reason",
    1526            1 :                 }
    1527            1 :             },
    1528            1 :             "current_physical_size": 42,
    1529            1 :             "attachment_status": {
    1530            1 :                 "slug":"attached",
    1531            1 :             },
    1532            1 :             "generation" : 1
    1533            1 :         });
    1534            1 : 
    1535            1 :         assert_eq!(
    1536            1 :             serde_json::to_value(&original_active).unwrap(),
    1537            1 :             expected_active
    1538            1 :         );
    1539              : 
    1540            1 :         assert_eq!(
    1541            1 :             serde_json::to_value(&original_broken).unwrap(),
    1542            1 :             expected_broken
    1543            1 :         );
    1544            1 :         assert!(format!("{:?}", &original_broken.state).contains("reason"));
    1545            1 :         assert!(format!("{:?}", &original_broken.state).contains("backtrace info"));
    1546            1 :     }
    1547              : 
    1548              :     #[test]
    1549            1 :     fn test_reject_unknown_field() {
    1550            1 :         let id = TenantId::generate();
    1551            1 :         let config_request = json!({
    1552            1 :             "tenant_id": id.to_string(),
    1553            1 :             "unknown_field": "unknown_value".to_string(),
    1554            1 :         });
    1555            1 :         let err = serde_json::from_value::<TenantConfigRequest>(config_request).unwrap_err();
    1556            1 :         assert!(
    1557            1 :             err.to_string().contains("unknown field `unknown_field`"),
    1558            0 :             "expect unknown field `unknown_field` error, got: {}",
    1559              :             err
    1560              :         );
    1561            1 :     }
    1562              : 
    1563              :     #[test]
    1564            1 :     fn tenantstatus_activating_serde() {
    1565            1 :         let states = [TenantState::Activating(ActivatingFrom::Attaching)];
    1566            1 :         let expected = "[{\"slug\":\"Activating\",\"data\":\"Attaching\"}]";
    1567            1 : 
    1568            1 :         let actual = serde_json::to_string(&states).unwrap();
    1569            1 : 
    1570            1 :         assert_eq!(actual, expected);
    1571              : 
    1572            1 :         let parsed = serde_json::from_str::<Vec<TenantState>>(&actual).unwrap();
    1573            1 : 
    1574            1 :         assert_eq!(states.as_slice(), &parsed);
    1575            1 :     }
    1576              : 
    1577              :     #[test]
    1578            1 :     fn tenantstatus_activating_strum() {
    1579            1 :         // tests added, because we use these for metrics
    1580            1 :         let examples = [
    1581            1 :             (line!(), TenantState::Attaching, "Attaching"),
    1582            1 :             (
    1583            1 :                 line!(),
    1584            1 :                 TenantState::Activating(ActivatingFrom::Attaching),
    1585            1 :                 "Activating",
    1586            1 :             ),
    1587            1 :             (line!(), TenantState::Active, "Active"),
    1588            1 :             (
    1589            1 :                 line!(),
    1590            1 :                 TenantState::Stopping {
    1591            1 :                     progress: utils::completion::Barrier::default(),
    1592            1 :                 },
    1593            1 :                 "Stopping",
    1594            1 :             ),
    1595            1 :             (
    1596            1 :                 line!(),
    1597            1 :                 TenantState::Broken {
    1598            1 :                     reason: "Example".into(),
    1599            1 :                     backtrace: "Looooong backtrace".into(),
    1600            1 :                 },
    1601            1 :                 "Broken",
    1602            1 :             ),
    1603            1 :         ];
    1604              : 
    1605            6 :         for (line, rendered, expected) in examples {
    1606            5 :             let actual: &'static str = rendered.into();
    1607            5 :             assert_eq!(actual, expected, "example on {line}");
    1608              :         }
    1609            1 :     }
    1610              : 
    1611              :     #[test]
    1612            1 :     fn test_aux_file_migration_path() {
    1613            1 :         assert!(AuxFilePolicy::is_valid_migration_path(
    1614            1 :             None,
    1615            1 :             AuxFilePolicy::V1
    1616            1 :         ));
    1617            1 :         assert!(AuxFilePolicy::is_valid_migration_path(
    1618            1 :             None,
    1619            1 :             AuxFilePolicy::V2
    1620            1 :         ));
    1621            1 :         assert!(AuxFilePolicy::is_valid_migration_path(
    1622            1 :             None,
    1623            1 :             AuxFilePolicy::CrossValidation
    1624            1 :         ));
    1625              :         // Self-migration is not a valid migration path, and the caller should handle it by itself.
    1626            1 :         assert!(!AuxFilePolicy::is_valid_migration_path(
    1627            1 :             Some(AuxFilePolicy::V1),
    1628            1 :             AuxFilePolicy::V1
    1629            1 :         ));
    1630            1 :         assert!(!AuxFilePolicy::is_valid_migration_path(
    1631            1 :             Some(AuxFilePolicy::V2),
    1632            1 :             AuxFilePolicy::V2
    1633            1 :         ));
    1634            1 :         assert!(!AuxFilePolicy::is_valid_migration_path(
    1635            1 :             Some(AuxFilePolicy::CrossValidation),
    1636            1 :             AuxFilePolicy::CrossValidation
    1637            1 :         ));
    1638              :         // Migrations not allowed
    1639            1 :         assert!(!AuxFilePolicy::is_valid_migration_path(
    1640            1 :             Some(AuxFilePolicy::CrossValidation),
    1641            1 :             AuxFilePolicy::V1
    1642            1 :         ));
    1643            1 :         assert!(!AuxFilePolicy::is_valid_migration_path(
    1644            1 :             Some(AuxFilePolicy::V1),
    1645            1 :             AuxFilePolicy::V2
    1646            1 :         ));
    1647            1 :         assert!(!AuxFilePolicy::is_valid_migration_path(
    1648            1 :             Some(AuxFilePolicy::V2),
    1649            1 :             AuxFilePolicy::V1
    1650            1 :         ));
    1651            1 :         assert!(!AuxFilePolicy::is_valid_migration_path(
    1652            1 :             Some(AuxFilePolicy::V2),
    1653            1 :             AuxFilePolicy::CrossValidation
    1654            1 :         ));
    1655            1 :         assert!(!AuxFilePolicy::is_valid_migration_path(
    1656            1 :             Some(AuxFilePolicy::V1),
    1657            1 :             AuxFilePolicy::CrossValidation
    1658            1 :         ));
    1659              :         // Migrations allowed
    1660            1 :         assert!(AuxFilePolicy::is_valid_migration_path(
    1661            1 :             Some(AuxFilePolicy::CrossValidation),
    1662            1 :             AuxFilePolicy::V2
    1663            1 :         ));
    1664            1 :     }
    1665              : 
    1666              :     #[test]
    1667            1 :     fn test_aux_parse() {
    1668            1 :         assert_eq!(AuxFilePolicy::from_str("V2").unwrap(), AuxFilePolicy::V2);
    1669            1 :         assert_eq!(AuxFilePolicy::from_str("v2").unwrap(), AuxFilePolicy::V2);
    1670            1 :         assert_eq!(
    1671            1 :             AuxFilePolicy::from_str("cross-validation").unwrap(),
    1672            1 :             AuxFilePolicy::CrossValidation
    1673            1 :         );
    1674            1 :     }
    1675              : 
    1676              :     #[test]
    1677            1 :     fn test_image_compression_algorithm_parsing() {
    1678              :         use ImageCompressionAlgorithm::*;
    1679            1 :         let cases = [
    1680            1 :             ("disabled", Disabled),
    1681            1 :             ("zstd", Zstd { level: None }),
    1682            1 :             ("zstd(18)", Zstd { level: Some(18) }),
    1683            1 :             ("zstd(-3)", Zstd { level: Some(-3) }),
    1684            1 :         ];
    1685              : 
    1686            5 :         for (display, expected) in cases {
    1687            4 :             assert_eq!(
    1688            4 :                 ImageCompressionAlgorithm::from_str(display).unwrap(),
    1689              :                 expected,
    1690            0 :                 "parsing works"
    1691              :             );
    1692            4 :             assert_eq!(format!("{expected}"), display, "Display FromStr roundtrip");
    1693              : 
    1694            4 :             let ser = serde_json::to_string(&expected).expect("serialization");
    1695            4 :             assert_eq!(
    1696            4 :                 serde_json::from_str::<ImageCompressionAlgorithm>(&ser).unwrap(),
    1697              :                 expected,
    1698            0 :                 "serde roundtrip"
    1699              :             );
    1700              : 
    1701            4 :             assert_eq!(
    1702            4 :                 serde_json::Value::String(display.to_string()),
    1703            4 :                 serde_json::to_value(expected).unwrap(),
    1704            0 :                 "Display is the serde serialization"
    1705              :             );
    1706              :         }
    1707            1 :     }
    1708              : }
        

Generated by: LCOV version 2.1-beta