|
| 1 | +use std::fmt::{Display, Write}; |
| 2 | + |
| 3 | +pub use stackable_operator_derive::Fragment; |
| 4 | + |
| 5 | +use super::merge::Atomic; |
| 6 | + |
| 7 | +use snafu::Snafu; |
| 8 | + |
| 9 | +pub struct Validator<'a> { |
| 10 | + ident: Option<&'a str>, |
| 11 | + parent: Option<&'a Validator<'a>>, |
| 12 | +} |
| 13 | + |
| 14 | +impl<'a> Validator<'a> { |
| 15 | + pub fn field<'b>(&'b self, ident: &'b str) -> Validator<'b> { |
| 16 | + Validator { |
| 17 | + ident: Some(ident), |
| 18 | + parent: Some(self), |
| 19 | + } |
| 20 | + } |
| 21 | + |
| 22 | + fn error_problem(self, problem: ValidationProblem) -> ValidationError { |
| 23 | + let mut idents = Vec::new(); |
| 24 | + let mut curr = Some(&self); |
| 25 | + while let Some(curr_some) = curr { |
| 26 | + if let Some(ident) = curr_some.ident { |
| 27 | + idents.push(ident.to_string()); |
| 28 | + } |
| 29 | + curr = curr_some.parent; |
| 30 | + } |
| 31 | + ValidationError { |
| 32 | + path: FieldPath { idents }, |
| 33 | + problem, |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + pub fn error_required(self) -> ValidationError { |
| 38 | + self.error_problem(ValidationProblem::FieldRequired) |
| 39 | + } |
| 40 | +} |
| 41 | + |
| 42 | +#[derive(Debug)] |
| 43 | +struct FieldPath { |
| 44 | + idents: Vec<String>, |
| 45 | +} |
| 46 | +impl Display for FieldPath { |
| 47 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 48 | + for (i, ident) in self.idents.iter().rev().enumerate() { |
| 49 | + if i > 0 { |
| 50 | + f.write_char('.')?; |
| 51 | + } |
| 52 | + f.write_str(ident)?; |
| 53 | + } |
| 54 | + Ok(()) |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +#[derive(Debug, Snafu)] |
| 59 | +#[snafu(display("failed to validate {path}"))] |
| 60 | +pub struct ValidationError { |
| 61 | + path: FieldPath, |
| 62 | + #[snafu(source)] |
| 63 | + problem: ValidationProblem, |
| 64 | +} |
| 65 | +#[derive(Debug, Snafu)] |
| 66 | +enum ValidationProblem { |
| 67 | + #[snafu(display("field is required"))] |
| 68 | + FieldRequired, |
| 69 | +} |
| 70 | + |
| 71 | +pub trait FromFragment: Sized { |
| 72 | + type Fragment; |
| 73 | + |
| 74 | + fn from_fragment( |
| 75 | + fragment: Self::Fragment, |
| 76 | + validator: Validator, |
| 77 | + ) -> Result<Self, ValidationError>; |
| 78 | + |
| 79 | + fn default_fragment() -> Option<Self::Fragment>; |
| 80 | +} |
| 81 | +impl<T: Atomic> FromFragment for T { |
| 82 | + type Fragment = T; |
| 83 | + |
| 84 | + fn from_fragment( |
| 85 | + fragment: Self::Fragment, |
| 86 | + _validator: Validator, |
| 87 | + ) -> Result<Self, ValidationError> { |
| 88 | + Ok(fragment) |
| 89 | + } |
| 90 | + |
| 91 | + fn default_fragment() -> Option<Self::Fragment> { |
| 92 | + None |
| 93 | + } |
| 94 | +} |
| 95 | + |
| 96 | +pub fn validate<T: FromFragment>(fragment: T::Fragment) -> Result<T, ValidationError> { |
| 97 | + T::from_fragment( |
| 98 | + fragment, |
| 99 | + Validator { |
| 100 | + ident: None, |
| 101 | + parent: None, |
| 102 | + }, |
| 103 | + ) |
| 104 | +} |
| 105 | + |
| 106 | +#[cfg(test)] |
| 107 | +mod tests { |
| 108 | + use super::{validate, Fragment, FromFragment, ValidationError, Validator}; |
| 109 | + |
| 110 | + #[derive(Fragment, Debug, PartialEq, Eq)] |
| 111 | + struct Empty {} |
| 112 | + |
| 113 | + #[derive(Fragment, Debug, PartialEq, Eq)] |
| 114 | + struct WithFields { |
| 115 | + name: String, |
| 116 | + #[fragment(default = "1")] |
| 117 | + replicas: u8, |
| 118 | + #[fragment(default)] |
| 119 | + overhead: u8, |
| 120 | + tag: Option<String>, |
| 121 | + } |
| 122 | + |
| 123 | + #[derive(Fragment, Debug, PartialEq, Eq)] |
| 124 | + struct Nested { |
| 125 | + required: WithFields, |
| 126 | + optional: Option<WithFields>, |
| 127 | + } |
| 128 | + |
| 129 | + #[test] |
| 130 | + fn validate_empty() { |
| 131 | + assert_eq!(validate::<Empty>(EmptyFragment {}).unwrap(), Empty {}); |
| 132 | + } |
| 133 | + |
| 134 | + #[test] |
| 135 | + fn validate_basics() { |
| 136 | + assert_eq!( |
| 137 | + validate::<WithFields>(WithFieldsFragment { |
| 138 | + name: Some("foo".to_string()), |
| 139 | + replicas: Some(23), |
| 140 | + overhead: Some(24), |
| 141 | + tag: Some("bar".to_string()), |
| 142 | + }) |
| 143 | + .unwrap(), |
| 144 | + WithFields { |
| 145 | + name: "foo".to_string(), |
| 146 | + replicas: 23, |
| 147 | + overhead: 24, |
| 148 | + tag: Some("bar".to_string()), |
| 149 | + } |
| 150 | + ); |
| 151 | + assert_eq!( |
| 152 | + validate::<WithFields>(WithFieldsFragment { |
| 153 | + name: Some("foo".to_string()), |
| 154 | + replicas: None, |
| 155 | + overhead: None, |
| 156 | + tag: None, |
| 157 | + }) |
| 158 | + .unwrap(), |
| 159 | + WithFields { |
| 160 | + name: "foo".to_string(), |
| 161 | + replicas: 1, |
| 162 | + overhead: 0, |
| 163 | + tag: None, |
| 164 | + } |
| 165 | + ); |
| 166 | + |
| 167 | + let err = validate::<WithFields>(WithFieldsFragment { |
| 168 | + name: None, |
| 169 | + replicas: None, |
| 170 | + overhead: None, |
| 171 | + tag: None, |
| 172 | + }) |
| 173 | + .unwrap_err(); |
| 174 | + assert!(err.to_string().contains("name")); |
| 175 | + } |
| 176 | + |
| 177 | + #[test] |
| 178 | + fn validate_nested() { |
| 179 | + // required complex fields should automatically be defaulted (so that the "leaf" fields are validated immediately) |
| 180 | + let err = validate::<Nested>(NestedFragment { |
| 181 | + required: None, |
| 182 | + optional: None, |
| 183 | + }) |
| 184 | + .unwrap_err(); |
| 185 | + assert!(err.to_string().contains("required.name")); |
| 186 | + |
| 187 | + // optional complex fields should still be treated as optional if not provided |
| 188 | + let nested = validate::<Nested>(NestedFragment { |
| 189 | + required: Some(WithFieldsFragment { |
| 190 | + name: Some("name".to_string()), |
| 191 | + ..Default::default() |
| 192 | + }), |
| 193 | + optional: None, |
| 194 | + }) |
| 195 | + .unwrap(); |
| 196 | + assert_eq!(nested.optional, None); |
| 197 | + } |
| 198 | +} |
0 commit comments