//! Runtime settings: the operator's values that change without a restart, and where each one comes from. //! //! The precedence is fixed: a UI override (a row of the `settings` table, written by the admin page), then //! the file (`[limits]` in the configuration), then the built-in default. [`resolve`] returns the value //! together with the layer it came from, so the admin page can show the source beside each value. Every //! caller reads through [`resolve`], so the rule is written once. Nothing here changes the database. use crate::config::Limits; use crate::error::{Error, Result}; use crate::quota::DEFAULT_MEMBER_QUOTA; use crate::store::Store; use crate::store::objects::DEFAULT_SERVICE_QUOTA; /// Settings key of the quota a new person gets, in bytes. pub const DEFAULT_QUOTA_KEY: &str = "default_quota_bytes"; /// Settings key of the quota a new service namespace gets, in bytes. pub const DEFAULT_SERVICE_QUOTA_KEY: &str = "default_service_quota_bytes"; /// Settings key of the days trash waits before a purge. pub const PURGE_KEY: &str = "purge_after_days"; /// Settings key of the largest upload, in bytes. pub const MAX_UPLOAD_KEY: &str = "max_upload_bytes"; /// Settings key of the longest share link, in days. pub const LINK_MAX_DAYS_KEY: &str = "link_max_days"; /// One GiB in bytes. const GIB: i64 = 1024 * 1024 * 1024; /// One MiB in bytes. const MIB: i64 = 1024 * 1024; /// One TiB in bytes: the upper bound of every byte value, far above any real quota. const TIB: i64 = 1024 * GIB; /// Default purge delay: 30 days. pub const DEFAULT_PURGE_AFTER_DAYS: i64 = 30; /// Default largest upload: 50 GiB. pub const DEFAULT_MAX_UPLOAD: i64 = 50 * GIB; /// Default longest share link: a year. pub const DEFAULT_LINK_MAX_DAYS: i64 = 365; /// How a field may change. Shown on the admin page next to the value. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Mode { /// The next request that reads the value uses the new one. Live, /// Takes effect after a restart of the process. Restart, /// Set in the file only, and shown but not editable. ReadOnly, } /// The layer a value came from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Source { /// Set on the admin page. Ui, /// Set in the configuration file. File, /// The built-in default. Default, } /// A value and the layer it came from. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Resolved { /// The value in the field's unit. pub value: i64, /// Which layer supplied it. pub source: Source, } /// One field the admin page can show or change: its key, default, the bounds a value must meet, and its /// mode. Byte fields are in bytes and day fields in days. #[derive(Debug)] pub struct Field { /// The settings key, also the key in the file's `[limits]` table. pub key: &'static str, /// The built-in default. pub default: i64, /// Smallest value accepted. pub min: i64, /// Largest value accepted. pub max: i64, /// How the value may change. pub mode: Mode, } /// Every field of the admin page's defaults section, in display order. pub const FIELDS: [Field; 5] = [ Field { key: DEFAULT_QUOTA_KEY, default: DEFAULT_MEMBER_QUOTA, min: 0, max: TIB, mode: Mode::Live, }, Field { key: DEFAULT_SERVICE_QUOTA_KEY, default: DEFAULT_SERVICE_QUOTA, min: 0, max: TIB, mode: Mode::Live, }, Field { key: PURGE_KEY, default: DEFAULT_PURGE_AFTER_DAYS, min: 1, max: 3650, mode: Mode::Live, }, Field { key: MAX_UPLOAD_KEY, default: DEFAULT_MAX_UPLOAD, min: MIB, max: TIB, mode: Mode::Live, }, Field { key: LINK_MAX_DAYS_KEY, default: DEFAULT_LINK_MAX_DAYS, min: 1, max: 3650, mode: Mode::Live, }, ]; /// The field with this key, if it is one of [`FIELDS`]. pub fn field(key: &str) -> Option<&'static Field> { FIELDS.iter().find(|field| field.key == key) } /// The file value of `key`, when the `[limits]` table sets it. pub fn file_value(limits: &Limits, key: &str) -> Option { match key { DEFAULT_QUOTA_KEY => limits.default_quota_bytes, DEFAULT_SERVICE_QUOTA_KEY => limits.default_service_quota_bytes, PURGE_KEY => limits.purge_after_days, MAX_UPLOAD_KEY => limits.max_upload_bytes, LINK_MAX_DAYS_KEY => limits.link_max_days, _ => None, } } /// Checks a value against the field's bounds. The refusal word is the key with `_range`, which the /// admin page turns into a sentence. pub fn check(field: &Field, value: i64) -> Result { if value < field.min || value > field.max { return Err(Error::Invalid(format!("{}_range", field.key))); } Ok(value) } /// Parses the text of an admin form for `key`. Blank means "no override": `Ok(None)`. Anything else /// must be an integer within the field's bounds. pub fn parse_ui(key: &str, text: &str) -> Result> { let field = field(key).ok_or_else(|| Error::Invalid("unknown_setting".into()))?; let text = text.trim(); if text.is_empty() { return Ok(None); } let value: i64 = text .parse() .map_err(|_| Error::Invalid(format!("{}_range", field.key)))?; check(field, value).map(Some) } /// Checks every value the file sets. Called by `Config::validate`, so a bad file fails at boot. pub fn check_file(limits: &Limits) -> Result<()> { for field in &FIELDS { if let Some(value) = file_value(limits, field.key) { check(field, value).map_err(|_| { Error::Config(format!( "limits.{} must be between {} and {}", field.key, field.min, field.max )) })?; } } Ok(()) } /// The effective value of `key`: the UI override when one is stored and valid, else the file value, else /// the default. A stored override that is out of bounds (possible only by hand-editing the database) is /// ignored and the next layer is used. pub async fn resolve(store: &Store, limits: &Limits, key: &str) -> Result { let field = field(key).ok_or_else(|| Error::Invalid("unknown_setting".into()))?; if let Some(text) = store.get_setting(key).await? && let Some(value) = text .trim() .parse::() .ok() .filter(|v| check(field, *v).is_ok()) { return Ok(Resolved { value, source: Source::Ui, }); } if let Some(value) = file_value(limits, key) { return Ok(Resolved { value, source: Source::File, }); } Ok(Resolved { value: field.default, source: Source::Default, }) } /// The word the admin page shows for a source: `ui`, `file` or `default`. The page translates it. pub fn source_word(source: Source) -> &'static str { match source { Source::Ui => "ui", Source::File => "file", Source::Default => "default", } } #[cfg(test)] mod tests { use super::*; use crate::store::Store; #[test] fn blank_clears_and_bounds_are_enforced() { assert_eq!(parse_ui(PURGE_KEY, " ").unwrap(), None); assert_eq!(parse_ui(PURGE_KEY, "30").unwrap(), Some(30)); assert!(parse_ui(PURGE_KEY, "0").is_err()); assert!(parse_ui(PURGE_KEY, "3651").is_err()); assert!(parse_ui(PURGE_KEY, "soon").is_err()); assert!(parse_ui("nope", "1").is_err()); } #[tokio::test] async fn ui_beats_file_beats_default() { let dir = tempfile::tempdir().unwrap(); let store = Store::open(&dir.path().join("in.db")).await.unwrap(); let limits = Limits { purge_after_days: Some(7), ..Limits::default() }; let from_file = resolve(&store, &limits, PURGE_KEY).await.unwrap(); assert_eq!(from_file.value, 7); assert_eq!(from_file.source, Source::File); store.set_setting(PURGE_KEY, "14").await.unwrap(); let from_ui = resolve(&store, &limits, PURGE_KEY).await.unwrap(); assert_eq!(from_ui.value, 14); assert_eq!(from_ui.source, Source::Ui); let default = resolve(&store, &Limits::default(), LINK_MAX_DAYS_KEY) .await .unwrap(); assert_eq!(default.value, DEFAULT_LINK_MAX_DAYS); assert_eq!(default.source, Source::Default); } }