LCOV - code coverage report
Current view: top level - pageserver/src - config.rs (source / functions) Coverage Total Hit
Test: 8ff8efadb0253cf618c612650348666c0c564111.info Lines: 81.9 % 259 212
Test Date: 2024-11-20 17:53:50 Functions: 46.7 % 45 21

            Line data    Source code
       1              : //! Functions for handling page server configuration options
       2              : //!
       3              : //! Configuration options can be set in the pageserver.toml configuration
       4              : //! file, or on the command line.
       5              : //! See also `settings.md` for better description on every parameter.
       6              : 
       7              : use anyhow::{bail, ensure, Context};
       8              : use pageserver_api::models::ImageCompressionAlgorithm;
       9              : use pageserver_api::{
      10              :     config::{DiskUsageEvictionTaskConfig, MaxVectoredReadBytes},
      11              :     shard::TenantShardId,
      12              : };
      13              : use remote_storage::{RemotePath, RemoteStorageConfig};
      14              : use std::env;
      15              : use storage_broker::Uri;
      16              : use utils::logging::SecretString;
      17              : 
      18              : use once_cell::sync::OnceCell;
      19              : use reqwest::Url;
      20              : use std::num::NonZeroUsize;
      21              : use std::sync::Arc;
      22              : use std::time::Duration;
      23              : 
      24              : use camino::{Utf8Path, Utf8PathBuf};
      25              : use postgres_backend::AuthType;
      26              : use utils::{
      27              :     id::{NodeId, TimelineId},
      28              :     logging::LogFormat,
      29              : };
      30              : 
      31              : use crate::tenant::storage_layer::inmemory_layer::IndexEntry;
      32              : use crate::tenant::{TENANTS_SEGMENT_NAME, TIMELINES_SEGMENT_NAME};
      33              : use crate::virtual_file;
      34              : use crate::virtual_file::io_engine;
      35              : use crate::{TENANT_HEATMAP_BASENAME, TENANT_LOCATION_CONFIG_NAME};
      36              : 
      37              : /// Global state of pageserver.
      38              : ///
      39              : /// It's mostly immutable configuration, but some semaphores and the
      40              : /// like crept in over time and the name stuck.
      41              : ///
      42              : /// Instantiated by deserializing `pageserver.toml` into  [`pageserver_api::config::ConfigToml`]
      43              : /// and passing that to [`PageServerConf::parse_and_validate`].
      44              : ///
      45              : /// # Adding a New Field
      46              : ///
      47              : /// 1. Add the field to `pageserver_api::config::ConfigToml`.
      48              : /// 2. Fix compiler errors (exhaustive destructuring will guide you).
      49              : ///
      50              : /// For fields that require additional validation or filling in of defaults at runtime,
      51              : /// check for examples in the [`PageServerConf::parse_and_validate`] method.
      52              : #[derive(Debug, Clone, PartialEq, Eq)]
      53              : pub struct PageServerConf {
      54              :     // Identifier of that particular pageserver so e g safekeepers
      55              :     // can safely distinguish different pageservers
      56              :     pub id: NodeId,
      57              : 
      58              :     /// Example (default): 127.0.0.1:64000
      59              :     pub listen_pg_addr: String,
      60              :     /// Example (default): 127.0.0.1:9898
      61              :     pub listen_http_addr: String,
      62              : 
      63              :     /// Current availability zone. Used for traffic metrics.
      64              :     pub availability_zone: Option<String>,
      65              : 
      66              :     // Timeout when waiting for WAL receiver to catch up to an LSN given in a GetPage@LSN call.
      67              :     pub wait_lsn_timeout: Duration,
      68              :     // How long to wait for WAL redo to complete.
      69              :     pub wal_redo_timeout: Duration,
      70              : 
      71              :     pub superuser: String,
      72              :     pub locale: String,
      73              : 
      74              :     pub page_cache_size: usize,
      75              :     pub max_file_descriptors: usize,
      76              : 
      77              :     // Repository directory, relative to current working directory.
      78              :     // Normally, the page server changes the current working directory
      79              :     // to the repository, and 'workdir' is always '.'. But we don't do
      80              :     // that during unit testing, because the current directory is global
      81              :     // to the process but different unit tests work on different
      82              :     // repositories.
      83              :     pub workdir: Utf8PathBuf,
      84              : 
      85              :     pub pg_distrib_dir: Utf8PathBuf,
      86              : 
      87              :     // Authentication
      88              :     /// authentication method for the HTTP mgmt API
      89              :     pub http_auth_type: AuthType,
      90              :     /// authentication method for libpq connections from compute
      91              :     pub pg_auth_type: AuthType,
      92              :     /// Path to a file or directory containing public key(s) for verifying JWT tokens.
      93              :     /// Used for both mgmt and compute auth, if enabled.
      94              :     pub auth_validation_public_key_path: Option<Utf8PathBuf>,
      95              : 
      96              :     pub remote_storage_config: Option<RemoteStorageConfig>,
      97              : 
      98              :     pub default_tenant_conf: crate::tenant::config::TenantConf,
      99              : 
     100              :     /// Storage broker endpoints to connect to.
     101              :     pub broker_endpoint: Uri,
     102              :     pub broker_keepalive_interval: Duration,
     103              : 
     104              :     pub log_format: LogFormat,
     105              : 
     106              :     /// Number of tenants which will be concurrently loaded from remote storage proactively on startup or attach.
     107              :     ///
     108              :     /// A lower value implicitly deprioritizes loading such tenants, vs. other work in the system.
     109              :     pub concurrent_tenant_warmup: ConfigurableSemaphore,
     110              : 
     111              :     /// Number of concurrent [`Tenant::gather_size_inputs`](crate::tenant::Tenant::gather_size_inputs) allowed.
     112              :     pub concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore,
     113              :     /// Limit of concurrent [`Tenant::gather_size_inputs`] issued by module `eviction_task`.
     114              :     /// The number of permits is the same as `concurrent_tenant_size_logical_size_queries`.
     115              :     /// See the comment in `eviction_task` for details.
     116              :     ///
     117              :     /// [`Tenant::gather_size_inputs`]: crate::tenant::Tenant::gather_size_inputs
     118              :     pub eviction_task_immitated_concurrent_logical_size_queries: ConfigurableSemaphore,
     119              : 
     120              :     // How often to collect metrics and send them to the metrics endpoint.
     121              :     pub metric_collection_interval: Duration,
     122              :     // How often to send unchanged cached metrics to the metrics endpoint.
     123              :     pub metric_collection_endpoint: Option<Url>,
     124              :     pub metric_collection_bucket: Option<RemoteStorageConfig>,
     125              :     pub synthetic_size_calculation_interval: Duration,
     126              : 
     127              :     pub disk_usage_based_eviction: Option<DiskUsageEvictionTaskConfig>,
     128              : 
     129              :     pub test_remote_failures: u64,
     130              : 
     131              :     pub ondemand_download_behavior_treat_error_as_warn: bool,
     132              : 
     133              :     /// How long will background tasks be delayed at most after initial load of tenants.
     134              :     ///
     135              :     /// Our largest initialization completions are in the range of 100-200s, so perhaps 10s works
     136              :     /// as we now isolate initial loading, initial logical size calculation and background tasks.
     137              :     /// Smaller nodes will have background tasks "not running" for this long unless every timeline
     138              :     /// has it's initial logical size calculated. Not running background tasks for some seconds is
     139              :     /// not terrible.
     140              :     pub background_task_maximum_delay: Duration,
     141              : 
     142              :     pub control_plane_api: Option<Url>,
     143              : 
     144              :     /// JWT token for use with the control plane API.
     145              :     pub control_plane_api_token: Option<SecretString>,
     146              : 
     147              :     /// If true, pageserver will make best-effort to operate without a control plane: only
     148              :     /// for use in major incidents.
     149              :     pub control_plane_emergency_mode: bool,
     150              : 
     151              :     /// How many heatmap uploads may be done concurrency: lower values implicitly deprioritize
     152              :     /// heatmap uploads vs. other remote storage operations.
     153              :     pub heatmap_upload_concurrency: usize,
     154              : 
     155              :     /// How many remote storage downloads may be done for secondary tenants concurrently.  Implicitly
     156              :     /// deprioritises secondary downloads vs. remote storage operations for attached tenants.
     157              :     pub secondary_download_concurrency: usize,
     158              : 
     159              :     /// Maximum number of WAL records to be ingested and committed at the same time
     160              :     pub ingest_batch_size: u64,
     161              : 
     162              :     pub virtual_file_io_engine: virtual_file::IoEngineKind,
     163              : 
     164              :     pub max_vectored_read_bytes: MaxVectoredReadBytes,
     165              : 
     166              :     pub image_compression: ImageCompressionAlgorithm,
     167              : 
     168              :     /// Whether to offload archived timelines automatically
     169              :     pub timeline_offloading: bool,
     170              : 
     171              :     /// How many bytes of ephemeral layer content will we allow per kilobyte of RAM.  When this
     172              :     /// is exceeded, we start proactively closing ephemeral layers to limit the total amount
     173              :     /// of ephemeral data.
     174              :     ///
     175              :     /// Setting this to zero disables limits on total ephemeral layer size.
     176              :     pub ephemeral_bytes_per_memory_kb: usize,
     177              : 
     178              :     pub l0_flush: crate::l0_flush::L0FlushConfig,
     179              : 
     180              :     /// Direct IO settings
     181              :     pub virtual_file_io_mode: virtual_file::IoMode,
     182              : 
     183              :     /// Optionally disable disk syncs (unsafe!)
     184              :     pub no_sync: bool,
     185              : 
     186              :     /// Maximum amount of time for which a get page request request
     187              :     /// might be held up for request merging.
     188              :     pub server_side_batch_timeout: Option<Duration>,
     189              : }
     190              : 
     191              : /// Token for authentication to safekeepers
     192              : ///
     193              : /// We do not want to store this in a PageServerConf because the latter may be logged
     194              : /// and/or serialized at a whim, while the token is secret. Currently this token is the
     195              : /// same for accessing all tenants/timelines, but may become per-tenant/per-timeline in
     196              : /// the future, more tokens and auth may arrive for storage broker, completely changing the logic.
     197              : /// Hence, we resort to a global variable for now instead of passing the token from the
     198              : /// startup code to the connection code through a dozen layers.
     199              : pub static SAFEKEEPER_AUTH_TOKEN: OnceCell<Arc<String>> = OnceCell::new();
     200              : 
     201              : impl PageServerConf {
     202              :     //
     203              :     // Repository paths, relative to workdir.
     204              :     //
     205              : 
     206         7042 :     pub fn tenants_path(&self) -> Utf8PathBuf {
     207         7042 :         self.workdir.join(TENANTS_SEGMENT_NAME)
     208         7042 :     }
     209              : 
     210           72 :     pub fn deletion_prefix(&self) -> Utf8PathBuf {
     211           72 :         self.workdir.join("deletion")
     212           72 :     }
     213              : 
     214            0 :     pub fn metadata_path(&self) -> Utf8PathBuf {
     215            0 :         self.workdir.join("metadata.json")
     216            0 :     }
     217              : 
     218           28 :     pub fn deletion_list_path(&self, sequence: u64) -> Utf8PathBuf {
     219              :         // Encode a version in the filename, so that if we ever switch away from JSON we can
     220              :         // increment this.
     221              :         const VERSION: u8 = 1;
     222              : 
     223           28 :         self.deletion_prefix()
     224           28 :             .join(format!("{sequence:016x}-{VERSION:02x}.list"))
     225           28 :     }
     226              : 
     227           24 :     pub fn deletion_header_path(&self) -> Utf8PathBuf {
     228              :         // Encode a version in the filename, so that if we ever switch away from JSON we can
     229              :         // increment this.
     230              :         const VERSION: u8 = 1;
     231              : 
     232           24 :         self.deletion_prefix().join(format!("header-{VERSION:02x}"))
     233           24 :     }
     234              : 
     235         7002 :     pub fn tenant_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
     236         7002 :         self.tenants_path().join(tenant_shard_id.to_string())
     237         7002 :     }
     238              : 
     239              :     /// Points to a place in pageserver's local directory,
     240              :     /// where certain tenant's LocationConf be stored.
     241            0 :     pub(crate) fn tenant_location_config_path(
     242            0 :         &self,
     243            0 :         tenant_shard_id: &TenantShardId,
     244            0 :     ) -> Utf8PathBuf {
     245            0 :         self.tenant_path(tenant_shard_id)
     246            0 :             .join(TENANT_LOCATION_CONFIG_NAME)
     247            0 :     }
     248              : 
     249            0 :     pub(crate) fn tenant_heatmap_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
     250            0 :         self.tenant_path(tenant_shard_id)
     251            0 :             .join(TENANT_HEATMAP_BASENAME)
     252            0 :     }
     253              : 
     254         6806 :     pub fn timelines_path(&self, tenant_shard_id: &TenantShardId) -> Utf8PathBuf {
     255         6806 :         self.tenant_path(tenant_shard_id)
     256         6806 :             .join(TIMELINES_SEGMENT_NAME)
     257         6806 :     }
     258              : 
     259         6416 :     pub fn timeline_path(
     260         6416 :         &self,
     261         6416 :         tenant_shard_id: &TenantShardId,
     262         6416 :         timeline_id: &TimelineId,
     263         6416 :     ) -> Utf8PathBuf {
     264         6416 :         self.timelines_path(tenant_shard_id)
     265         6416 :             .join(timeline_id.to_string())
     266         6416 :     }
     267              : 
     268              :     /// Turns storage remote path of a file into its local path.
     269            0 :     pub fn local_path(&self, remote_path: &RemotePath) -> Utf8PathBuf {
     270            0 :         remote_path.with_base(&self.workdir)
     271            0 :     }
     272              : 
     273              :     //
     274              :     // Postgres distribution paths
     275              :     //
     276           20 :     pub fn pg_distrib_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
     277           20 :         let path = self.pg_distrib_dir.clone();
     278           20 : 
     279           20 :         #[allow(clippy::manual_range_patterns)]
     280           20 :         match pg_version {
     281           20 :             14 | 15 | 16 | 17 => Ok(path.join(format!("v{pg_version}"))),
     282            0 :             _ => bail!("Unsupported postgres version: {}", pg_version),
     283              :         }
     284           20 :     }
     285              : 
     286           10 :     pub fn pg_bin_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
     287           10 :         Ok(self.pg_distrib_dir(pg_version)?.join("bin"))
     288           10 :     }
     289           10 :     pub fn pg_lib_dir(&self, pg_version: u32) -> anyhow::Result<Utf8PathBuf> {
     290           10 :         Ok(self.pg_distrib_dir(pg_version)?.join("lib"))
     291           10 :     }
     292              : 
     293              :     /// Parse a configuration file (pageserver.toml) into a PageServerConf struct,
     294              :     /// validating the input and failing on errors.
     295              :     ///
     296              :     /// This leaves any options not present in the file in the built-in defaults.
     297          210 :     pub fn parse_and_validate(
     298          210 :         id: NodeId,
     299          210 :         config_toml: pageserver_api::config::ConfigToml,
     300          210 :         workdir: &Utf8Path,
     301          210 :     ) -> anyhow::Result<Self> {
     302          210 :         let pageserver_api::config::ConfigToml {
     303          210 :             listen_pg_addr,
     304          210 :             listen_http_addr,
     305          210 :             availability_zone,
     306          210 :             wait_lsn_timeout,
     307          210 :             wal_redo_timeout,
     308          210 :             superuser,
     309          210 :             locale,
     310          210 :             page_cache_size,
     311          210 :             max_file_descriptors,
     312          210 :             pg_distrib_dir,
     313          210 :             http_auth_type,
     314          210 :             pg_auth_type,
     315          210 :             auth_validation_public_key_path,
     316          210 :             remote_storage,
     317          210 :             broker_endpoint,
     318          210 :             broker_keepalive_interval,
     319          210 :             log_format,
     320          210 :             metric_collection_interval,
     321          210 :             metric_collection_endpoint,
     322          210 :             metric_collection_bucket,
     323          210 :             synthetic_size_calculation_interval,
     324          210 :             disk_usage_based_eviction,
     325          210 :             test_remote_failures,
     326          210 :             ondemand_download_behavior_treat_error_as_warn,
     327          210 :             background_task_maximum_delay,
     328          210 :             control_plane_api,
     329          210 :             control_plane_api_token,
     330          210 :             control_plane_emergency_mode,
     331          210 :             heatmap_upload_concurrency,
     332          210 :             secondary_download_concurrency,
     333          210 :             ingest_batch_size,
     334          210 :             max_vectored_read_bytes,
     335          210 :             image_compression,
     336          210 :             timeline_offloading,
     337          210 :             ephemeral_bytes_per_memory_kb,
     338          210 :             l0_flush,
     339          210 :             virtual_file_io_mode,
     340          210 :             concurrent_tenant_warmup,
     341          210 :             concurrent_tenant_size_logical_size_queries,
     342          210 :             virtual_file_io_engine,
     343          210 :             server_side_batch_timeout,
     344          210 :             tenant_config,
     345          210 :             no_sync,
     346          210 :         } = config_toml;
     347              : 
     348          210 :         let mut conf = PageServerConf {
     349              :             // ------------------------------------------------------------
     350              :             // fields that are already fully validated by the ConfigToml Deserialize impl
     351              :             // ------------------------------------------------------------
     352          210 :             listen_pg_addr,
     353          210 :             listen_http_addr,
     354          210 :             availability_zone,
     355          210 :             wait_lsn_timeout,
     356          210 :             wal_redo_timeout,
     357          210 :             superuser,
     358          210 :             locale,
     359          210 :             page_cache_size,
     360          210 :             max_file_descriptors,
     361          210 :             http_auth_type,
     362          210 :             pg_auth_type,
     363          210 :             auth_validation_public_key_path,
     364          210 :             remote_storage_config: remote_storage,
     365          210 :             broker_endpoint,
     366          210 :             broker_keepalive_interval,
     367          210 :             log_format,
     368          210 :             metric_collection_interval,
     369          210 :             metric_collection_endpoint,
     370          210 :             metric_collection_bucket,
     371          210 :             synthetic_size_calculation_interval,
     372          210 :             disk_usage_based_eviction,
     373          210 :             test_remote_failures,
     374          210 :             ondemand_download_behavior_treat_error_as_warn,
     375          210 :             background_task_maximum_delay,
     376          210 :             control_plane_api,
     377          210 :             control_plane_emergency_mode,
     378          210 :             heatmap_upload_concurrency,
     379          210 :             secondary_download_concurrency,
     380          210 :             ingest_batch_size,
     381          210 :             max_vectored_read_bytes,
     382          210 :             image_compression,
     383          210 :             timeline_offloading,
     384          210 :             ephemeral_bytes_per_memory_kb,
     385          210 :             server_side_batch_timeout,
     386          210 : 
     387          210 :             // ------------------------------------------------------------
     388          210 :             // fields that require additional validation or custom handling
     389          210 :             // ------------------------------------------------------------
     390          210 :             workdir: workdir.to_owned(),
     391          210 :             pg_distrib_dir: pg_distrib_dir.unwrap_or_else(|| {
     392            2 :                 std::env::current_dir()
     393            2 :                     .expect("current_dir() failed")
     394            2 :                     .try_into()
     395            2 :                     .expect("current_dir() is not a valid Utf8Path")
     396          210 :             }),
     397          210 :             control_plane_api_token: control_plane_api_token.map(SecretString::from),
     398          210 :             id,
     399          210 :             default_tenant_conf: tenant_config,
     400          210 :             concurrent_tenant_warmup: ConfigurableSemaphore::new(concurrent_tenant_warmup),
     401          210 :             concurrent_tenant_size_logical_size_queries: ConfigurableSemaphore::new(
     402          210 :                 concurrent_tenant_size_logical_size_queries,
     403          210 :             ),
     404          210 :             eviction_task_immitated_concurrent_logical_size_queries: ConfigurableSemaphore::new(
     405          210 :                 // re-use `concurrent_tenant_size_logical_size_queries`
     406          210 :                 concurrent_tenant_size_logical_size_queries,
     407          210 :             ),
     408          210 :             virtual_file_io_engine: match virtual_file_io_engine {
     409            0 :                 Some(v) => v,
     410          210 :                 None => match crate::virtual_file::io_engine_feature_test()
     411          210 :                     .context("auto-detect virtual_file_io_engine")?
     412              :                 {
     413          210 :                     io_engine::FeatureTestResult::PlatformPreferred(v) => v, // make no noise
     414            0 :                     io_engine::FeatureTestResult::Worse { engine, remark } => {
     415            0 :                         // TODO: bubble this up to the caller so we can tracing::warn! it.
     416            0 :                         eprintln!("auto-detected IO engine is not platform-preferred: engine={engine:?} remark={remark:?}");
     417            0 :                         engine
     418              :                     }
     419              :                 },
     420              :             },
     421          210 :             l0_flush: l0_flush
     422          210 :                 .map(crate::l0_flush::L0FlushConfig::from)
     423          210 :                 .unwrap_or_default(),
     424          210 :             virtual_file_io_mode: virtual_file_io_mode.unwrap_or(virtual_file::IoMode::preferred()),
     425          210 :             no_sync: no_sync.unwrap_or(false),
     426          210 :         };
     427          210 : 
     428          210 :         // ------------------------------------------------------------
     429          210 :         // custom validation code that covers more than one field in isolation
     430          210 :         // ------------------------------------------------------------
     431          210 : 
     432          210 :         if conf.http_auth_type == AuthType::NeonJWT || conf.pg_auth_type == AuthType::NeonJWT {
     433            0 :             let auth_validation_public_key_path = conf
     434            0 :                 .auth_validation_public_key_path
     435            0 :                 .get_or_insert_with(|| workdir.join("auth_public_key.pem"));
     436            0 :             ensure!(
     437            0 :                 auth_validation_public_key_path.exists(),
     438            0 :                 format!(
     439            0 :                     "Can't find auth_validation_public_key at '{auth_validation_public_key_path}'",
     440            0 :                 )
     441              :             );
     442          210 :         }
     443              : 
     444          210 :         IndexEntry::validate_checkpoint_distance(conf.default_tenant_conf.checkpoint_distance)
     445          210 :             .map_err(anyhow::Error::msg)
     446          210 :             .with_context(|| {
     447            0 :                 format!(
     448            0 :                     "effective checkpoint distance is unsupported: {}",
     449            0 :                     conf.default_tenant_conf.checkpoint_distance
     450            0 :                 )
     451          210 :             })?;
     452              : 
     453          210 :         Ok(conf)
     454          210 :     }
     455              : 
     456              :     #[cfg(test)]
     457          210 :     pub fn test_repo_dir(test_name: &str) -> Utf8PathBuf {
     458          210 :         let test_output_dir = std::env::var("TEST_OUTPUT").unwrap_or("../tmp_check".into());
     459          210 :         Utf8PathBuf::from(format!("{test_output_dir}/test_{test_name}"))
     460          210 :     }
     461              : 
     462          208 :     pub fn dummy_conf(repo_dir: Utf8PathBuf) -> Self {
     463          208 :         let pg_distrib_dir = Utf8PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../pg_install");
     464          208 : 
     465          208 :         let config_toml = pageserver_api::config::ConfigToml {
     466          208 :             wait_lsn_timeout: Duration::from_secs(60),
     467          208 :             wal_redo_timeout: Duration::from_secs(60),
     468          208 :             pg_distrib_dir: Some(pg_distrib_dir),
     469          208 :             metric_collection_interval: Duration::from_secs(60),
     470          208 :             synthetic_size_calculation_interval: Duration::from_secs(60),
     471          208 :             background_task_maximum_delay: Duration::ZERO,
     472          208 :             ..Default::default()
     473          208 :         };
     474          208 :         PageServerConf::parse_and_validate(NodeId(0), config_toml, &repo_dir).unwrap()
     475          208 :     }
     476              : }
     477              : 
     478            0 : #[derive(serde::Deserialize, serde::Serialize)]
     479              : #[serde(deny_unknown_fields)]
     480              : pub struct PageserverIdentity {
     481              :     pub id: NodeId,
     482              : }
     483              : 
     484              : /// Configurable semaphore permits setting.
     485              : ///
     486              : /// Does not allow semaphore permits to be zero, because at runtime initially zero permits and empty
     487              : /// semaphore cannot be distinguished, leading any feature using these to await forever (or until
     488              : /// new permits are added).
     489              : #[derive(Debug, Clone)]
     490              : pub struct ConfigurableSemaphore {
     491              :     initial_permits: NonZeroUsize,
     492              :     inner: std::sync::Arc<tokio::sync::Semaphore>,
     493              : }
     494              : 
     495              : impl ConfigurableSemaphore {
     496              :     /// Initializse using a non-zero amount of permits.
     497              :     ///
     498              :     /// Require a non-zero initial permits, because using permits == 0 is a crude way to disable a
     499              :     /// feature such as [`Tenant::gather_size_inputs`]. Otherwise any semaphore using future will
     500              :     /// behave like [`futures::future::pending`], just waiting until new permits are added.
     501              :     ///
     502              :     /// [`Tenant::gather_size_inputs`]: crate::tenant::Tenant::gather_size_inputs
     503          630 :     pub fn new(initial_permits: NonZeroUsize) -> Self {
     504          630 :         ConfigurableSemaphore {
     505          630 :             initial_permits,
     506          630 :             inner: std::sync::Arc::new(tokio::sync::Semaphore::new(initial_permits.get())),
     507          630 :         }
     508          630 :     }
     509              : 
     510              :     /// Returns the configured amount of permits.
     511            0 :     pub fn initial_permits(&self) -> NonZeroUsize {
     512            0 :         self.initial_permits
     513            0 :     }
     514              : }
     515              : 
     516              : impl PartialEq for ConfigurableSemaphore {
     517            0 :     fn eq(&self, other: &Self) -> bool {
     518            0 :         // the number of permits can be increased at runtime, so we cannot really fulfill the
     519            0 :         // PartialEq value equality otherwise
     520            0 :         self.initial_permits == other.initial_permits
     521            0 :     }
     522              : }
     523              : 
     524              : impl Eq for ConfigurableSemaphore {}
     525              : 
     526              : impl ConfigurableSemaphore {
     527            0 :     pub fn inner(&self) -> &std::sync::Arc<tokio::sync::Semaphore> {
     528            0 :         &self.inner
     529            0 :     }
     530              : }
     531              : 
     532              : #[cfg(test)]
     533              : mod tests {
     534              : 
     535              :     use camino::Utf8PathBuf;
     536              :     use utils::id::NodeId;
     537              : 
     538              :     use super::PageServerConf;
     539              : 
     540              :     #[test]
     541            2 :     fn test_empty_config_toml_is_valid() {
     542            2 :         // we use Default impl of everything in this situation
     543            2 :         let input = r#"
     544            2 :         "#;
     545            2 :         let config_toml = toml_edit::de::from_str::<pageserver_api::config::ConfigToml>(input)
     546            2 :             .expect("empty config is valid");
     547            2 :         let workdir = Utf8PathBuf::from("/nonexistent");
     548            2 :         PageServerConf::parse_and_validate(NodeId(0), config_toml, &workdir)
     549            2 :             .expect("parse_and_validate");
     550            2 :     }
     551              : 
     552              :     /// If there's a typo in the pageserver config, we'd rather catch that typo
     553              :     /// and fail pageserver startup than silently ignoring the typo, leaving whoever
     554              :     /// made it in the believe that their config change is effective.
     555              :     ///
     556              :     /// The default in serde is to allow unknown fields, so, we rely
     557              :     /// on developer+review discipline to add `deny_unknown_fields` when adding
     558              :     /// new structs to the config, and these tests here as a regression test.
     559              :     ///
     560              :     /// The alternative to all of this would be to allow unknown fields in the config.
     561              :     /// To catch them, we could have a config check tool or mgmt API endpoint that
     562              :     /// compares the effective config with the TOML on disk and makes sure that
     563              :     /// the on-disk TOML is a strict subset of the effective config.
     564              :     mod unknown_fields_handling {
     565              :         macro_rules! test {
     566              :             ($short_name:ident, $input:expr) => {
     567              :                 #[test]
     568           10 :                 fn $short_name() {
     569           10 :                     let input = $input;
     570           10 :                     let err = toml_edit::de::from_str::<pageserver_api::config::ConfigToml>(&input)
     571           10 :                         .expect_err("some_invalid_field is an invalid field");
     572           10 :                     dbg!(&err);
     573           10 :                     assert!(err.to_string().contains("some_invalid_field"));
     574           10 :                 }
     575              :             };
     576              :         }
     577              :         use indoc::indoc;
     578              : 
     579              :         test!(
     580              :             toplevel,
     581              :             indoc! {r#"
     582              :                 some_invalid_field = 23
     583              :             "#}
     584              :         );
     585              : 
     586              :         test!(
     587              :             toplevel_nested,
     588              :             indoc! {r#"
     589              :                 [some_invalid_field]
     590              :                 foo = 23
     591              :             "#}
     592              :         );
     593              : 
     594              :         test!(
     595              :             disk_usage_based_eviction,
     596              :             indoc! {r#"
     597              :                 [disk_usage_based_eviction]
     598              :                 some_invalid_field = 23
     599              :             "#}
     600              :         );
     601              : 
     602              :         test!(
     603              :             tenant_config,
     604              :             indoc! {r#"
     605              :                 [tenant_config]
     606              :                 some_invalid_field = 23
     607              :             "#}
     608              :         );
     609              : 
     610              :         test!(
     611              :             l0_flush,
     612              :             indoc! {r#"
     613              :                 [l0_flush]
     614              :                 mode = "direct"
     615              :                 some_invalid_field = 23
     616              :             "#}
     617              :         );
     618              : 
     619              :         // TODO: fix this => https://github.com/neondatabase/neon/issues/8915
     620              :         // test!(
     621              :         //     remote_storage_config,
     622              :         //     indoc! {r#"
     623              :         //         [remote_storage_config]
     624              :         //         local_path = "/nonexistent"
     625              :         //         some_invalid_field = 23
     626              :         //     "#}
     627              :         // );
     628              :     }
     629              : }
        

Generated by: LCOV version 2.1-beta