use std::collections::BTreeSet;
use std::fmt;
use serde::Serialize;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Violation {
pub path: String,
pub message: String,
pub kind: ViolationKind,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ViolationKind {
Malformed,
Constraint,
}
impl fmt::Display for Violation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.path.is_empty() {
f.write_str(&self.message)
} else {
write!(f, "{}: {}", self.path, self.message)
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rejection {
violations: Vec<Violation>,
summary: Option<String>,
}
impl Rejection {
pub fn new(violations: impl IntoIterator<Item = Violation>) -> Self {
let mut collected = Violations::default();
collected.extend(violations);
collected.finish()
}
pub fn constraint(path: impl Into<String>, message: impl Into<String>) -> Self {
Self::of(ViolationKind::Constraint, path, message)
}
pub fn malformed(path: impl Into<String>, message: impl Into<String>) -> Self {
Self::of(ViolationKind::Malformed, path, message)
}
fn of(kind: ViolationKind, path: impl Into<String>, message: impl Into<String>) -> Self {
Self {
summary: None,
violations: vec![Violation {
path: path.into(),
message: message.into(),
kind,
}],
}
}
pub(crate) fn with_summary(mut self, summary: String) -> Self {
self.summary = Some(summary);
self
}
pub fn violations(&self) -> &[Violation] {
&self.violations
}
pub fn into_violations(self) -> Vec<Violation> {
self.violations
}
pub fn is_malformed(&self) -> bool {
self.violations
.iter()
.any(|v| v.kind == ViolationKind::Malformed)
}
pub fn count(&self) -> usize {
match self.violations.split_last() {
Some((last, listed)) if listed.len() == MAX_VIOLATIONS => match unlisted(last) {
Some(unlisted) => listed.len() + unlisted,
None => self.violations.len(),
},
_ => self.violations.len(),
}
}
pub fn summary(&self) -> String {
if let Some(summary) = &self.summary {
return summary.clone();
}
match self.violations.first() {
None => "the request is invalid".to_owned(),
Some(first) => match self.count() {
0 | 1 => first.to_string(),
count => format!("{first} (and {} more)", count - 1),
},
}
}
}
const UNLISTED: &str = " more violations are not listed";
fn unlisted(violation: &Violation) -> Option<usize> {
if !violation.path.is_empty() || violation.kind != ViolationKind::Constraint {
return None;
}
violation.message.strip_suffix(UNLISTED)?.parse().ok()
}
#[derive(Debug, Default)]
pub struct Violations {
listed: Vec<Violation>,
unlisted: usize,
}
impl Violations {
pub fn is_full(&self) -> bool {
self.listed.len() >= MAX_VIOLATIONS
}
pub fn push(&mut self, violation: Violation) {
if self.is_full() {
self.unlisted += 1;
} else {
self.listed.push(violation);
}
}
pub fn push_with(&mut self, make: impl FnOnce() -> Violation) {
if self.is_full() {
self.unlisted += 1;
} else {
self.listed.push(make());
}
}
pub fn is_empty(&self) -> bool {
self.listed.is_empty()
}
pub fn listed(&self) -> &[Violation] {
&self.listed
}
pub fn into_rejection(self) -> Option<Rejection> {
(!self.is_empty()).then(|| self.finish())
}
fn finish(mut self) -> Rejection {
if self.unlisted > 0 {
self.listed.push(Violation {
path: String::new(),
message: format!("{}{UNLISTED}", self.unlisted),
kind: ViolationKind::Constraint,
});
}
Rejection {
summary: None,
violations: self.listed,
}
}
}
impl Extend<Violation> for Violations {
fn extend<I: IntoIterator<Item = Violation>>(&mut self, violations: I) {
for violation in violations {
self.push(violation);
}
}
}
impl FromIterator<Violation> for Violations {
fn from_iter<I: IntoIterator<Item = Violation>>(violations: I) -> Self {
let mut collected = Self::default();
collected.extend(violations);
collected
}
}
impl fmt::Display for Rejection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.summary())
}
}
impl std::error::Error for Rejection {}
pub trait Validate {
fn validate(&self, validator: &mut Validator);
}
impl<T: Validate> Validate for Box<T> {
fn validate(&self, validator: &mut Validator) {
(**self).validate(validator);
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Step {
Member(&'static str),
Index(usize),
Key(String),
}
impl From<&'static str> for Step {
fn from(name: &'static str) -> Self {
Self::Member(name)
}
}
impl From<usize> for Step {
fn from(index: usize) -> Self {
Self::Index(index)
}
}
impl From<&String> for Step {
fn from(key: &String) -> Self {
Self::Key(key.clone())
}
}
impl From<String> for Step {
fn from(key: String) -> Self {
Self::Key(key)
}
}
impl fmt::Display for Step {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Member(name) => f.write_str(name),
Self::Index(index) => write!(f, "{index}"),
Self::Key(key) => f.write_str(key),
}
}
}
#[derive(Default)]
pub struct Validator {
path: Steps,
violations: Violations,
sensitive: usize,
}
const HIDDEN_KEY: &str = "[key]";
pub const MAX_VIOLATIONS: usize = 100;
const INLINE_STEPS: usize = 8;
#[derive(Default)]
struct Steps {
inline: [Option<Step>; INLINE_STEPS],
len: usize,
spill: Vec<Step>,
}
impl Steps {
fn push(&mut self, step: Step) {
if self.len < INLINE_STEPS {
self.inline[self.len] = Some(step);
} else {
self.spill.push(step);
}
self.len += 1;
}
fn pop(&mut self) {
self.len -= 1;
if self.len < INLINE_STEPS {
self.inline[self.len] = None;
} else {
self.spill.pop();
}
}
fn iter(&self) -> impl Iterator<Item = &Step> {
self.inline.iter().flatten().chain(&self.spill)
}
}
impl Validator {
pub fn check<T: Validate>(value: &T) -> Result<(), Rejection> {
let mut validator = Self::default();
value.validate(&mut validator);
match validator.violations.into_rejection() {
None => Ok(()),
Some(rejection) => Err(rejection),
}
}
pub fn at(&mut self, step: impl Into<Step>, check: impl FnOnce(&mut Self)) {
let step = match step.into() {
Step::Key(_) if self.sensitive > 0 => Step::Member(HIDDEN_KEY),
step => step,
};
self.path.push(step);
check(self);
self.path.pop();
}
pub fn sensitive(&mut self, check: impl FnOnce(&mut Self)) {
self.sensitive += 1;
check(self);
self.sensitive -= 1;
}
pub fn fail(&mut self, message: impl Into<String>) {
let path = &self.path;
self.violations.push_with(|| Violation {
path: path
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("/"),
message: message.into(),
kind: ViolationKind::Constraint,
});
}
pub fn length(&mut self, length: usize, min: Option<u64>, max: Option<u64>) {
let length = length as u64;
match (min, max) {
(Some(min), Some(max)) if length < min || length > max => {
self.fail(format!("length must be between {min} and {max}, inclusive"))
}
(Some(min), None) if length < min => {
self.fail(format!("length must be at least {min}"))
}
(None, Some(max)) if length > max => self.fail(format!("length must be at most {max}")),
_ => {}
}
}
pub fn range_integer(&mut self, value: i128, min: Option<i128>, max: Option<i128>) {
if min.is_some_and(|min| value < min) || max.is_some_and(|max| value > max) {
self.fail(range_message(
min.map(|m| m.to_string()),
max.map(|m| m.to_string()),
));
}
}
pub fn range_decimal(
&mut self,
value: &crate::number::DecimalValue,
min: Option<&crate::number::DecimalValue>,
max: Option<&crate::number::DecimalValue>,
) {
if min.is_some_and(|min| value < min) || max.is_some_and(|max| value > max) {
self.fail(range_message(
min.map(ToString::to_string),
max.map(ToString::to_string),
));
}
}
pub fn range_float(&mut self, value: f64, min: Option<f64>, max: Option<f64>) {
if min.is_some_and(|min| value < min) || max.is_some_and(|max| value > max) {
self.fail(range_message(
min.map(|m| m.to_string()),
max.map(|m| m.to_string()),
));
}
}
pub fn range_float32(&mut self, value: f32, min: Option<f64>, max: Option<f64>) {
if !value.is_finite() {
self.range_float(f64::from(value), min, max);
return;
}
if min.is_some_and(|min| value < min as f32) || max.is_some_and(|max| value > max as f32) {
self.fail(range_message(
min.map(|m| m.to_string()),
max.map(|m| m.to_string()),
));
}
}
pub fn pattern(&mut self, text: &str, regex: ®ex::Regex, pattern: &str) {
if !regex.is_match(text) {
self.fail(format!("must match the pattern {pattern}"));
}
}
pub fn unique<T: Serialize>(&mut self, items: &[T]) {
let mut seen = BTreeSet::new();
for item in items {
if !seen.insert(crate::codec::key(item).unwrap_or_default()) {
self.fail("items must be unique");
return;
}
}
}
}
fn range_message(min: Option<String>, max: Option<String>) -> String {
match (min, max) {
(Some(min), Some(max)) => format!("must be between {min} and {max}, inclusive"),
(Some(min), None) => format!("must be at least {min}"),
(None, Some(max)) => format!("must be at most {max}"),
(None, None) => "is out of range".to_owned(),
}
}
#[cfg(test)]
mod tests {
use super::Validator;
#[test]
fn pattern_reports_ecma_violations_with_the_original_pattern() {
for (pattern, accepted, rejected) in [
(r"^\d+$", "12", "١٢"),
(r"^\w+$", "a_2", "é"),
(r"^a.b$", "aéb", "a\rb"),
(r"^a.b$", "aéb", "a\u{2028}b"),
(r"^\s$", "\u{feff}", "\u{85}"),
(r"\ba\b", "éaé", "bab"),
] {
let constraints = crucible_ir::ir::Constraints {
pattern: Some(pattern.into()),
..Default::default()
};
let regex = regex::Regex::new(&constraints.rust_pattern().unwrap().unwrap()).unwrap();
let mut validator = Validator::default();
validator.at("value", |v| v.pattern(accepted, ®ex, pattern));
assert!(validator.violations.listed().is_empty());
validator.at("value", |v| v.pattern(rejected, ®ex, pattern));
assert_eq!(validator.violations.listed().len(), 1);
assert_eq!(validator.violations.listed()[0].path, "value");
assert_eq!(
validator.violations.listed()[0].message,
format!("must match the pattern {pattern}")
);
}
}
#[test]
fn a_rejection_lists_at_most_max_violations_and_counts_the_rest() {
struct Items(usize);
impl super::Validate for Items {
fn validate(&self, validator: &mut Validator) {
for index in 0..self.0 {
validator.at("items", |v| v.at(index, |v| v.length(0, Some(1), None)));
}
}
}
let rejection = Validator::check(&Items(super::MAX_VIOLATIONS)).unwrap_err();
assert_eq!(rejection.violations().len(), super::MAX_VIOLATIONS);
assert_eq!(rejection.violations()[99].path, "items/99");
let rejection = Validator::check(&Items(1_000_000)).unwrap_err();
assert_eq!(rejection.violations().len(), super::MAX_VIOLATIONS + 1);
assert_eq!(rejection.violations()[0].path, "items/0");
assert_eq!(
rejection.violations()[0].message,
"length must be at least 1"
);
let last = rejection.violations().last().unwrap();
assert_eq!(last.path, "");
assert_eq!(last.message, "999900 more violations are not listed");
assert_eq!(rejection.count(), 1_000_000);
assert_eq!(
rejection.summary(),
"items/0: length must be at least 1 (and 999999 more)"
);
}
#[test]
fn map_keys_inside_a_sensitive_scope_are_not_named() {
let mut validator = Validator::default();
let key = "hunter2".to_owned();
validator.at("public", |v| v.at(&key, |v| v.fail("broken")));
validator.at("private", |v| {
v.sensitive(|v| v.at(&key, |v| v.at(3, |v| v.at("name", |v| v.fail("broken")))));
});
validator.at("after", |v| v.at(&key, |v| v.fail("broken")));
let paths: Vec<_> = validator
.violations
.listed()
.iter()
.map(|v| v.path.as_str())
.collect();
assert_eq!(
paths,
["public/hunter2", "private/[key]/3/name", "after/hunter2"]
);
}
#[test]
fn every_rejection_is_capped_and_its_summary_counts_the_unlisted() {
let violation = |index: usize| super::Violation {
path: format!("p{index}"),
message: "broken".to_owned(),
kind: super::ViolationKind::Malformed,
};
let rejection = super::Rejection::new((0..150).map(violation));
assert_eq!(rejection.violations().len(), super::MAX_VIOLATIONS + 1);
assert_eq!(rejection.count(), 150);
assert_eq!(rejection.summary(), "p0: broken (and 149 more)");
let last = rejection.violations().last().unwrap();
assert_eq!(last.message, "50 more violations are not listed");
let rejection = super::Rejection::new((0..3).map(violation));
assert_eq!(rejection.count(), 3);
assert_eq!(rejection.summary(), "p0: broken (and 2 more)");
let rejection = super::Rejection::new((0..1).map(violation));
assert_eq!(rejection.summary(), "p0: broken");
assert_eq!(
super::Rejection::new([]).summary(),
"the request is invalid"
);
let collected: super::Violations = (0..super::MAX_VIOLATIONS).map(violation).collect();
assert!(collected.is_full());
assert!(super::Violations::default().into_rejection().is_none());
}
#[test]
fn f32_range_accepts_rounded_bounds_and_rejects_adjacent_values() {
let mut validator = Validator::default();
validator.range_float32(0.1, None, Some(0.1));
validator.range_float32(0.7, Some(0.7), None);
assert!(validator.violations.listed().is_empty());
validator.range_float32(f32::from_bits(0.1f32.to_bits() + 1), None, Some(0.1));
validator.range_float32(f32::from_bits(0.7f32.to_bits() - 1), Some(0.7), None);
assert_eq!(validator.violations.listed().len(), 2);
assert_eq!(
validator.violations.listed()[0].message,
"must be at most 0.1"
);
assert_eq!(
validator.violations.listed()[1].message,
"must be at least 0.7"
);
let mut double = Validator::default();
double.range_float(f64::from_bits(0.1f64.to_bits() + 1), None, Some(0.1));
double.range_float(f64::from_bits(0.7f64.to_bits() - 1), Some(0.7), None);
assert_eq!(double.violations.listed().len(), 2);
let mut non_finite = Validator::default();
non_finite.range_float32(f32::INFINITY, None, Some(1e100));
non_finite.range_float32(f32::NEG_INFINITY, Some(-1e100), None);
assert_eq!(non_finite.violations.listed().len(), 2);
}
}