servlet 1.0.0

A small application runtime with an explicit operational contract
Documentation
//! Bounded declarations and explicit overrides before capture.

use super::{MAX_KEYS, MAX_TOTAL, MAX_VALUE, SettingsError, SettingsErrorKind as Kind};
use std::{
    collections::BTreeMap,
    fmt,
    path::{Path, PathBuf},
};

pub(super) struct Declaration {
    pub default: Option<String>,
    pub override_value: Option<String>,
    pub file: Option<PathBuf>,
    pub secret: bool,
}
impl Declaration {
    fn bytes(&self) -> usize {
        self.default.as_ref().map_or(0, String::len)
            + self.override_value.as_ref().map_or(0, String::len)
            + self.file.as_ref().map_or(0, |p| p.as_os_str().len())
    }
}

/// An explicit schema for at most 128 application settings.
/// Names are uppercase ASCII identifiers, at most 96 bytes. Values are at most
/// 64 KiB each; stored defaults, overrides, and paths together are at most 1 MiB.
/// All values and paths, including ordinary settings, are redacted from `Debug`.
#[derive(Default)]
pub struct Settings {
    pub(super) declarations: BTreeMap<String, Declaration>,
}

impl Settings {
    /// Start with no declarations and no implicit settings.
    pub fn new() -> Self {
        Self::default()
    }
    /// Declare an ordinary key with an optional lowest-priority default.
    pub fn value(self, key: &str, default: Option<&str>) -> Result<Self, SettingsError> {
        self.declare(key, default, false)
    }
    /// Declare a secret key. Snapshot access must use a secret accessor.
    pub fn secret(self, key: &str, default: Option<&str>) -> Result<Self, SettingsError> {
        self.declare(key, default, true)
    }
    /// Set a highest-priority override for a previously declared key.
    /// Repeated calls replace the override; an empty string is a present value.
    pub fn override_value(mut self, key: &str, value: &str) -> Result<Self, SettingsError> {
        let prior = self
            .entry(key)?
            .override_value
            .as_ref()
            .map_or(0, String::len);
        self.check_size(key, value.len(), prior, MAX_VALUE)?;
        self.declarations
            .get_mut(key)
            .expect("declared key")
            .override_value = Some(value.into());
        Ok(self)
    }
    /// Configure an explicit file fallback for a previously declared secret key.
    /// Precedence is override > environment > file > default. A selected file
    /// failure is fatal; a shadowed file is never opened. Paths are at most 4096
    /// bytes. Files must be regular UTF-8 files and are read without trimming.
    pub fn secret_file(mut self, key: &str, path: impl AsRef<Path>) -> Result<Self, SettingsError> {
        let entry = self.entry(key)?;
        if !entry.secret {
            return Err(SettingsError::new(key, Kind::SecretAccess));
        }
        let prior = entry.file.as_ref().map_or(0, |p| p.as_os_str().len());
        let path = path.as_ref();
        self.check_size(key, path.as_os_str().len(), prior, 4096)?;
        self.declarations.get_mut(key).expect("declared key").file = Some(path.to_owned());
        Ok(self)
    }
    fn declare(
        mut self,
        key: &str,
        default: Option<&str>,
        secret: bool,
    ) -> Result<Self, SettingsError> {
        if !super::valid_key(key) {
            return Err(SettingsError::new(key, Kind::InvalidKey));
        }
        if self.declarations.contains_key(key) {
            return Err(SettingsError::new(key, Kind::DuplicateKey));
        }
        if self.declarations.len() >= MAX_KEYS {
            return Err(SettingsError::new(key, Kind::Limit));
        }
        self.check_size(key, default.map_or(0, str::len), 0, MAX_VALUE)?;
        self.declarations.insert(
            key.into(),
            Declaration {
                default: default.map(str::to_owned),
                override_value: None,
                file: None,
                secret,
            },
        );
        Ok(self)
    }
    fn entry(&self, key: &str) -> Result<&Declaration, SettingsError> {
        self.declarations
            .get(key)
            .ok_or_else(|| SettingsError::new(key, Kind::UnknownKey))
    }
    fn check_size(
        &self,
        key: &str,
        added: usize,
        prior: usize,
        limit: usize,
    ) -> Result<(), SettingsError> {
        if added > limit
            || self
                .declarations
                .values()
                .map(Declaration::bytes)
                .sum::<usize>()
                - prior
                + added
                > MAX_TOTAL
        {
            return Err(SettingsError::new(key, Kind::Limit));
        }
        Ok(())
    }
}
impl fmt::Debug for Settings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Settings")
            .field("keys", &self.declarations.keys())
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
#[path = "builder_test.rs"]
mod builder_test;