redup-config 0.1.0

Типизированная конфигурация: чтение из YAML и окружения, строгость, проверка и выгрузка с комментариями.
Documentation
//! Скаляры конфигурации: целые и дробные числа, логические значения, текст, длительность, адрес
//! службы, отпечаток в 128 бит и идентификатор. Каждый читается и пишется грамматикой
//! `redup-primitives`. Дата и время — в модуле `datetime`.

use std::str::FromStr;
use std::time::Duration;

use redup_primitives::{
    Address, Hash128, format_duration, format_size, parse_duration, parse_size,
};
use uuid::Uuid;

use crate::node::{Node, Shape, Unbuilt, read_scalar, replaced, sampled};
use crate::path::Path;
use crate::problems::Problems;
use crate::raw::Raw;

/// Целое с суффиксом кратности: `13Mi`, `5k`, `0xFF`.
macro_rules! integer {
    ($($ty:ty),*) => {$(
        impl Node for $ty {
            fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
                read_scalar(raw, path, problems, "an integer", parse_size::<$ty>)
            }
            replaced!();
            sampled!(Some(<$ty>::default()));
            fn shape(&self) -> Shape<'_> {
                Shape::Scalar(format_size(*self))
            }
        }
    )*};
}

integer!(i32, i64, u16, u32, u64);

macro_rules! float {
    ($($ty:ty),*) => {$(
        impl Node for $ty {
            fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
                fn parse(text: &str) -> Result<$ty, &'static str> {
                    let value: $ty = text.parse().map_err(|_| "a finite decimal number is expected")?;
                    if value.is_finite() { Ok(value) } else { Err("a finite number is expected") }
                }
                read_scalar(raw, path, problems, "a number", parse)
            }
            replaced!();
            sampled!(Some(<$ty>::default()));
            fn shape(&self) -> Shape<'_> {
                Shape::Scalar(self.to_string())
            }
        }
    )*};
}

float!(f32, f64);

impl Node for bool {
    fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
        fn parse(text: &str) -> Result<bool, &'static str> {
            match text.to_ascii_lowercase().as_str() {
                "true" => Ok(true),
                "false" => Ok(false),
                _ => Err("`true` or `false` is expected"),
            }
        }
        read_scalar(raw, path, problems, "a boolean", parse)
    }
    replaced!();
    sampled!(Some(false));
    fn shape(&self) -> Shape<'_> {
        Shape::Scalar(self.to_string())
    }
}

impl Node for String {
    fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
        read_scalar(raw, path, problems, "a string", |text| {
            Ok::<String, std::convert::Infallible>(text.to_owned())
        })
    }
    replaced!();
    sampled!(Some("example".to_owned()));
    fn shape(&self) -> Shape<'_> {
        Shape::Scalar(self.clone())
    }
}

impl Node for Duration {
    fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
        read_scalar(raw, path, problems, "a duration", parse_duration)
    }
    replaced!();
    sampled!(Some(Duration::ZERO));
    fn shape(&self) -> Shape<'_> {
        Shape::Scalar(format_duration(*self))
    }
}

/// Адрес службы: `[схема://]хост[:порт]`, читается и пишется правилами типа.
impl Node for Address {
    fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
        read_scalar(raw, path, problems, "an address", Address::from_str)
    }
    replaced!();
    fn shape(&self) -> Shape<'_> {
        Shape::Scalar(self.to_string())
    }
}

/// Отпечаток в 128 бит: пишется 32 шестнадцатеричными цифрами в нижнем регистре и читается
/// ровно 32 цифрами в любом регистре, с префиксом `0x` или без него.
impl Node for Hash128 {
    fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
        read_scalar(raw, path, problems, "a hash", Hash128::from_str)
    }
    replaced!();
    sampled!(Some(Hash128::ZERO));
    fn shape(&self) -> Shape<'_> {
        Shape::Scalar(self.to_string())
    }
}

/// Идентификатор UUID: пишется в нижнем регистре через дефисы, читается через дефисы, слитно,
/// в фигурных скобках и с префиксом `urn:uuid:`.
impl Node for Uuid {
    fn read(raw: &Raw, path: &Path, problems: &mut Problems) -> Result<Self, Unbuilt> {
        read_scalar(raw, path, problems, "a UUID", Uuid::parse_str)
    }
    replaced!();
    sampled!(Some(Uuid::nil()));
    fn shape(&self) -> Shape<'_> {
        Shape::Scalar(self.to_string())
    }
}

#[cfg(test)]
mod tests {
    use redup_primitives::{Address, Hash128};
    use uuid::Uuid;

    use crate::node::{Node, Shape};
    use crate::path::Path;
    use crate::problems::Problems;
    use crate::raw::Raw;

    /// Читает значение из текста скаляра; ошибку возвращает её текстом.
    fn read<T: Node>(text: &str) -> Result<T, String> {
        let raw = Raw::scalar(text, crate::mark::Mark::Model);
        let mut problems = Problems::new();
        match T::read(&raw, &Path::new(), &mut problems) {
            Ok(value) => Ok(value),
            Err(_) => Err(problems.to_string()),
        }
    }

    /// Текст скалярной формы узла.
    fn text_of(value: &impl Node) -> String {
        match value.shape() {
            Shape::Scalar(text) => text,
            _ => String::from("not a scalar"),
        }
    }

    #[test]
    fn hash_needs_32_digits_and_is_written_in_lower_case() -> Result<(), String> {
        for text in [
            "3f2504e04f8941d39a0c0305e82c3301",
            "3F2504E04F8941D39A0C0305E82C3301",
            "0x3f2504e04f8941d39a0c0305e82c3301",
        ] {
            let hash: Hash128 = read(text)?;
            assert_eq!(
                text_of(&hash),
                "3f2504e04f8941d39a0c0305e82c3301",
                "read {text:?}"
            );
        }
        assert_eq!(
            read::<Hash128>("0x000000000000000000000000DEADBEEF").map(|value| text_of(&value)),
            Ok("000000000000000000000000deadbeef".to_owned())
        );
        assert_eq!(
            <Hash128 as Node>::sample().map(|value| text_of(&value)),
            Some("0".repeat(32))
        );
        // Меньше 32 цифр, больше 32 цифр и не цифры — ошибки с одним текстом.
        for text in ["xyz", "DEADBEEF", "000000000000000000000000deadbeef000"] {
            let error = read::<Hash128>(text).unwrap_err();
            assert!(
                error.contains(" is not a hash: expected 32 hexadecimal digits"),
                "{text:?}: {error}"
            );
        }
        Ok(())
    }

    #[test]
    fn uuid_is_written_in_lower_case_with_hyphens() -> Result<(), String> {
        for text in [
            "01234567-89ab-cdef-0123-456789abcdef",
            "0123456789ABCDEF0123456789ABCDEF",
            "{01234567-89AB-CDEF-0123-456789ABCDEF}",
            "urn:uuid:01234567-89ab-cdef-0123-456789abcdef",
        ] {
            let id: Uuid = read(text)?;
            assert_eq!(
                text_of(&id),
                "01234567-89ab-cdef-0123-456789abcdef",
                "read {text:?}"
            );
        }
        assert_eq!(
            <Uuid as Node>::sample().map(|id| text_of(&id)),
            Some("00000000-0000-0000-0000-000000000000".to_owned())
        );
        for text in ["zzz", "", "01234567-89ab-cdef-0123-456789abcde"] {
            let error = read::<Uuid>(text).unwrap_err();
            assert!(
                error.starts_with(&format!("{text:?} is not a UUID: ")),
                "{text:?}: {error}"
            );
        }
        Ok(())
    }

    #[test]
    fn address_and_sample_of_numbers_keep_their_writing() -> Result<(), String> {
        let address: Address = read("host:4200")?;
        assert_eq!(text_of(&address), "host:4200");
        assert_eq!(
            <u32 as Node>::sample().map(|value| text_of(&value)),
            Some("0".to_owned())
        );
        assert!(<Address as Node>::sample().is_none());
        Ok(())
    }
}