use std::{borrow::Cow, collections::BTreeSet, error::Error, fmt, time::Duration};
use serde::{Deserializer, Serializer, de};
use crate::result::{ClassifyError, ErrorKind};
pub const MAX_CONFIG_ISSUES: usize = 128;
const DEFAULT_CONFIG_ISSUE_PATH: &str = "configuration";
const DEFAULT_CONFIG_ISSUE_MESSAGE: &str = "is invalid";
pub trait SettingsAdapter<T> {
type Error;
fn adapt(&self) -> Result<T, Self::Error>;
}
pub trait ValidateSettings {
fn validate_settings(&self) -> Result<(), ConfigValidationError>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigIssue {
path: String,
message: String,
}
impl ConfigIssue {
#[must_use]
pub fn new(path: impl Into<String>, message: impl Into<String>) -> Self {
Self {
path: normalize_config_issue_field(path, DEFAULT_CONFIG_ISSUE_PATH),
message: normalize_config_issue_field(message, DEFAULT_CONFIG_ISSUE_MESSAGE),
}
}
#[must_use]
pub fn path(&self) -> &str {
&self.path
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
fn normalize_config_issue_field(value: impl Into<String>, fallback: &'static str) -> String {
let value = value.into().trim().to_owned();
if value.is_empty() {
fallback.to_owned()
} else {
value
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigIssues {
issues: Vec<ConfigIssue>,
}
impl ConfigIssues {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, path: impl Into<String>, message: impl Into<String>) {
if self.issues.len() < MAX_CONFIG_ISSUES {
self.issues.push(ConfigIssue::new(path, message));
}
}
pub fn require(
&mut self,
condition: bool,
path: impl Into<String>,
message: impl Into<String>,
) {
if !condition {
self.push(path, message);
}
}
pub fn require_non_empty(&mut self, path: impl Into<String>, value: &str) {
let path = path.into();
self.require(!value.trim().is_empty(), path, "must not be empty");
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.issues.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.issues.len()
}
#[must_use]
pub fn as_slice(&self) -> &[ConfigIssue] {
&self.issues
}
pub fn into_result(self) -> Result<(), ConfigValidationError> {
if self.issues.is_empty() {
Ok(())
} else {
Err(ConfigValidationError { issues: self })
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigIssueCollector {
issues: ConfigIssues,
}
impl ConfigIssueCollector {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn push(&mut self, path: impl Into<String>, message: impl Into<String>) {
self.issues.push(path, message);
}
pub fn require(
&mut self,
condition: bool,
path: impl Into<String>,
message: impl Into<String>,
) {
self.issues.require(condition, path, message);
}
pub fn require_non_empty(&mut self, path: impl Into<String>, value: &str) {
self.issues.require_non_empty(path, value);
}
pub fn extend(&mut self, error: ConfigValidationError) {
for issue in error.issues() {
self.push(issue.path(), issue.message());
}
}
pub fn extend_result(&mut self, result: Result<(), ConfigValidationError>) {
if let Err(error) = result {
self.extend(error);
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.issues.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.issues.len()
}
#[must_use]
pub fn issues(&self) -> &[ConfigIssue] {
self.issues.as_slice()
}
pub fn into_result(self) -> Result<(), ConfigValidationError> {
self.issues.into_result()
}
#[must_use]
pub fn into_issues(self) -> ConfigIssues {
self.issues
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigValidationError {
issues: ConfigIssues,
}
impl ConfigValidationError {
#[must_use]
pub fn new(issues: ConfigIssues) -> Self {
Self { issues }
}
#[must_use]
pub fn single(path: impl Into<String>, message: impl Into<String>) -> Self {
let mut issues = ConfigIssues::new();
issues.push(path, message);
Self { issues }
}
#[must_use]
pub fn issues(&self) -> &[ConfigIssue] {
self.issues.as_slice()
}
#[must_use]
pub fn into_issues(self) -> ConfigIssues {
self.issues
}
}
impl fmt::Display for ConfigValidationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("configuration validation failed")?;
for issue in self.issues() {
write!(formatter, "\n- {}: {}", issue.path(), issue.message())?;
}
Ok(())
}
}
impl Error for ConfigValidationError {}
impl ClassifyError for ConfigValidationError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed("configuration_invalid")
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigDocument {
title: String,
sections: Vec<ConfigSectionDoc>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConfigExampleMode {
RequiredOnly,
Recommended,
Complete,
}
impl ConfigDocument {
#[must_use]
pub fn new(title: impl Into<String>) -> Self {
Self {
title: title.into().trim().to_owned(),
sections: Vec::new(),
}
}
#[must_use]
pub fn with_section(mut self, section: ConfigSectionDoc) -> Self {
self.sections.push(section);
self
}
#[must_use]
pub fn with_sections(mut self, sections: impl IntoIterator<Item = ConfigSectionDoc>) -> Self {
self.sections.extend(sections);
self
}
#[must_use]
pub fn title(&self) -> &str {
&self.title
}
#[must_use]
pub fn sections(&self) -> &[ConfigSectionDoc] {
&self.sections
}
pub fn validate(&self) -> Result<(), ConfigValidationError> {
let mut issues = ConfigIssues::new();
let mut section_names = BTreeSet::new();
for section in &self.sections {
issues.require(
is_toml_path(§ion.name),
format!("[{}]", section.name),
"section name must be a TOML bare-key path",
);
if !section_names.insert(section.name.as_str()) {
issues.push(format!("[{}]", section.name), "section name must be unique");
}
let mut field_names = BTreeSet::new();
for field in §ion.fields {
let field_path = format!("{}.{}", section.name, field.name);
issues.require(
is_toml_path(field.name()),
&field_path,
"field name must be a TOML bare-key path",
);
issues.require(
!field.example_value().trim().is_empty(),
&field_path,
"example value must not be empty",
);
if !field_names.insert(field.name()) {
issues.push(&field_path, "field name must be unique within section");
}
}
}
issues.into_result()
}
#[must_use]
pub fn render_markdown(&self) -> String {
let mut output = String::new();
output.push_str("# ");
output.push_str(if self.title.is_empty() {
"Configuration"
} else {
&self.title
});
output.push_str("\n\n");
for section in &self.sections {
section.render_markdown_into(&mut output);
}
output
}
#[must_use]
pub fn render_toml_example(&self) -> String {
self.render_toml(ConfigExampleMode::Complete)
}
#[must_use]
pub fn render_required_toml_example(&self) -> String {
self.render_toml(ConfigExampleMode::RequiredOnly)
}
#[must_use]
pub fn render_recommended_toml_example(&self) -> String {
self.render_toml(ConfigExampleMode::Recommended)
}
#[must_use]
pub fn render_toml(&self, mode: ConfigExampleMode) -> String {
let mut output = String::new();
for section in &self.sections {
section.render_toml_into(&mut output, mode);
}
output
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigSectionDoc {
name: String,
description: String,
fields: Vec<ConfigFieldDoc>,
}
impl ConfigSectionDoc {
#[must_use]
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into().trim().trim_matches(['[', ']']).to_owned(),
description: String::new(),
fields: Vec::new(),
}
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = description.into().trim().to_owned();
self
}
#[must_use]
pub fn with_field(mut self, field: ConfigFieldDoc) -> Self {
self.fields.push(field);
self
}
#[must_use]
pub fn with_fields(mut self, fields: impl IntoIterator<Item = ConfigFieldDoc>) -> Self {
self.fields.extend(fields);
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn description(&self) -> &str {
&self.description
}
#[must_use]
pub fn fields(&self) -> &[ConfigFieldDoc] {
&self.fields
}
#[must_use]
pub fn field(&self, name: &str) -> Option<&ConfigFieldDoc> {
self.fields.iter().find(|field| field.name() == name)
}
fn render_markdown_into(&self, output: &mut String) {
output.push_str("## [");
output.push_str(&self.name);
output.push_str("]\n\n");
if !self.description.is_empty() {
output.push_str(&self.description);
output.push_str("\n\n");
}
for field in &self.fields {
output.push_str("- `");
output.push_str(field.name());
output.push('`');
if field.is_required() {
output.push_str(" required");
}
if field.is_secret() {
output.push_str(", secret");
}
if field.is_recommended() && !field.is_required() {
output.push_str(", recommended");
}
if field.restart_required() {
output.push_str(", restart required");
}
if let Some(default) = field.default_value() {
output.push_str(", default `");
output.push_str(default);
output.push('`');
}
if let Some(env_var) = field.env_var() {
output.push_str(", env `");
output.push_str(env_var);
output.push('`');
}
if !field.description().is_empty() {
output.push_str(": ");
output.push_str(field.description());
}
output.push('\n');
}
output.push('\n');
}
fn render_toml_into(&self, output: &mut String, mode: ConfigExampleMode) {
let fields = self
.fields
.iter()
.filter(|field| field.included_in_example(mode));
let mut wrote_header = false;
for field in fields {
if !wrote_header {
output.push('[');
output.push_str(&self.name);
output.push_str("]\n");
wrote_header = true;
}
if matches!(mode, ConfigExampleMode::Complete) && !field.is_required() {
output.push_str("# ");
}
output.push_str(field.name());
output.push_str(" = ");
output.push_str(field.example_value());
if field.is_secret() {
output.push_str(" # secret");
} else if !field.description().is_empty() {
output.push_str(" # ");
output.push_str(field.description());
}
output.push('\n');
}
if wrote_header {
output.push('\n');
}
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ConfigFieldDoc {
name: String,
description: String,
example_value: String,
default_value: Option<String>,
required: bool,
recommended: bool,
secret: bool,
restart_required: bool,
env_var: Option<String>,
}
impl fmt::Debug for ConfigFieldDoc {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = formatter.debug_struct("ConfigFieldDoc");
debug
.field("name", &self.name)
.field("description", &self.description);
if self.secret {
debug.field("example_value", &"[REDACTED]").field(
"default_value",
&self.default_value.as_ref().map(|_| "[REDACTED]"),
);
} else {
debug
.field("example_value", &self.example_value)
.field("default_value", &self.default_value);
}
debug
.field("required", &self.required)
.field("recommended", &self.recommended)
.field("secret", &self.secret)
.field("restart_required", &self.restart_required)
.field("env_var", &self.env_var)
.finish()
}
}
impl ConfigFieldDoc {
#[must_use]
pub fn required(
name: impl Into<String>,
example_value: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self::new(name, example_value, description, true, None)
}
#[must_use]
pub fn optional(
name: impl Into<String>,
example_value: impl Into<String>,
description: impl Into<String>,
) -> Self {
Self::new(name, example_value, description, false, None)
}
#[must_use]
pub fn optional_default(
name: impl Into<String>,
default_value: impl Into<String>,
description: impl Into<String>,
) -> Self {
let default_value = default_value.into();
Self::new(
name,
default_value.clone(),
description,
false,
Some(default_value),
)
}
#[must_use]
pub fn secret(mut self) -> Self {
self.secret = true;
self
}
#[must_use]
pub const fn recommended(mut self) -> Self {
self.recommended = true;
self
}
#[must_use]
pub fn with_restart_required(mut self) -> Self {
self.restart_required = true;
self
}
#[must_use]
pub fn with_env_var(mut self, env_var: impl Into<String>) -> Self {
let env_var = env_var.into().trim().to_owned();
if !env_var.is_empty() {
self.env_var = Some(env_var);
}
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn description(&self) -> &str {
&self.description
}
#[must_use]
pub fn example_value(&self) -> &str {
&self.example_value
}
#[must_use]
pub fn default_value(&self) -> Option<&str> {
self.default_value.as_deref()
}
#[must_use]
pub const fn is_required(&self) -> bool {
self.required
}
#[must_use]
pub const fn is_recommended(&self) -> bool {
self.recommended
}
#[must_use]
pub const fn is_secret(&self) -> bool {
self.secret
}
#[must_use]
pub const fn restart_required(&self) -> bool {
self.restart_required
}
#[must_use]
pub fn env_var(&self) -> Option<&str> {
self.env_var.as_deref()
}
fn new(
name: impl Into<String>,
example_value: impl Into<String>,
description: impl Into<String>,
required: bool,
default_value: Option<String>,
) -> Self {
Self {
name: name.into().trim().to_owned(),
description: description.into().trim().to_owned(),
example_value: example_value.into().trim().to_owned(),
default_value,
required,
recommended: required,
secret: false,
restart_required: false,
env_var: None,
}
}
const fn included_in_example(&self, mode: ConfigExampleMode) -> bool {
match mode {
ConfigExampleMode::RequiredOnly => self.required,
ConfigExampleMode::Recommended => self.required || self.recommended,
ConfigExampleMode::Complete => true,
}
}
}
fn is_toml_path(value: &str) -> bool {
let value = value.trim();
!value.is_empty()
&& value.split('.').all(|part| {
!part.is_empty()
&& part
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-'))
})
}
pub mod human_duration {
use super::*;
const NANOS_PER_NANO: u128 = 1;
const NANOS_PER_MICRO: u128 = 1_000;
const NANOS_PER_MILLI: u128 = 1_000_000;
const NANOS_PER_SECOND: u128 = 1_000_000_000;
const NANOS_PER_MINUTE: u128 = 60 * NANOS_PER_SECOND;
const NANOS_PER_HOUR: u128 = 60 * NANOS_PER_MINUTE;
const NANOS_PER_DAY: u128 = 24 * NANOS_PER_HOUR;
const NANOS_PER_WEEK: u128 = 7 * NANOS_PER_DAY;
pub fn serialize<S>(duration: &Duration, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format(*duration))
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Duration, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_str(DurationVisitor)
}
pub mod option {
use super::*;
pub fn serialize<S>(duration: &Option<Duration>, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match duration {
Some(duration) => serializer.serialize_some(&format(*duration)),
None => serializer.serialize_none(),
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
where
D: Deserializer<'de>,
{
struct OptionDurationVisitor;
impl<'de> de::Visitor<'de> for OptionDurationVisitor {
type Value = Option<Duration>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("null or a duration string")
}
fn visit_none<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}
fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: de::Error,
{
Ok(None)
}
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: Deserializer<'de>,
{
super::deserialize(deserializer).map(Some)
}
}
deserializer.deserialize_option(OptionDurationVisitor)
}
}
#[must_use]
pub fn format(duration: Duration) -> String {
let total_nanos =
u128::from(duration.as_secs()) * NANOS_PER_SECOND + u128::from(duration.subsec_nanos());
for (unit, unit_nanos) in [
("w", NANOS_PER_WEEK),
("d", NANOS_PER_DAY),
("h", NANOS_PER_HOUR),
("m", NANOS_PER_MINUTE),
("s", NANOS_PER_SECOND),
("ms", NANOS_PER_MILLI),
("us", NANOS_PER_MICRO),
("ns", NANOS_PER_NANO),
] {
if total_nanos >= unit_nanos && total_nanos.is_multiple_of(unit_nanos) {
return format!("{}{unit}", total_nanos / unit_nanos);
}
}
format!("{}ns", duration.as_nanos())
}
pub fn parse(value: &str) -> Result<Duration, ParseDurationError> {
let value = value.trim();
if value.is_empty() {
return Err(ParseDurationError::Empty);
}
let mut index = 0;
let mut total_nanos = 0_u128;
let mut saw_component = false;
while index < value.len() {
skip_ascii_whitespace(value, &mut index);
if index >= value.len() {
break;
}
let number_start = index;
while value.as_bytes().get(index).is_some_and(u8::is_ascii_digit) {
index += 1;
}
if number_start == index {
return Err(ParseDurationError::MissingNumber { offset: index });
}
let amount = value
.get(number_start..index)
.ok_or(ParseDurationError::InvalidUnit)?
.parse::<u128>()
.map_err(|_| ParseDurationError::NumberTooLarge)?;
let unit = value.get(index..).ok_or(ParseDurationError::InvalidUnit)?;
let (unit_nanos, unit_len) = duration_unit(unit)?;
index += unit_len;
saw_component = true;
let component = amount
.checked_mul(unit_nanos)
.ok_or(ParseDurationError::Overflow)?;
total_nanos = total_nanos
.checked_add(component)
.ok_or(ParseDurationError::Overflow)?;
if total_nanos / NANOS_PER_SECOND > u128::from(u64::MAX) {
return Err(ParseDurationError::Overflow);
}
}
if !saw_component {
return Err(ParseDurationError::Empty);
}
Ok(Duration::new(
(total_nanos / NANOS_PER_SECOND) as u64,
(total_nanos % NANOS_PER_SECOND) as u32,
))
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseDurationError {
Empty,
MissingNumber {
#[doc = "The offset value."]
offset: usize,
},
NumberTooLarge,
InvalidUnit,
Overflow,
}
impl fmt::Display for ParseDurationError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Empty => formatter.write_str("duration must not be empty"),
Self::MissingNumber { offset } => {
write!(
formatter,
"duration component must start with digits at byte {offset}"
)
}
Self::NumberTooLarge => formatter.write_str("duration number is too large"),
Self::InvalidUnit => {
formatter.write_str("duration unit must be one of ns, us, ms, s, m, h, d or w")
}
Self::Overflow => formatter.write_str("duration is too large"),
}
}
}
impl Error for ParseDurationError {}
impl ClassifyError for ParseDurationError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> Cow<'static, str> {
Cow::Borrowed(match self {
Self::Empty => "duration_empty",
Self::MissingNumber { .. } => "duration_missing_number",
Self::NumberTooLarge => "duration_number_too_large",
Self::InvalidUnit => "duration_invalid_unit",
Self::Overflow => "duration_overflow",
})
}
}
struct DurationVisitor;
impl de::Visitor<'_> for DurationVisitor {
type Value = Duration;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a duration string such as 500ms, 30s, 5m, 2h, 7d or 1h30m")
}
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
parse(value).map_err(E::custom)
}
}
fn duration_unit(value: &str) -> Result<(u128, usize), ParseDurationError> {
if value.starts_with("ns") {
Ok((NANOS_PER_NANO, 2))
} else if value.starts_with("ms") {
Ok((NANOS_PER_MILLI, 2))
} else if value.starts_with("us") {
Ok((NANOS_PER_MICRO, 2))
} else if value.starts_with("µs") {
Ok((NANOS_PER_MICRO, "µs".len()))
} else if single_unit_boundary(value, 's') {
Ok((NANOS_PER_SECOND, 1))
} else if single_unit_boundary(value, 'm') {
Ok((NANOS_PER_MINUTE, 1))
} else if single_unit_boundary(value, 'h') {
Ok((NANOS_PER_HOUR, 1))
} else if single_unit_boundary(value, 'd') {
Ok((NANOS_PER_DAY, 1))
} else if single_unit_boundary(value, 'w') {
Ok((NANOS_PER_WEEK, 1))
} else {
Err(ParseDurationError::InvalidUnit)
}
}
fn single_unit_boundary(value: &str, unit: char) -> bool {
value.starts_with(unit)
&& value
.get(unit.len_utf8()..)
.unwrap_or_default()
.chars()
.next()
.is_none_or(|character| {
character.is_ascii_whitespace() || character.is_ascii_digit()
})
}
fn skip_ascii_whitespace(value: &str, index: &mut usize) {
while value
.as_bytes()
.get(*index)
.is_some_and(u8::is_ascii_whitespace)
{
*index += 1;
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{
ConfigDocument, ConfigFieldDoc, ConfigIssue, ConfigIssueCollector, ConfigIssues,
ConfigSectionDoc, SettingsAdapter, ValidateSettings, human_duration,
};
use crate::result::{ClassifyError, ErrorKind};
struct AppConfig {
host: String,
port: u16,
}
impl ValidateSettings for AppConfig {
fn validate_settings(&self) -> Result<(), super::ConfigValidationError> {
let mut issues = ConfigIssues::new();
issues.require_non_empty("server.host", &self.host);
issues.require(self.port > 0, "server.port", "must be greater than zero");
issues.into_result()
}
}
impl SettingsAdapter<String> for AppConfig {
type Error = super::ConfigValidationError;
fn adapt(&self) -> Result<String, Self::Error> {
self.validate_settings()?;
Ok(format!("{}:{}", self.host, self.port))
}
}
#[test]
fn config_issue_collector_merges_nested_validation_errors() {
let mut collector = ConfigIssueCollector::new();
collector.require_non_empty("server.host", "");
collector.extend_result(
AppConfig {
host: String::new(),
port: 0,
}
.validate_settings(),
);
let error = collector
.into_result()
.expect_err("collector should contain validation issues");
let paths = error
.issues()
.iter()
.map(|issue| issue.path())
.collect::<Vec<_>>();
assert!(paths.contains(&"server.host"));
assert!(paths.contains(&"server.port"));
assert_eq!(error.error_kind(), ErrorKind::Validation);
assert_eq!(error.error_code(), "configuration_invalid");
}
#[test]
fn config_issue_uses_stable_fallbacks_for_empty_operator_text() {
let issue = ConfigIssue::new(" ", "");
assert_eq!(issue.path(), "configuration");
assert_eq!(issue.message(), "is invalid");
}
#[test]
fn human_duration_accepts_compact_duration_strings() {
assert_eq!(
human_duration::parse("1h30m").expect("duration should parse"),
Duration::from_secs(90 * 60)
);
assert_eq!(
human_duration::parse("500ms").expect("duration should parse"),
Duration::from_millis(500)
);
assert_eq!(
human_duration::parse("2w 3d 4h").expect("duration should parse"),
Duration::from_secs((14 + 3) * 24 * 60 * 60 + 4 * 60 * 60)
);
}
#[test]
fn human_duration_rejects_ambiguous_values() {
assert!(human_duration::parse("").is_err());
assert!(human_duration::parse("5").is_err());
assert!(human_duration::parse("1mo").is_err());
assert!(human_duration::parse("m").is_err());
}
#[test]
fn human_duration_errors_have_stable_classification() {
let error = human_duration::parse("1mo").expect_err("unit should be invalid");
let descriptor = error.error_descriptor();
assert_eq!(descriptor.kind(), ErrorKind::Validation);
assert_eq!(descriptor.code().as_str(), "duration_invalid_unit");
}
#[test]
fn human_duration_formats_using_largest_exact_unit() {
assert_eq!(human_duration::format(Duration::from_secs(60 * 60)), "1h");
assert_eq!(human_duration::format(Duration::from_millis(500)), "500ms");
assert_eq!(human_duration::format(Duration::from_nanos(1)), "1ns");
}
#[test]
fn human_duration_option_supports_null_and_strings() {
#[derive(serde::Deserialize, serde::Serialize)]
struct Config {
#[serde(default, with = "human_duration::option")]
value: Option<Duration>,
}
let parsed: Config = serde_json::from_str(r#"{ "value": "5m" }"#).unwrap();
assert_eq!(parsed.value, Some(Duration::from_secs(300)));
let parsed: Config = serde_json::from_str(r#"{ "value": null }"#).unwrap();
assert_eq!(parsed.value, None);
assert_eq!(
serde_json::to_value(Config {
value: Some(Duration::from_secs(30))
})
.unwrap(),
serde_json::json!({ "value": "30s" })
);
}
#[test]
fn settings_adapter_validates_before_mapping() {
let config = AppConfig {
host: "127.0.0.1".to_owned(),
port: 8080,
};
assert_eq!(config.adapt().unwrap(), "127.0.0.1:8080");
let config = AppConfig {
host: String::new(),
port: 0,
};
let error = config.adapt().unwrap_err();
assert_eq!(error.issues().len(), 2);
assert!(error.to_string().contains("server.host"));
}
#[test]
fn config_document_renders_markdown_and_toml_example() {
let document = ConfigDocument::new("Example").with_section(
ConfigSectionDoc::new("server")
.with_description("HTTP listener settings.")
.with_field(ConfigFieldDoc::required(
"host",
r#""127.0.0.1""#,
"Bind host.",
))
.with_field(
ConfigFieldDoc::optional_default("port", "8080", "Bind port.").recommended(),
)
.with_field(ConfigFieldDoc::optional_default(
"debug",
"false",
"Debug mode.",
))
.with_field(
ConfigFieldDoc::required("token", r#""change-me""#, "Admin token.")
.secret()
.with_restart_required()
.with_env_var("APP_TOKEN"),
),
);
document.validate().expect("document should be valid");
assert!(document.sections()[0].field("port").is_some());
let markdown = document.render_markdown();
assert!(markdown.contains("## [server]"));
assert!(markdown.contains("`host` required"));
assert!(markdown.contains("default `8080`"));
assert!(markdown.contains("`port`, recommended"));
assert!(markdown.contains("`token` required, secret, restart required"));
assert!(markdown.contains("env `APP_TOKEN`"));
let toml = document.render_toml_example();
assert!(toml.contains("[server]"));
assert!(toml.contains("host = \"127.0.0.1\""));
assert!(toml.contains("# port = 8080"));
let required = document.render_required_toml_example();
assert!(required.contains("host = \"127.0.0.1\""));
assert!(required.contains("token = \"change-me\" # secret"));
assert!(!required.contains("port = 8080"));
let recommended = document.render_recommended_toml_example();
assert!(recommended.contains("host = \"127.0.0.1\""));
assert!(recommended.contains("port = 8080"));
assert!(!recommended.contains("debug = false"));
}
#[test]
fn secret_config_field_debug_redacts_example_and_default_values() {
let secret = "private-config-secret";
let field = ConfigFieldDoc::optional_default("token", secret, "Admin token.").secret();
let debug = format!("{field:?}");
assert!(debug.contains("token"));
assert!(debug.contains("[REDACTED]"));
assert!(!debug.contains(secret));
let non_secret = ConfigFieldDoc::optional_default("port", "8080", "Bind port.");
assert!(format!("{non_secret:?}").contains("8080"));
}
#[test]
fn config_document_validation_rejects_invalid_toml_paths_and_duplicates() {
let document = ConfigDocument::new("Bad")
.with_section(
ConfigSectionDoc::new("bad section").with_field(ConfigFieldDoc::required(
"host",
r#""127.0.0.1""#,
"",
)),
)
.with_section(
ConfigSectionDoc::new("server")
.with_field(ConfigFieldDoc::required("host", r#""127.0.0.1""#, ""))
.with_field(ConfigFieldDoc::optional("host", "8080", "")),
)
.with_section(ConfigSectionDoc::new("server"));
let error = document.validate().expect_err("document should be invalid");
let message = error.to_string();
assert!(message.contains("[bad section]"));
assert!(message.contains("server.host"));
assert!(message.contains("section name must be unique"));
assert!(message.contains("field name must be unique within section"));
}
}