validation core as a dependency2
This commit is contained in:
@@ -4,7 +4,7 @@ version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
description = "Shared validation primitives, recipes, and package metadata."
|
||||
description = "Shared validation primitives, rules, and sets."
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
|
||||
@@ -5,7 +5,7 @@ Validation is split into three ownership layers.
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Server[server<br/>stores simple settings<br/>binds table fields<br/>enforces writes]
|
||||
Core[validation-core<br/>owns meaning<br/>resolves recipes<br/>runs pure validation]
|
||||
Core[validation-core<br/>owns meaning<br/>resolves sets<br/>runs pure validation]
|
||||
Canvas[canvas<br/>editor integration<br/>masking while typing<br/>UI feedback]
|
||||
Common[common/proto<br/>wire format]
|
||||
|
||||
@@ -23,13 +23,14 @@ settings mean. `canvas` uses the resolved result for editing behavior.
|
||||
```mermaid
|
||||
flowchart TD
|
||||
Settings[ValidationSettings<br/>serializable data]
|
||||
Recipe[ValidationRecipe<br/>named reusable settings]
|
||||
Package[ValidationPackage<br/>distributable recipes]
|
||||
Rule[ValidationRule<br/>named reusable fragment]
|
||||
Set[ValidationSet<br/>ordered rules]
|
||||
Config[ValidationConfig<br/>resolved runtime config]
|
||||
Result[ValidationResult]
|
||||
|
||||
Package --> Recipe
|
||||
Recipe --> Settings
|
||||
Rule --> Settings
|
||||
Set --> Rule
|
||||
Set --> Settings
|
||||
Settings --> Config
|
||||
Config --> Result
|
||||
```
|
||||
@@ -50,30 +51,32 @@ sequenceDiagram
|
||||
Client->>Client: canvas editing, masks, errors
|
||||
```
|
||||
|
||||
## Future Package Flow
|
||||
## Set Flow
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
Registry[validation package registry]
|
||||
Package[phone package]
|
||||
Recipe[phone.e164 recipe]
|
||||
RuleA[digits-only rule]
|
||||
RuleB[phone-length rule]
|
||||
RuleC[phone-mask rule]
|
||||
Set[phone set]
|
||||
Assignment[column assignment]
|
||||
Stored[server stored settings<br/>recipe ref + resolved config]
|
||||
Stored[server stored settings<br/>set name + resolved config]
|
||||
Runtime[server/canvas runtime]
|
||||
|
||||
Registry --> Package
|
||||
Package --> Recipe
|
||||
Recipe --> Assignment
|
||||
RuleA --> Set
|
||||
RuleB --> Set
|
||||
RuleC --> Set
|
||||
Set --> Assignment
|
||||
Assignment --> Stored
|
||||
Stored --> Runtime
|
||||
```
|
||||
|
||||
The server may store both the recipe reference and the resolved settings:
|
||||
The server stores reusable rules and sets, and field application stores a
|
||||
resolved snapshot:
|
||||
|
||||
```text
|
||||
field customer_phone uses phone.e164@1.0.0
|
||||
field customer_phone uses set phone
|
||||
resolved settings = {...}
|
||||
```
|
||||
|
||||
That keeps package imports inspectable and versioned while preserving stable
|
||||
backend enforcement even if a package changes later.
|
||||
That keeps backend enforcement stable even if the reusable set changes later.
|
||||
|
||||
@@ -2,6 +2,8 @@ use crate::rules::{
|
||||
CharacterFilter, CharacterLimits, DisplayMask, PatternFilters, PositionFilter, PositionRange,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::Arc;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AllowedValues {
|
||||
@@ -60,6 +62,7 @@ pub enum CharacterFilterSettings {
|
||||
Alphanumeric,
|
||||
Exact(char),
|
||||
OneOf(Vec<char>),
|
||||
Regex(String),
|
||||
}
|
||||
|
||||
impl CharacterFilterSettings {
|
||||
@@ -70,6 +73,22 @@ impl CharacterFilterSettings {
|
||||
Self::Alphanumeric => CharacterFilter::Alphanumeric,
|
||||
Self::Exact(ch) => CharacterFilter::Exact(*ch),
|
||||
Self::OneOf(chars) => CharacterFilter::OneOf(chars.clone()),
|
||||
Self::Regex(pattern) => {
|
||||
#[cfg(feature = "regex")]
|
||||
{
|
||||
match regex::Regex::new(pattern) {
|
||||
Ok(regex) => CharacterFilter::Custom(Arc::new(move |ch| {
|
||||
regex.is_match(&ch.to_string())
|
||||
})),
|
||||
Err(_) => CharacterFilter::Custom(Arc::new(|_| false)),
|
||||
}
|
||||
}
|
||||
#[cfg(not(feature = "regex"))]
|
||||
{
|
||||
let _ = pattern;
|
||||
CharacterFilter::Custom(Arc::new(|_| false))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,6 +145,68 @@ impl ValidationSettings {
|
||||
external_validation_enabled: self.external_validation_enabled,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn merge_rules<'a>(
|
||||
rules: impl IntoIterator<Item = &'a ValidationSettings>,
|
||||
) -> Result<Self, ValidationMergeError> {
|
||||
let mut merged = ValidationSettings::default();
|
||||
|
||||
for rule in rules {
|
||||
merged.merge_rule(rule)?;
|
||||
}
|
||||
|
||||
Ok(merged)
|
||||
}
|
||||
|
||||
pub fn merge_rule(&mut self, rule: &ValidationSettings) -> Result<(), ValidationMergeError> {
|
||||
self.required |= rule.required;
|
||||
self.external_validation_enabled |= rule.external_validation_enabled;
|
||||
|
||||
merge_singleton(
|
||||
"character_limits",
|
||||
&mut self.character_limits,
|
||||
&rule.character_limits,
|
||||
)?;
|
||||
merge_singleton("allowed_values", &mut self.allowed_values, &rule.allowed_values)?;
|
||||
merge_singleton("display_mask", &mut self.display_mask, &rule.display_mask)?;
|
||||
merge_singleton("formatter", &mut self.formatter, &rule.formatter)?;
|
||||
|
||||
if let Some(pattern) = &rule.pattern {
|
||||
match &mut self.pattern {
|
||||
Some(existing) => {
|
||||
existing.filters.extend(pattern.filters.clone());
|
||||
if existing.description.is_none() {
|
||||
existing.description = pattern.description.clone();
|
||||
}
|
||||
}
|
||||
None => self.pattern = Some(pattern.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn merge_singleton<T: Clone>(
|
||||
field_name: &'static str,
|
||||
target: &mut Option<T>,
|
||||
source: &Option<T>,
|
||||
) -> Result<(), ValidationMergeError> {
|
||||
if let Some(source) = source {
|
||||
if target.is_some() {
|
||||
return Err(ValidationMergeError::DuplicateSingleton { field_name });
|
||||
}
|
||||
|
||||
*target = Some(source.clone());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error)]
|
||||
pub enum ValidationMergeError {
|
||||
#[error("validation set contains more than one rule configuring {field_name}")]
|
||||
DuplicateSingleton { field_name: &'static str },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
pub mod config;
|
||||
pub mod recipe;
|
||||
pub mod rules;
|
||||
pub mod set;
|
||||
|
||||
pub use config::{
|
||||
AllowedValues, CharacterFilterSettings, FormatterOption, FormatterSettings, PatternSettings,
|
||||
PositionFilterSettings, ValidationConfig, ValidationResult, ValidationSettings,
|
||||
};
|
||||
pub use recipe::{
|
||||
AppliedValidation, PackageId, PackageRequirement, RecipeId, RecipeReference,
|
||||
ValidationPackage, ValidationRecipe,
|
||||
PositionFilterSettings, ValidationConfig, ValidationMergeError, ValidationResult,
|
||||
ValidationSettings,
|
||||
};
|
||||
pub use rules::{
|
||||
count_text, CharacterFilter, CharacterLimits, CountMode, DisplayMask, LimitCheckResult,
|
||||
MaskDisplayMode, PatternFilters, PositionFilter, PositionRange,
|
||||
};
|
||||
pub use set::{AppliedValidation, ValidationRule, ValidationSet};
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
use crate::{ValidationConfig, ValidationSettings};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct PackageId(pub String);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct RecipeId(pub String);
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ValidationRecipe {
|
||||
pub id: RecipeId,
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub settings: ValidationSettings,
|
||||
}
|
||||
|
||||
impl ValidationRecipe {
|
||||
pub fn resolve(&self) -> ValidationConfig {
|
||||
self.settings.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ValidationPackage {
|
||||
pub id: PackageId,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
pub description: Option<String>,
|
||||
pub recipes: Vec<ValidationRecipe>,
|
||||
pub dependencies: Vec<PackageRequirement>,
|
||||
}
|
||||
|
||||
impl ValidationPackage {
|
||||
pub fn recipe(&self, id: &RecipeId) -> Option<&ValidationRecipe> {
|
||||
self.recipes.iter().find(|recipe| &recipe.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PackageRequirement {
|
||||
pub package_id: PackageId,
|
||||
pub version_requirement: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RecipeReference {
|
||||
pub package_id: PackageId,
|
||||
pub recipe_id: RecipeId,
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AppliedValidation {
|
||||
pub source: Option<RecipeReference>,
|
||||
pub settings: ValidationSettings,
|
||||
}
|
||||
|
||||
impl AppliedValidation {
|
||||
pub fn resolve(&self) -> ValidationConfig {
|
||||
self.settings.resolve()
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,26 @@ impl CharacterLimits {
|
||||
count_mode: CountMode::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create new character limits with just minimum length
|
||||
pub fn new_min(min_length: usize) -> Self {
|
||||
Self {
|
||||
max_length: None,
|
||||
min_length: Some(min_length),
|
||||
warning_threshold: None,
|
||||
count_mode: CountMode::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create new character limits with only a warning threshold.
|
||||
pub fn new_warning(threshold: usize) -> Self {
|
||||
Self {
|
||||
max_length: None,
|
||||
min_length: None,
|
||||
warning_threshold: Some(threshold),
|
||||
count_mode: CountMode::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set warning threshold (when to show warning before hitting limit)
|
||||
pub fn with_warning_threshold(mut self, threshold: usize) -> Self {
|
||||
|
||||
@@ -237,6 +237,11 @@ impl DisplayMask {
|
||||
&self.pattern
|
||||
}
|
||||
|
||||
/// Get the input placeholder character
|
||||
pub fn input_char(&self) -> char {
|
||||
self.input_char
|
||||
}
|
||||
|
||||
/// Get the position of the first input character in the pattern
|
||||
pub fn first_input_position(&self) -> usize {
|
||||
for (pos, ch) in self.pattern.chars().enumerate() {
|
||||
|
||||
118
validation-core/src/set.rs
Normal file
118
validation-core/src/set.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
use crate::{ValidationConfig, ValidationMergeError, ValidationSettings};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ValidationRule {
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub settings: ValidationSettings,
|
||||
}
|
||||
|
||||
impl ValidationRule {
|
||||
pub fn resolve(&self) -> ValidationConfig {
|
||||
self.settings.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ValidationSet {
|
||||
pub name: String,
|
||||
pub description: Option<String>,
|
||||
pub rules: Vec<ValidationRule>,
|
||||
}
|
||||
|
||||
impl ValidationSet {
|
||||
pub fn resolve_settings(&self) -> Result<ValidationSettings, ValidationMergeError> {
|
||||
ValidationSettings::merge_rules(self.rules.iter().map(|rule| &rule.settings))
|
||||
}
|
||||
|
||||
pub fn resolve(&self) -> Result<ValidationConfig, ValidationMergeError> {
|
||||
Ok(self.resolve_settings()?.resolve())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AppliedValidation {
|
||||
pub set_name: Option<String>,
|
||||
pub settings: ValidationSettings,
|
||||
}
|
||||
|
||||
impl AppliedValidation {
|
||||
pub fn resolve(&self) -> ValidationConfig {
|
||||
self.settings.resolve()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
CharacterFilterSettings, CharacterLimits, PatternSettings, PositionFilterSettings,
|
||||
PositionRange,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn validation_set_merges_rule_fragments() {
|
||||
let set = ValidationSet {
|
||||
name: "phone".to_string(),
|
||||
description: None,
|
||||
rules: vec![
|
||||
ValidationRule {
|
||||
name: "phone-length".to_string(),
|
||||
description: None,
|
||||
settings: ValidationSettings {
|
||||
character_limits: Some(CharacterLimits::new_range(10, 15)),
|
||||
..ValidationSettings::default()
|
||||
},
|
||||
},
|
||||
ValidationRule {
|
||||
name: "digits-only".to_string(),
|
||||
description: None,
|
||||
settings: ValidationSettings {
|
||||
pattern: Some(PatternSettings {
|
||||
filters: vec![PositionFilterSettings {
|
||||
positions: PositionRange::From(0),
|
||||
filter: CharacterFilterSettings::Numeric,
|
||||
}],
|
||||
description: None,
|
||||
}),
|
||||
..ValidationSettings::default()
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
let settings = set.resolve_settings().expect("set should resolve");
|
||||
|
||||
assert!(settings.character_limits.is_some());
|
||||
assert_eq!(settings.pattern.expect("pattern").filters.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_set_rejects_duplicate_singleton_rules() {
|
||||
let set = ValidationSet {
|
||||
name: "conflict".to_string(),
|
||||
description: None,
|
||||
rules: vec![
|
||||
ValidationRule {
|
||||
name: "short".to_string(),
|
||||
description: None,
|
||||
settings: ValidationSettings {
|
||||
character_limits: Some(CharacterLimits::new(10)),
|
||||
..ValidationSettings::default()
|
||||
},
|
||||
},
|
||||
ValidationRule {
|
||||
name: "long".to_string(),
|
||||
description: None,
|
||||
settings: ValidationSettings {
|
||||
character_limits: Some(CharacterLimits::new(20)),
|
||||
..ValidationSettings::default()
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
assert!(set.resolve_settings().is_err());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user