LCOV - code coverage report
Current view: top level - pageserver/src/tenant - config.rs (source / functions) Coverage Total Hit
Test: 727bdccc1d7d53837da843959afb612f56da4e79.info Lines: 16.7 % 436 73
Test Date: 2025-01-30 15:18:43 Functions: 9.4 % 106 10

            Line data    Source code
       1              : //! Functions for handling per-tenant configuration options
       2              : //!
       3              : //! If tenant is created with --config option,
       4              : //! the tenant-specific config will be stored in tenant's directory.
       5              : //! Otherwise, global pageserver's config is used.
       6              : //!
       7              : //! If the tenant config file is corrupted, the tenant will be disabled.
       8              : //! We cannot use global or default config instead, because wrong settings
       9              : //! may lead to a data loss.
      10              : //!
      11              : pub(crate) use pageserver_api::config::TenantConfigToml as TenantConf;
      12              : use pageserver_api::models::CompactionAlgorithmSettings;
      13              : use pageserver_api::models::EvictionPolicy;
      14              : use pageserver_api::models::{self, TenantConfigPatch};
      15              : use pageserver_api::shard::{ShardCount, ShardIdentity, ShardNumber, ShardStripeSize};
      16              : use serde::de::IntoDeserializer;
      17              : use serde::{Deserialize, Serialize};
      18              : use serde_json::Value;
      19              : use std::num::NonZeroU64;
      20              : use std::time::Duration;
      21              : use utils::generation::Generation;
      22              : use utils::postgres_client::PostgresClientProtocol;
      23              : 
      24            0 : #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
      25              : pub(crate) enum AttachmentMode {
      26              :     /// Our generation is current as far as we know, and as far as we know we are the only attached
      27              :     /// pageserver.  This is the "normal" attachment mode.
      28              :     Single,
      29              :     /// Our generation number is current as far as we know, but we are advised that another
      30              :     /// pageserver is still attached, and therefore to avoid executing deletions.   This is
      31              :     /// the attachment mode of a pagesever that is the destination of a migration.
      32              :     Multi,
      33              :     /// Our generation number is superseded, or about to be superseded.  We are advised
      34              :     /// to avoid remote storage writes if possible, and to avoid sending billing data.  This
      35              :     /// is the attachment mode of a pageserver that is the origin of a migration.
      36              :     Stale,
      37              : }
      38              : 
      39            0 : #[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Eq)]
      40              : pub(crate) struct AttachedLocationConfig {
      41              :     pub(crate) generation: Generation,
      42              :     pub(crate) attach_mode: AttachmentMode,
      43              :     // TODO: add a flag to override AttachmentMode's policies under
      44              :     // disk pressure (i.e. unblock uploads under disk pressure in Stale
      45              :     // state, unblock deletions after timeout in Multi state)
      46              : }
      47              : 
      48            0 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
      49              : pub(crate) struct SecondaryLocationConfig {
      50              :     /// If true, keep the local cache warm by polling remote storage
      51              :     pub(crate) warm: bool,
      52              : }
      53              : 
      54            0 : #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
      55              : pub(crate) enum LocationMode {
      56              :     Attached(AttachedLocationConfig),
      57              :     Secondary(SecondaryLocationConfig),
      58              : }
      59              : 
      60              : /// Per-tenant, per-pageserver configuration.  All pageservers use the same TenantConf,
      61              : /// but have distinct LocationConf.
      62            0 : #[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
      63              : pub(crate) struct LocationConf {
      64              :     /// The location-specific part of the configuration, describes the operating
      65              :     /// mode of this pageserver for this tenant.
      66              :     pub(crate) mode: LocationMode,
      67              : 
      68              :     /// The detailed shard identity.  This structure is already scoped within
      69              :     /// a TenantShardId, but we need the full ShardIdentity to enable calculating
      70              :     /// key->shard mappings.
      71              :     #[serde(default = "ShardIdentity::unsharded")]
      72              :     #[serde(skip_serializing_if = "ShardIdentity::is_unsharded")]
      73              :     pub(crate) shard: ShardIdentity,
      74              : 
      75              :     /// The pan-cluster tenant configuration, the same on all locations
      76              :     pub(crate) tenant_conf: TenantConfOpt,
      77              : }
      78              : 
      79              : impl std::fmt::Debug for LocationConf {
      80            0 :     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
      81            0 :         match &self.mode {
      82            0 :             LocationMode::Attached(conf) => {
      83            0 :                 write!(
      84            0 :                     f,
      85            0 :                     "Attached {:?}, gen={:?}",
      86            0 :                     conf.attach_mode, conf.generation
      87            0 :                 )
      88              :             }
      89            0 :             LocationMode::Secondary(conf) => {
      90            0 :                 write!(f, "Secondary, warm={}", conf.warm)
      91              :             }
      92              :         }
      93            0 :     }
      94              : }
      95              : 
      96              : impl AttachedLocationConfig {
      97              :     /// Consult attachment mode to determine whether we are currently permitted
      98              :     /// to delete layers.  This is only advisory, not required for data safety.
      99              :     /// See [`AttachmentMode`] for more context.
     100         2420 :     pub(crate) fn may_delete_layers_hint(&self) -> bool {
     101         2420 :         // TODO: add an override for disk pressure in AttachedLocationConfig,
     102         2420 :         // and respect it here.
     103         2420 :         match &self.attach_mode {
     104         2420 :             AttachmentMode::Single => true,
     105              :             AttachmentMode::Multi | AttachmentMode::Stale => {
     106              :                 // In Multi mode we avoid doing deletions because some other
     107              :                 // attached pageserver might get 404 while trying to read
     108              :                 // a layer we delete which is still referenced in their metadata.
     109              :                 //
     110              :                 // In Stale mode, we avoid doing deletions because we expect
     111              :                 // that they would ultimately fail validation in the deletion
     112              :                 // queue due to our stale generation.
     113            0 :                 false
     114              :             }
     115              :         }
     116         2420 :     }
     117              : 
     118              :     /// Whether we are currently hinted that it is worthwhile to upload layers.
     119              :     /// This is only advisory, not required for data safety.
     120              :     /// See [`AttachmentMode`] for more context.
     121          912 :     pub(crate) fn may_upload_layers_hint(&self) -> bool {
     122          912 :         // TODO: add an override for disk pressure in AttachedLocationConfig,
     123          912 :         // and respect it here.
     124          912 :         match &self.attach_mode {
     125          912 :             AttachmentMode::Single | AttachmentMode::Multi => true,
     126              :             AttachmentMode::Stale => {
     127              :                 // In Stale mode, we avoid doing uploads because we expect that
     128              :                 // our replacement pageserver will already have started its own
     129              :                 // IndexPart that will never reference layers we upload: it is
     130              :                 // wasteful.
     131            0 :                 false
     132              :             }
     133              :         }
     134          912 :     }
     135              : }
     136              : 
     137              : impl LocationConf {
     138              :     /// For use when loading from a legacy configuration: presence of a tenant
     139              :     /// implies it is in AttachmentMode::Single, which used to be the only
     140              :     /// possible state.  This function should eventually be removed.
     141          440 :     pub(crate) fn attached_single(
     142          440 :         tenant_conf: TenantConfOpt,
     143          440 :         generation: Generation,
     144          440 :         shard_params: &models::ShardParameters,
     145          440 :     ) -> Self {
     146          440 :         Self {
     147          440 :             mode: LocationMode::Attached(AttachedLocationConfig {
     148          440 :                 generation,
     149          440 :                 attach_mode: AttachmentMode::Single,
     150          440 :             }),
     151          440 :             shard: ShardIdentity::from_params(ShardNumber(0), shard_params),
     152          440 :             tenant_conf,
     153          440 :         }
     154          440 :     }
     155              : 
     156              :     /// For use when attaching/re-attaching: update the generation stored in this
     157              :     /// structure.  If we were in a secondary state, promote to attached (posession
     158              :     /// of a fresh generation implies this).
     159            0 :     pub(crate) fn attach_in_generation(&mut self, mode: AttachmentMode, generation: Generation) {
     160            0 :         match &mut self.mode {
     161            0 :             LocationMode::Attached(attach_conf) => {
     162            0 :                 attach_conf.generation = generation;
     163            0 :                 attach_conf.attach_mode = mode;
     164            0 :             }
     165              :             LocationMode::Secondary(_) => {
     166              :                 // We are promoted to attached by the control plane's re-attach response
     167            0 :                 self.mode = LocationMode::Attached(AttachedLocationConfig {
     168            0 :                     generation,
     169            0 :                     attach_mode: mode,
     170            0 :                 })
     171              :             }
     172              :         }
     173            0 :     }
     174              : 
     175            0 :     pub(crate) fn try_from(conf: &'_ models::LocationConfig) -> anyhow::Result<Self> {
     176            0 :         let tenant_conf = TenantConfOpt::try_from(&conf.tenant_conf)?;
     177              : 
     178            0 :         fn get_generation(conf: &'_ models::LocationConfig) -> Result<Generation, anyhow::Error> {
     179            0 :             conf.generation
     180            0 :                 .map(Generation::new)
     181            0 :                 .ok_or_else(|| anyhow::anyhow!("Generation must be set when attaching"))
     182            0 :         }
     183              : 
     184            0 :         let mode = match &conf.mode {
     185              :             models::LocationConfigMode::AttachedMulti => {
     186              :                 LocationMode::Attached(AttachedLocationConfig {
     187            0 :                     generation: get_generation(conf)?,
     188            0 :                     attach_mode: AttachmentMode::Multi,
     189              :                 })
     190              :             }
     191              :             models::LocationConfigMode::AttachedSingle => {
     192              :                 LocationMode::Attached(AttachedLocationConfig {
     193            0 :                     generation: get_generation(conf)?,
     194            0 :                     attach_mode: AttachmentMode::Single,
     195              :                 })
     196              :             }
     197              :             models::LocationConfigMode::AttachedStale => {
     198              :                 LocationMode::Attached(AttachedLocationConfig {
     199            0 :                     generation: get_generation(conf)?,
     200            0 :                     attach_mode: AttachmentMode::Stale,
     201              :                 })
     202              :             }
     203              :             models::LocationConfigMode::Secondary => {
     204            0 :                 anyhow::ensure!(conf.generation.is_none());
     205              : 
     206            0 :                 let warm = conf
     207            0 :                     .secondary_conf
     208            0 :                     .as_ref()
     209            0 :                     .map(|c| c.warm)
     210            0 :                     .unwrap_or(false);
     211            0 :                 LocationMode::Secondary(SecondaryLocationConfig { warm })
     212              :             }
     213              :             models::LocationConfigMode::Detached => {
     214              :                 // Should not have been called: API code should translate this mode
     215              :                 // into a detach rather than trying to decode it as a LocationConf
     216            0 :                 return Err(anyhow::anyhow!("Cannot decode a Detached configuration"));
     217              :             }
     218              :         };
     219              : 
     220            0 :         let shard = if conf.shard_count == 0 {
     221            0 :             ShardIdentity::unsharded()
     222              :         } else {
     223            0 :             ShardIdentity::new(
     224            0 :                 ShardNumber(conf.shard_number),
     225            0 :                 ShardCount::new(conf.shard_count),
     226            0 :                 ShardStripeSize(conf.shard_stripe_size),
     227            0 :             )?
     228              :         };
     229              : 
     230            0 :         Ok(Self {
     231            0 :             shard,
     232            0 :             mode,
     233            0 :             tenant_conf,
     234            0 :         })
     235            0 :     }
     236              : }
     237              : 
     238              : impl Default for LocationConf {
     239              :     // TODO: this should be removed once tenant loading can guarantee that we are never
     240              :     // loading from a directory without a configuration.
     241              :     // => tech debt since https://github.com/neondatabase/neon/issues/1555
     242            0 :     fn default() -> Self {
     243            0 :         Self {
     244            0 :             mode: LocationMode::Attached(AttachedLocationConfig {
     245            0 :                 generation: Generation::none(),
     246            0 :                 attach_mode: AttachmentMode::Single,
     247            0 :             }),
     248            0 :             tenant_conf: TenantConfOpt::default(),
     249            0 :             shard: ShardIdentity::unsharded(),
     250            0 :         }
     251            0 :     }
     252              : }
     253              : 
     254              : /// Same as TenantConf, but this struct preserves the information about
     255              : /// which parameters are set and which are not.
     256          220 : #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
     257              : pub struct TenantConfOpt {
     258              :     #[serde(skip_serializing_if = "Option::is_none")]
     259              :     #[serde(default)]
     260              :     pub checkpoint_distance: Option<u64>,
     261              : 
     262              :     #[serde(skip_serializing_if = "Option::is_none")]
     263              :     #[serde(with = "humantime_serde")]
     264              :     #[serde(default)]
     265              :     pub checkpoint_timeout: Option<Duration>,
     266              : 
     267              :     #[serde(skip_serializing_if = "Option::is_none")]
     268              :     #[serde(default)]
     269              :     pub compaction_target_size: Option<u64>,
     270              : 
     271              :     #[serde(skip_serializing_if = "Option::is_none")]
     272              :     #[serde(with = "humantime_serde")]
     273              :     #[serde(default)]
     274              :     pub compaction_period: Option<Duration>,
     275              : 
     276              :     #[serde(skip_serializing_if = "Option::is_none")]
     277              :     #[serde(default)]
     278              :     pub compaction_threshold: Option<usize>,
     279              : 
     280              :     #[serde(skip_serializing_if = "Option::is_none")]
     281              :     #[serde(default)]
     282              :     pub compaction_upper_limit: Option<usize>,
     283              : 
     284              :     #[serde(skip_serializing_if = "Option::is_none")]
     285              :     #[serde(default)]
     286              :     pub compaction_algorithm: Option<CompactionAlgorithmSettings>,
     287              : 
     288              :     #[serde(skip_serializing_if = "Option::is_none")]
     289              :     #[serde(default)]
     290              :     pub l0_flush_delay_threshold: Option<usize>,
     291              : 
     292              :     #[serde(skip_serializing_if = "Option::is_none")]
     293              :     #[serde(default)]
     294              :     pub l0_flush_stall_threshold: Option<usize>,
     295              : 
     296              :     #[serde(skip_serializing_if = "Option::is_none")]
     297              :     #[serde(default)]
     298              :     pub l0_flush_wait_upload: Option<bool>,
     299              : 
     300              :     #[serde(skip_serializing_if = "Option::is_none")]
     301              :     #[serde(default)]
     302              :     pub gc_horizon: Option<u64>,
     303              : 
     304              :     #[serde(skip_serializing_if = "Option::is_none")]
     305              :     #[serde(with = "humantime_serde")]
     306              :     #[serde(default)]
     307              :     pub gc_period: Option<Duration>,
     308              : 
     309              :     #[serde(skip_serializing_if = "Option::is_none")]
     310              :     #[serde(default)]
     311              :     pub image_creation_threshold: Option<usize>,
     312              : 
     313              :     #[serde(skip_serializing_if = "Option::is_none")]
     314              :     #[serde(with = "humantime_serde")]
     315              :     #[serde(default)]
     316              :     pub pitr_interval: Option<Duration>,
     317              : 
     318              :     #[serde(skip_serializing_if = "Option::is_none")]
     319              :     #[serde(with = "humantime_serde")]
     320              :     #[serde(default)]
     321              :     pub walreceiver_connect_timeout: Option<Duration>,
     322              : 
     323              :     #[serde(skip_serializing_if = "Option::is_none")]
     324              :     #[serde(with = "humantime_serde")]
     325              :     #[serde(default)]
     326              :     pub lagging_wal_timeout: Option<Duration>,
     327              : 
     328              :     #[serde(skip_serializing_if = "Option::is_none")]
     329              :     #[serde(default)]
     330              :     pub max_lsn_wal_lag: Option<NonZeroU64>,
     331              : 
     332              :     #[serde(skip_serializing_if = "Option::is_none")]
     333              :     #[serde(default)]
     334              :     pub eviction_policy: Option<EvictionPolicy>,
     335              : 
     336              :     #[serde(skip_serializing_if = "Option::is_none")]
     337              :     #[serde(default)]
     338              :     pub min_resident_size_override: Option<u64>,
     339              : 
     340              :     #[serde(skip_serializing_if = "Option::is_none")]
     341              :     #[serde(with = "humantime_serde")]
     342              :     #[serde(default)]
     343              :     pub evictions_low_residence_duration_metric_threshold: Option<Duration>,
     344              : 
     345              :     #[serde(skip_serializing_if = "Option::is_none")]
     346              :     #[serde(with = "humantime_serde")]
     347              :     #[serde(default)]
     348              :     pub heatmap_period: Option<Duration>,
     349              : 
     350              :     #[serde(skip_serializing_if = "Option::is_none")]
     351              :     #[serde(default)]
     352              :     pub lazy_slru_download: Option<bool>,
     353              : 
     354              :     #[serde(skip_serializing_if = "Option::is_none")]
     355              :     pub timeline_get_throttle: Option<pageserver_api::models::ThrottleConfig>,
     356              : 
     357              :     #[serde(skip_serializing_if = "Option::is_none")]
     358              :     pub image_layer_creation_check_threshold: Option<u8>,
     359              : 
     360              :     #[serde(skip_serializing_if = "Option::is_none")]
     361              :     #[serde(with = "humantime_serde")]
     362              :     #[serde(default)]
     363              :     pub lsn_lease_length: Option<Duration>,
     364              : 
     365              :     #[serde(skip_serializing_if = "Option::is_none")]
     366              :     #[serde(with = "humantime_serde")]
     367              :     #[serde(default)]
     368              :     pub lsn_lease_length_for_ts: Option<Duration>,
     369              : 
     370              :     #[serde(skip_serializing_if = "Option::is_none")]
     371              :     #[serde(default)]
     372              :     pub timeline_offloading: Option<bool>,
     373              : 
     374              :     #[serde(skip_serializing_if = "Option::is_none")]
     375              :     pub wal_receiver_protocol_override: Option<PostgresClientProtocol>,
     376              : 
     377              :     #[serde(skip_serializing_if = "Option::is_none")]
     378              :     pub rel_size_v2_enabled: Option<bool>,
     379              : 
     380              :     #[serde(skip_serializing_if = "Option::is_none")]
     381              :     pub gc_compaction_enabled: Option<bool>,
     382              : 
     383              :     #[serde(skip_serializing_if = "Option::is_none")]
     384              :     pub gc_compaction_initial_threshold_kb: Option<u64>,
     385              : 
     386              :     #[serde(skip_serializing_if = "Option::is_none")]
     387              :     pub gc_compaction_ratio_percent: Option<u64>,
     388              : }
     389              : 
     390              : impl TenantConfOpt {
     391            0 :     pub fn merge(&self, global_conf: TenantConf) -> TenantConf {
     392            0 :         TenantConf {
     393            0 :             checkpoint_distance: self
     394            0 :                 .checkpoint_distance
     395            0 :                 .unwrap_or(global_conf.checkpoint_distance),
     396            0 :             checkpoint_timeout: self
     397            0 :                 .checkpoint_timeout
     398            0 :                 .unwrap_or(global_conf.checkpoint_timeout),
     399            0 :             compaction_target_size: self
     400            0 :                 .compaction_target_size
     401            0 :                 .unwrap_or(global_conf.compaction_target_size),
     402            0 :             compaction_period: self
     403            0 :                 .compaction_period
     404            0 :                 .unwrap_or(global_conf.compaction_period),
     405            0 :             compaction_threshold: self
     406            0 :                 .compaction_threshold
     407            0 :                 .unwrap_or(global_conf.compaction_threshold),
     408            0 :             compaction_upper_limit: self
     409            0 :                 .compaction_upper_limit
     410            0 :                 .unwrap_or(global_conf.compaction_upper_limit),
     411            0 :             compaction_algorithm: self
     412            0 :                 .compaction_algorithm
     413            0 :                 .as_ref()
     414            0 :                 .unwrap_or(&global_conf.compaction_algorithm)
     415            0 :                 .clone(),
     416            0 :             l0_flush_delay_threshold: self
     417            0 :                 .l0_flush_delay_threshold
     418            0 :                 .or(global_conf.l0_flush_delay_threshold),
     419            0 :             l0_flush_stall_threshold: self
     420            0 :                 .l0_flush_stall_threshold
     421            0 :                 .or(global_conf.l0_flush_stall_threshold),
     422            0 :             l0_flush_wait_upload: self
     423            0 :                 .l0_flush_wait_upload
     424            0 :                 .unwrap_or(global_conf.l0_flush_wait_upload),
     425            0 :             gc_horizon: self.gc_horizon.unwrap_or(global_conf.gc_horizon),
     426            0 :             gc_period: self.gc_period.unwrap_or(global_conf.gc_period),
     427            0 :             image_creation_threshold: self
     428            0 :                 .image_creation_threshold
     429            0 :                 .unwrap_or(global_conf.image_creation_threshold),
     430            0 :             pitr_interval: self.pitr_interval.unwrap_or(global_conf.pitr_interval),
     431            0 :             walreceiver_connect_timeout: self
     432            0 :                 .walreceiver_connect_timeout
     433            0 :                 .unwrap_or(global_conf.walreceiver_connect_timeout),
     434            0 :             lagging_wal_timeout: self
     435            0 :                 .lagging_wal_timeout
     436            0 :                 .unwrap_or(global_conf.lagging_wal_timeout),
     437            0 :             max_lsn_wal_lag: self.max_lsn_wal_lag.unwrap_or(global_conf.max_lsn_wal_lag),
     438            0 :             eviction_policy: self.eviction_policy.unwrap_or(global_conf.eviction_policy),
     439            0 :             min_resident_size_override: self
     440            0 :                 .min_resident_size_override
     441            0 :                 .or(global_conf.min_resident_size_override),
     442            0 :             evictions_low_residence_duration_metric_threshold: self
     443            0 :                 .evictions_low_residence_duration_metric_threshold
     444            0 :                 .unwrap_or(global_conf.evictions_low_residence_duration_metric_threshold),
     445            0 :             heatmap_period: self.heatmap_period.unwrap_or(global_conf.heatmap_period),
     446            0 :             lazy_slru_download: self
     447            0 :                 .lazy_slru_download
     448            0 :                 .unwrap_or(global_conf.lazy_slru_download),
     449            0 :             timeline_get_throttle: self
     450            0 :                 .timeline_get_throttle
     451            0 :                 .clone()
     452            0 :                 .unwrap_or(global_conf.timeline_get_throttle),
     453            0 :             image_layer_creation_check_threshold: self
     454            0 :                 .image_layer_creation_check_threshold
     455            0 :                 .unwrap_or(global_conf.image_layer_creation_check_threshold),
     456            0 :             lsn_lease_length: self
     457            0 :                 .lsn_lease_length
     458            0 :                 .unwrap_or(global_conf.lsn_lease_length),
     459            0 :             lsn_lease_length_for_ts: self
     460            0 :                 .lsn_lease_length_for_ts
     461            0 :                 .unwrap_or(global_conf.lsn_lease_length_for_ts),
     462            0 :             timeline_offloading: self
     463            0 :                 .lazy_slru_download
     464            0 :                 .unwrap_or(global_conf.timeline_offloading),
     465            0 :             wal_receiver_protocol_override: self
     466            0 :                 .wal_receiver_protocol_override
     467            0 :                 .or(global_conf.wal_receiver_protocol_override),
     468            0 :             rel_size_v2_enabled: self.rel_size_v2_enabled.or(global_conf.rel_size_v2_enabled),
     469            0 :             gc_compaction_enabled: self
     470            0 :                 .gc_compaction_enabled
     471            0 :                 .unwrap_or(global_conf.gc_compaction_enabled),
     472            0 :             gc_compaction_initial_threshold_kb: self
     473            0 :                 .gc_compaction_initial_threshold_kb
     474            0 :                 .unwrap_or(global_conf.gc_compaction_initial_threshold_kb),
     475            0 :             gc_compaction_ratio_percent: self
     476            0 :                 .gc_compaction_ratio_percent
     477            0 :                 .unwrap_or(global_conf.gc_compaction_ratio_percent),
     478            0 :         }
     479            0 :     }
     480              : 
     481            0 :     pub fn apply_patch(self, patch: TenantConfigPatch) -> anyhow::Result<TenantConfOpt> {
     482            0 :         let Self {
     483            0 :             mut checkpoint_distance,
     484            0 :             mut checkpoint_timeout,
     485            0 :             mut compaction_target_size,
     486            0 :             mut compaction_period,
     487            0 :             mut compaction_threshold,
     488            0 :             mut compaction_upper_limit,
     489            0 :             mut compaction_algorithm,
     490            0 :             mut l0_flush_delay_threshold,
     491            0 :             mut l0_flush_stall_threshold,
     492            0 :             mut l0_flush_wait_upload,
     493            0 :             mut gc_horizon,
     494            0 :             mut gc_period,
     495            0 :             mut image_creation_threshold,
     496            0 :             mut pitr_interval,
     497            0 :             mut walreceiver_connect_timeout,
     498            0 :             mut lagging_wal_timeout,
     499            0 :             mut max_lsn_wal_lag,
     500            0 :             mut eviction_policy,
     501            0 :             mut min_resident_size_override,
     502            0 :             mut evictions_low_residence_duration_metric_threshold,
     503            0 :             mut heatmap_period,
     504            0 :             mut lazy_slru_download,
     505            0 :             mut timeline_get_throttle,
     506            0 :             mut image_layer_creation_check_threshold,
     507            0 :             mut lsn_lease_length,
     508            0 :             mut lsn_lease_length_for_ts,
     509            0 :             mut timeline_offloading,
     510            0 :             mut wal_receiver_protocol_override,
     511            0 :             mut rel_size_v2_enabled,
     512            0 :             mut gc_compaction_enabled,
     513            0 :             mut gc_compaction_initial_threshold_kb,
     514            0 :             mut gc_compaction_ratio_percent,
     515            0 :         } = self;
     516            0 : 
     517            0 :         patch.checkpoint_distance.apply(&mut checkpoint_distance);
     518            0 :         patch
     519            0 :             .checkpoint_timeout
     520            0 :             .map(|v| humantime::parse_duration(&v))?
     521            0 :             .apply(&mut checkpoint_timeout);
     522            0 :         patch
     523            0 :             .compaction_target_size
     524            0 :             .apply(&mut compaction_target_size);
     525            0 :         patch
     526            0 :             .compaction_period
     527            0 :             .map(|v| humantime::parse_duration(&v))?
     528            0 :             .apply(&mut compaction_period);
     529            0 :         patch.compaction_threshold.apply(&mut compaction_threshold);
     530            0 :         patch
     531            0 :             .compaction_upper_limit
     532            0 :             .apply(&mut compaction_upper_limit);
     533            0 :         patch.compaction_algorithm.apply(&mut compaction_algorithm);
     534            0 :         patch
     535            0 :             .l0_flush_delay_threshold
     536            0 :             .apply(&mut l0_flush_delay_threshold);
     537            0 :         patch
     538            0 :             .l0_flush_stall_threshold
     539            0 :             .apply(&mut l0_flush_stall_threshold);
     540            0 :         patch.l0_flush_wait_upload.apply(&mut l0_flush_wait_upload);
     541            0 :         patch.gc_horizon.apply(&mut gc_horizon);
     542            0 :         patch
     543            0 :             .gc_period
     544            0 :             .map(|v| humantime::parse_duration(&v))?
     545            0 :             .apply(&mut gc_period);
     546            0 :         patch
     547            0 :             .image_creation_threshold
     548            0 :             .apply(&mut image_creation_threshold);
     549            0 :         patch
     550            0 :             .pitr_interval
     551            0 :             .map(|v| humantime::parse_duration(&v))?
     552            0 :             .apply(&mut pitr_interval);
     553            0 :         patch
     554            0 :             .walreceiver_connect_timeout
     555            0 :             .map(|v| humantime::parse_duration(&v))?
     556            0 :             .apply(&mut walreceiver_connect_timeout);
     557            0 :         patch
     558            0 :             .lagging_wal_timeout
     559            0 :             .map(|v| humantime::parse_duration(&v))?
     560            0 :             .apply(&mut lagging_wal_timeout);
     561            0 :         patch.max_lsn_wal_lag.apply(&mut max_lsn_wal_lag);
     562            0 :         patch.eviction_policy.apply(&mut eviction_policy);
     563            0 :         patch
     564            0 :             .min_resident_size_override
     565            0 :             .apply(&mut min_resident_size_override);
     566            0 :         patch
     567            0 :             .evictions_low_residence_duration_metric_threshold
     568            0 :             .map(|v| humantime::parse_duration(&v))?
     569            0 :             .apply(&mut evictions_low_residence_duration_metric_threshold);
     570            0 :         patch
     571            0 :             .heatmap_period
     572            0 :             .map(|v| humantime::parse_duration(&v))?
     573            0 :             .apply(&mut heatmap_period);
     574            0 :         patch.lazy_slru_download.apply(&mut lazy_slru_download);
     575            0 :         patch
     576            0 :             .timeline_get_throttle
     577            0 :             .apply(&mut timeline_get_throttle);
     578            0 :         patch
     579            0 :             .image_layer_creation_check_threshold
     580            0 :             .apply(&mut image_layer_creation_check_threshold);
     581            0 :         patch
     582            0 :             .lsn_lease_length
     583            0 :             .map(|v| humantime::parse_duration(&v))?
     584            0 :             .apply(&mut lsn_lease_length);
     585            0 :         patch
     586            0 :             .lsn_lease_length_for_ts
     587            0 :             .map(|v| humantime::parse_duration(&v))?
     588            0 :             .apply(&mut lsn_lease_length_for_ts);
     589            0 :         patch.timeline_offloading.apply(&mut timeline_offloading);
     590            0 :         patch
     591            0 :             .wal_receiver_protocol_override
     592            0 :             .apply(&mut wal_receiver_protocol_override);
     593            0 :         patch.rel_size_v2_enabled.apply(&mut rel_size_v2_enabled);
     594            0 :         patch
     595            0 :             .gc_compaction_enabled
     596            0 :             .apply(&mut gc_compaction_enabled);
     597            0 :         patch
     598            0 :             .gc_compaction_initial_threshold_kb
     599            0 :             .apply(&mut gc_compaction_initial_threshold_kb);
     600            0 :         patch
     601            0 :             .gc_compaction_ratio_percent
     602            0 :             .apply(&mut gc_compaction_ratio_percent);
     603            0 : 
     604            0 :         Ok(Self {
     605            0 :             checkpoint_distance,
     606            0 :             checkpoint_timeout,
     607            0 :             compaction_target_size,
     608            0 :             compaction_period,
     609            0 :             compaction_threshold,
     610            0 :             compaction_upper_limit,
     611            0 :             compaction_algorithm,
     612            0 :             l0_flush_delay_threshold,
     613            0 :             l0_flush_stall_threshold,
     614            0 :             l0_flush_wait_upload,
     615            0 :             gc_horizon,
     616            0 :             gc_period,
     617            0 :             image_creation_threshold,
     618            0 :             pitr_interval,
     619            0 :             walreceiver_connect_timeout,
     620            0 :             lagging_wal_timeout,
     621            0 :             max_lsn_wal_lag,
     622            0 :             eviction_policy,
     623            0 :             min_resident_size_override,
     624            0 :             evictions_low_residence_duration_metric_threshold,
     625            0 :             heatmap_period,
     626            0 :             lazy_slru_download,
     627            0 :             timeline_get_throttle,
     628            0 :             image_layer_creation_check_threshold,
     629            0 :             lsn_lease_length,
     630            0 :             lsn_lease_length_for_ts,
     631            0 :             timeline_offloading,
     632            0 :             wal_receiver_protocol_override,
     633            0 :             rel_size_v2_enabled,
     634            0 :             gc_compaction_enabled,
     635            0 :             gc_compaction_initial_threshold_kb,
     636            0 :             gc_compaction_ratio_percent,
     637            0 :         })
     638            0 :     }
     639              : }
     640              : 
     641              : impl TryFrom<&'_ models::TenantConfig> for TenantConfOpt {
     642              :     type Error = anyhow::Error;
     643              : 
     644            8 :     fn try_from(request_data: &'_ models::TenantConfig) -> Result<Self, Self::Error> {
     645              :         // Convert the request_data to a JSON Value
     646            8 :         let json_value: Value = serde_json::to_value(request_data)?;
     647              : 
     648              :         // Create a Deserializer from the JSON Value
     649            8 :         let deserializer = json_value.into_deserializer();
     650              : 
     651              :         // Use serde_path_to_error to deserialize the JSON Value into TenantConfOpt
     652            8 :         let tenant_conf: TenantConfOpt = serde_path_to_error::deserialize(deserializer)?;
     653              : 
     654            4 :         Ok(tenant_conf)
     655            8 :     }
     656              : }
     657              : 
     658              : /// This is a conversion from our internal tenant config object to the one used
     659              : /// in external APIs.
     660              : impl From<TenantConfOpt> for models::TenantConfig {
     661            0 :     fn from(value: TenantConfOpt) -> Self {
     662            0 :         fn humantime(d: Duration) -> String {
     663            0 :             format!("{}s", d.as_secs())
     664            0 :         }
     665            0 :         Self {
     666            0 :             checkpoint_distance: value.checkpoint_distance,
     667            0 :             checkpoint_timeout: value.checkpoint_timeout.map(humantime),
     668            0 :             compaction_algorithm: value.compaction_algorithm,
     669            0 :             compaction_target_size: value.compaction_target_size,
     670            0 :             compaction_period: value.compaction_period.map(humantime),
     671            0 :             compaction_threshold: value.compaction_threshold,
     672            0 :             compaction_upper_limit: value.compaction_upper_limit,
     673            0 :             l0_flush_delay_threshold: value.l0_flush_delay_threshold,
     674            0 :             l0_flush_stall_threshold: value.l0_flush_stall_threshold,
     675            0 :             l0_flush_wait_upload: value.l0_flush_wait_upload,
     676            0 :             gc_horizon: value.gc_horizon,
     677            0 :             gc_period: value.gc_period.map(humantime),
     678            0 :             image_creation_threshold: value.image_creation_threshold,
     679            0 :             pitr_interval: value.pitr_interval.map(humantime),
     680            0 :             walreceiver_connect_timeout: value.walreceiver_connect_timeout.map(humantime),
     681            0 :             lagging_wal_timeout: value.lagging_wal_timeout.map(humantime),
     682            0 :             max_lsn_wal_lag: value.max_lsn_wal_lag,
     683            0 :             eviction_policy: value.eviction_policy,
     684            0 :             min_resident_size_override: value.min_resident_size_override,
     685            0 :             evictions_low_residence_duration_metric_threshold: value
     686            0 :                 .evictions_low_residence_duration_metric_threshold
     687            0 :                 .map(humantime),
     688            0 :             heatmap_period: value.heatmap_period.map(humantime),
     689            0 :             lazy_slru_download: value.lazy_slru_download,
     690            0 :             timeline_get_throttle: value.timeline_get_throttle,
     691            0 :             image_layer_creation_check_threshold: value.image_layer_creation_check_threshold,
     692            0 :             lsn_lease_length: value.lsn_lease_length.map(humantime),
     693            0 :             lsn_lease_length_for_ts: value.lsn_lease_length_for_ts.map(humantime),
     694            0 :             timeline_offloading: value.timeline_offloading,
     695            0 :             wal_receiver_protocol_override: value.wal_receiver_protocol_override,
     696            0 :             rel_size_v2_enabled: value.rel_size_v2_enabled,
     697            0 :             gc_compaction_enabled: value.gc_compaction_enabled,
     698            0 :             gc_compaction_initial_threshold_kb: value.gc_compaction_initial_threshold_kb,
     699            0 :             gc_compaction_ratio_percent: value.gc_compaction_ratio_percent,
     700            0 :         }
     701            0 :     }
     702              : }
     703              : 
     704              : #[cfg(test)]
     705              : mod tests {
     706              :     use super::*;
     707              :     use models::TenantConfig;
     708              : 
     709              :     #[test]
     710            4 :     fn de_serializing_pageserver_config_omits_empty_values() {
     711            4 :         let small_conf = TenantConfOpt {
     712            4 :             gc_horizon: Some(42),
     713            4 :             ..TenantConfOpt::default()
     714            4 :         };
     715            4 : 
     716            4 :         let toml_form = toml_edit::ser::to_string(&small_conf).unwrap();
     717            4 :         assert_eq!(toml_form, "gc_horizon = 42\n");
     718            4 :         assert_eq!(small_conf, toml_edit::de::from_str(&toml_form).unwrap());
     719              : 
     720            4 :         let json_form = serde_json::to_string(&small_conf).unwrap();
     721            4 :         assert_eq!(json_form, "{\"gc_horizon\":42}");
     722            4 :         assert_eq!(small_conf, serde_json::from_str(&json_form).unwrap());
     723            4 :     }
     724              : 
     725              :     #[test]
     726            4 :     fn test_try_from_models_tenant_config_err() {
     727            4 :         let tenant_config = models::TenantConfig {
     728            4 :             lagging_wal_timeout: Some("5a".to_string()),
     729            4 :             ..TenantConfig::default()
     730            4 :         };
     731            4 : 
     732            4 :         let tenant_conf_opt = TenantConfOpt::try_from(&tenant_config);
     733            4 : 
     734            4 :         assert!(
     735            4 :             tenant_conf_opt.is_err(),
     736            0 :             "Suceeded to convert TenantConfig to TenantConfOpt"
     737              :         );
     738              : 
     739            4 :         let expected_error_str =
     740            4 :             "lagging_wal_timeout: invalid value: string \"5a\", expected a duration";
     741            4 :         assert_eq!(tenant_conf_opt.unwrap_err().to_string(), expected_error_str);
     742            4 :     }
     743              : 
     744              :     #[test]
     745            4 :     fn test_try_from_models_tenant_config_success() {
     746            4 :         let tenant_config = models::TenantConfig {
     747            4 :             lagging_wal_timeout: Some("5s".to_string()),
     748            4 :             ..TenantConfig::default()
     749            4 :         };
     750            4 : 
     751            4 :         let tenant_conf_opt = TenantConfOpt::try_from(&tenant_config).unwrap();
     752            4 : 
     753            4 :         assert_eq!(
     754            4 :             tenant_conf_opt.lagging_wal_timeout,
     755            4 :             Some(Duration::from_secs(5))
     756            4 :         );
     757            4 :     }
     758              : }
        

Generated by: LCOV version 2.1-beta