feat: validate resolved configuration
This commit is contained in:
parent
18ec49ceb4
commit
8226989ce4
327
src/config.rs
327
src/config.rs
|
|
@ -166,6 +166,7 @@ impl ConfigLoader {
|
|||
apply_file(&mut config, path)?;
|
||||
}
|
||||
apply_cli_overrides(&mut config, &self.overrides);
|
||||
config.validate().map_err(ConfigError::Validation)?;
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
|
|
@ -216,6 +217,116 @@ pub enum ConfigError {
|
|||
/// Layer containing the duplicates.
|
||||
path: PathBuf,
|
||||
},
|
||||
/// The fully resolved model violates a configuration invariant.
|
||||
#[error("resolved configuration is invalid")]
|
||||
Validation(#[source] ConfigValidationError),
|
||||
}
|
||||
|
||||
/// A semantic invariant violated by the fully resolved configuration.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ConfigValidationError {
|
||||
/// This build supports only schema version 1.
|
||||
#[error("unsupported schema_version {actual}; expected 1")]
|
||||
UnsupportedSchema {
|
||||
/// Version found after layering.
|
||||
actual: u32,
|
||||
},
|
||||
/// A stable record ID is malformed.
|
||||
#[error("invalid {kind} ID `{id}`; expected lowercase kebab-case")]
|
||||
InvalidId {
|
||||
/// Kind of configuration record.
|
||||
kind: &'static str,
|
||||
/// Invalid stable ID.
|
||||
id: String,
|
||||
},
|
||||
/// A stable ID occurs more than once in the resolved model.
|
||||
#[error("duplicate {kind} ID `{id}`")]
|
||||
DuplicateId {
|
||||
/// Kind of configuration record.
|
||||
kind: &'static str,
|
||||
/// Repeated ID.
|
||||
id: String,
|
||||
},
|
||||
/// Two replacement rules target the same source character.
|
||||
#[error("replacement source `{character}` is configured more than once")]
|
||||
DuplicateReplacementSource {
|
||||
/// Conflicting source character.
|
||||
character: char,
|
||||
},
|
||||
/// A replacement target is empty or contains non-ASCII text.
|
||||
#[error("replacement `{id}` must have a non-empty ASCII target")]
|
||||
InvalidReplacementTarget {
|
||||
/// Replacement rule ID.
|
||||
id: String,
|
||||
},
|
||||
/// A user-facing explanatory field is empty.
|
||||
#[error("{kind} `{id}` has an empty `{field}`")]
|
||||
EmptyField {
|
||||
/// Kind of configuration record.
|
||||
kind: &'static str,
|
||||
/// Stable record ID.
|
||||
id: String,
|
||||
/// Empty field name.
|
||||
field: &'static str,
|
||||
},
|
||||
/// A heuristic weight is negative or non-finite.
|
||||
#[error("rule `{id}` has invalid weight {weight}")]
|
||||
InvalidWeight {
|
||||
/// Heuristic rule ID.
|
||||
id: String,
|
||||
/// Invalid configured weight.
|
||||
weight: f64,
|
||||
},
|
||||
/// A rule cannot contribute any occurrences.
|
||||
#[error("rule `{id}` must have an occurrence_cap greater than zero")]
|
||||
ZeroOccurrenceCap {
|
||||
/// Heuristic rule ID.
|
||||
id: String,
|
||||
},
|
||||
/// A regular expression could not be compiled.
|
||||
#[error("rule `{id}` has an invalid regular expression")]
|
||||
InvalidRegex {
|
||||
/// Heuristic rule ID.
|
||||
id: String,
|
||||
/// Regex compiler failure.
|
||||
#[source]
|
||||
source: regex::Error,
|
||||
},
|
||||
/// A matcher can succeed without consuming text.
|
||||
#[error("rule `{id}` can match empty text")]
|
||||
EmptyMatch {
|
||||
/// Heuristic rule ID.
|
||||
id: String,
|
||||
},
|
||||
/// Replacement-backed matchers must use the catalog sentinel.
|
||||
#[error("replacement rule `{id}` must use pattern `configured-replacements`")]
|
||||
InvalidReplacementMatcher {
|
||||
/// Heuristic rule ID.
|
||||
id: String,
|
||||
},
|
||||
/// A rule has no applicable content kinds.
|
||||
#[error("rule `{id}` must apply to at least one content kind")]
|
||||
EmptyScope {
|
||||
/// Heuristic rule ID.
|
||||
id: String,
|
||||
},
|
||||
/// An extension includes path/dot/case syntax instead of a normalized value.
|
||||
#[error("rule `{id}` has invalid extension `{extension}`")]
|
||||
InvalidExtension {
|
||||
/// Heuristic rule ID.
|
||||
id: String,
|
||||
/// Invalid extension value.
|
||||
extension: String,
|
||||
},
|
||||
/// Confidence thresholds are not strictly increasing.
|
||||
#[error("confidence thresholds must satisfy low < medium < high <= 100")]
|
||||
InvalidThresholds,
|
||||
/// An input resource limit is zero.
|
||||
#[error("input limit `{field}` must be greater than zero")]
|
||||
ZeroInputLimit {
|
||||
/// Zero-valued field.
|
||||
field: &'static str,
|
||||
},
|
||||
}
|
||||
|
||||
fn embedded_figment() -> Figment {
|
||||
|
|
@ -645,10 +756,179 @@ impl Default for InputLimits {
|
|||
impl Config {
|
||||
/// Load the replacement defaults embedded in this build.
|
||||
pub fn embedded() -> Self {
|
||||
embedded_figment()
|
||||
let config: Self = embedded_figment()
|
||||
.extract()
|
||||
.expect("embedded configuration must be valid")
|
||||
.expect("embedded configuration must deserialize");
|
||||
config
|
||||
.validate()
|
||||
.expect("embedded configuration must be semantically valid");
|
||||
config
|
||||
}
|
||||
|
||||
/// Check schema and semantic invariants after all layers have been applied.
|
||||
pub fn validate(&self) -> Result<(), ConfigValidationError> {
|
||||
if self.schema_version != 1 {
|
||||
return Err(ConfigValidationError::UnsupportedSchema {
|
||||
actual: self.schema_version,
|
||||
});
|
||||
}
|
||||
validate_thresholds(self.thresholds)?;
|
||||
validate_input_limits(&self.input)?;
|
||||
validate_replacements(&self.replacements)?;
|
||||
validate_rules(&self.rules)
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_thresholds(thresholds: ConfidenceThresholds) -> Result<(), ConfigValidationError> {
|
||||
if !(thresholds.low < thresholds.medium
|
||||
&& thresholds.medium < thresholds.high
|
||||
&& thresholds.high <= 100)
|
||||
{
|
||||
return Err(ConfigValidationError::InvalidThresholds);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_input_limits(input: &InputLimits) -> Result<(), ConfigValidationError> {
|
||||
for (field, value) in [
|
||||
("max_document_bytes", input.max_document_bytes),
|
||||
("max_archive_bytes", input.max_archive_bytes),
|
||||
("max_expanded_bytes", input.max_expanded_bytes),
|
||||
("max_archive_entries", input.max_archive_entries as u64),
|
||||
("max_compression_ratio", input.max_compression_ratio),
|
||||
("max_walk_depth", input.max_walk_depth as u64),
|
||||
] {
|
||||
if value == 0 {
|
||||
return Err(ConfigValidationError::ZeroInputLimit { field });
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_replacements(replacements: &[ReplacementRule]) -> Result<(), ConfigValidationError> {
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
let mut sources = std::collections::BTreeSet::new();
|
||||
for rule in replacements {
|
||||
validate_id("replacement", &rule.id)?;
|
||||
if !ids.insert(&rule.id) {
|
||||
return Err(ConfigValidationError::DuplicateId {
|
||||
kind: "replacement",
|
||||
id: rule.id.clone(),
|
||||
});
|
||||
}
|
||||
if !sources.insert(rule.source) {
|
||||
return Err(ConfigValidationError::DuplicateReplacementSource {
|
||||
character: rule.source,
|
||||
});
|
||||
}
|
||||
if rule.replacement.is_empty() || !rule.replacement.is_ascii() {
|
||||
return Err(ConfigValidationError::InvalidReplacementTarget {
|
||||
id: rule.id.clone(),
|
||||
});
|
||||
}
|
||||
require_text("replacement", &rule.id, "rationale", &rule.rationale)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_rules(rules: &[HeuristicRule]) -> Result<(), ConfigValidationError> {
|
||||
let mut ids = std::collections::BTreeSet::new();
|
||||
for rule in rules {
|
||||
validate_id("rule", &rule.id)?;
|
||||
if !ids.insert(&rule.id) {
|
||||
return Err(ConfigValidationError::DuplicateId {
|
||||
kind: "rule",
|
||||
id: rule.id.clone(),
|
||||
});
|
||||
}
|
||||
require_text("rule", &rule.id, "pattern", &rule.pattern)?;
|
||||
require_text("rule", &rule.id, "message", &rule.message)?;
|
||||
require_text("rule", &rule.id, "help", &rule.help)?;
|
||||
if !rule.weight.is_finite() || rule.weight < 0.0 {
|
||||
return Err(ConfigValidationError::InvalidWeight {
|
||||
id: rule.id.clone(),
|
||||
weight: rule.weight,
|
||||
});
|
||||
}
|
||||
if rule.occurrence_cap == 0 {
|
||||
return Err(ConfigValidationError::ZeroOccurrenceCap {
|
||||
id: rule.id.clone(),
|
||||
});
|
||||
}
|
||||
match rule.matcher {
|
||||
MatcherType::ExactPhrase => {}
|
||||
MatcherType::Regex => {
|
||||
let regex = regex::Regex::new(&rule.pattern).map_err(|source| {
|
||||
ConfigValidationError::InvalidRegex {
|
||||
id: rule.id.clone(),
|
||||
source,
|
||||
}
|
||||
})?;
|
||||
if regex.is_match("") {
|
||||
return Err(ConfigValidationError::EmptyMatch {
|
||||
id: rule.id.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
MatcherType::Replacement if rule.pattern != "configured-replacements" => {
|
||||
return Err(ConfigValidationError::InvalidReplacementMatcher {
|
||||
id: rule.id.clone(),
|
||||
});
|
||||
}
|
||||
MatcherType::Replacement => {}
|
||||
}
|
||||
if rule.scope.content.is_empty() {
|
||||
return Err(ConfigValidationError::EmptyScope {
|
||||
id: rule.id.clone(),
|
||||
});
|
||||
}
|
||||
for extension in &rule.scope.extensions {
|
||||
if extension.is_empty()
|
||||
|| !extension
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit())
|
||||
{
|
||||
return Err(ConfigValidationError::InvalidExtension {
|
||||
id: rule.id.clone(),
|
||||
extension: extension.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_id(kind: &'static str, id: &str) -> Result<(), ConfigValidationError> {
|
||||
let valid = !id.is_empty()
|
||||
&& !id.starts_with('-')
|
||||
&& !id.ends_with('-')
|
||||
&& !id.contains("--")
|
||||
&& id
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-');
|
||||
if !valid {
|
||||
return Err(ConfigValidationError::InvalidId {
|
||||
kind,
|
||||
id: id.to_owned(),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn require_text(
|
||||
kind: &'static str,
|
||||
id: &str,
|
||||
field: &'static str,
|
||||
value: &str,
|
||||
) -> Result<(), ConfigValidationError> {
|
||||
if value.trim().is_empty() {
|
||||
return Err(ConfigValidationError::EmptyField {
|
||||
kind,
|
||||
id: id.to_owned(),
|
||||
field,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
|
|
@ -847,4 +1127,47 @@ weight = 9.5
|
|||
assert_eq!(heuristic.weight, 9.5);
|
||||
assert_eq!(heuristic.matcher, MatcherType::Regex);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolved_configuration_rejects_invalid_semantics() {
|
||||
let mut config = Config::embedded();
|
||||
config.thresholds.medium = config.thresholds.low;
|
||||
assert!(matches!(
|
||||
config.validate(),
|
||||
Err(ConfigValidationError::InvalidThresholds)
|
||||
));
|
||||
|
||||
let mut config = Config::embedded();
|
||||
config.replacements[1].source = config.replacements[0].source;
|
||||
assert!(matches!(
|
||||
config.validate(),
|
||||
Err(ConfigValidationError::DuplicateReplacementSource { .. })
|
||||
));
|
||||
|
||||
let mut config = Config::embedded();
|
||||
config.replacements[0].replacement = "—".to_owned();
|
||||
assert!(matches!(
|
||||
config.validate(),
|
||||
Err(ConfigValidationError::InvalidReplacementTarget { .. })
|
||||
));
|
||||
|
||||
let mut config = Config::embedded();
|
||||
config.rules[0].weight = f64::NAN;
|
||||
assert!(matches!(
|
||||
config.validate(),
|
||||
Err(ConfigValidationError::InvalidWeight { .. })
|
||||
));
|
||||
|
||||
let mut config = Config::embedded();
|
||||
let regex_rule = config
|
||||
.rules
|
||||
.iter_mut()
|
||||
.find(|rule| rule.matcher == MatcherType::Regex)
|
||||
.unwrap();
|
||||
regex_rule.pattern = "(".to_owned();
|
||||
assert!(matches!(
|
||||
config.validate(),
|
||||
Err(ConfigValidationError::InvalidRegex { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,8 +14,8 @@ mod replacement;
|
|||
|
||||
pub use config::{
|
||||
ConfidenceThresholds, Config, ConfigError, ConfigLoader, ConfigName, ConfigNameError,
|
||||
ConfigOverrides, ConfigPaths, ContentKind, HeuristicRule, InputLimits, InputOverrides,
|
||||
MatcherType, ReplacementRule, RuleScope, ThresholdOverrides,
|
||||
ConfigOverrides, ConfigPaths, ConfigValidationError, ContentKind, HeuristicRule, InputLimits,
|
||||
InputOverrides, MatcherType, ReplacementRule, RuleScope, ThresholdOverrides,
|
||||
};
|
||||
pub use error::{InputError, InputResult};
|
||||
pub use input::{Document, Documents};
|
||||
|
|
|
|||
2
tasks.md
2
tasks.md
|
|
@ -92,7 +92,7 @@ entry do not discard successful documents.
|
|||
non-ASCII characters. Resolve the user path with platform APIs.
|
||||
- [x] Implement merge-by-ID for rule/replacement tables rather than allowing
|
||||
positional array replacement to produce surprising partial configuration.
|
||||
- [ ] Validate the fully resolved model: schema version, unique IDs/sources,
|
||||
- [x] Validate the fully resolved model: schema version, unique IDs/sources,
|
||||
ASCII-only replacement targets, regex compilation, finite non-negative weights,
|
||||
ordered thresholds, safe matchers, and edit conflicts.
|
||||
- [ ] Preserve enough provider metadata to identify the offending file and key in
|
||||
|
|
|
|||
Loading…
Reference in New Issue