LCOV - code coverage report
Current view: top level - libs/pageserver_api/src - models.rs (source / functions) Coverage Total Hit
Test: 472031e0b71f3195f7f21b1f2b20de09fd07bb56.info Lines: 51.7 % 1285 664
Test Date: 2025-05-26 10:37:33 Functions: 7.0 % 1078 75

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

Generated by: LCOV version 2.1-beta