LCOV - code coverage report
Current view: top level - libs/pageserver_api/src - models.rs (source / functions) Coverage Total Hit
Test: 83fdc07b20afb411eb00587331b88259a1ff6742.info Lines: 62.3 % 636 396
Test Date: 2024-06-20 09:39:16 Functions: 5.2 % 1060 55

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

Generated by: LCOV version 2.1-beta