use std::fmt;
use indexmap::IndexMap;
use serde_json::Value as Json;
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Bound {
gte: Option<f64>,
gt: Option<f64>,
lte: Option<f64>,
lt: Option<f64>,
}
impl Bound {
pub fn gte(value: f64) -> Self {
Self { gte: Some(value), ..Self::default() }
}
pub fn gt(value: f64) -> Self {
Self { gt: Some(value), ..Self::default() }
}
pub fn lte(value: f64) -> Self {
Self { lte: Some(value), ..Self::default() }
}
pub fn lt(value: f64) -> Self {
Self { lt: Some(value), ..Self::default() }
}
#[must_use]
pub fn and_gte(mut self, value: f64) -> Self {
self.gte = Some(value);
self
}
#[must_use]
pub fn and_gt(mut self, value: f64) -> Self {
self.gt = Some(value);
self
}
#[must_use]
pub fn and_lte(mut self, value: f64) -> Self {
self.lte = Some(value);
self
}
#[must_use]
pub fn and_lt(mut self, value: f64) -> Self {
self.lt = Some(value);
self
}
fn holds(self, got: f64) -> bool {
self.gte.is_none_or(|b| got >= b)
&& self.gt.is_none_or(|b| got > b)
&& self.lte.is_none_or(|b| got <= b)
&& self.lt.is_none_or(|b| got < b)
}
fn is_empty(self) -> bool {
self.gte.is_none() && self.gt.is_none() && self.lte.is_none() && self.lt.is_none()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Value {
Bool(bool),
Text(String),
Number(f64),
AnyOf(Vec<Value>),
Bound(Bound),
Nested(Condition),
Null,
}
impl From<bool> for Value {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl From<&str> for Value {
fn from(value: &str) -> Self {
Self::Text(value.to_owned())
}
}
impl From<String> for Value {
fn from(value: String) -> Self {
Self::Text(value)
}
}
impl From<Bound> for Value {
fn from(value: Bound) -> Self {
Self::Bound(value)
}
}
impl From<Condition> for Value {
fn from(value: Condition) -> Self {
Self::Nested(value)
}
}
impl<T: Into<Value>> From<Vec<T>> for Value {
fn from(value: Vec<T>) -> Self {
Self::AnyOf(value.into_iter().map(Into::into).collect())
}
}
impl<T: Into<Value>> From<Option<T>> for Value {
fn from(value: Option<T>) -> Self {
value.map_or(Self::Null, Into::into)
}
}
macro_rules! value_from_number {
($($t:ty),*) => {
$(impl From<$t> for Value {
fn from(value: $t) -> Self {
Self::Number(f64::from(value))
}
})*
};
}
value_from_number!(i8, i16, i32, u8, u16, u32, f32, f64);
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Condition(IndexMap<String, Value>);
impl Condition {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with(mut self, member: impl Into<String>, value: impl Into<Value>) -> Self {
self.0.insert(member.into(), value.into());
self
}
}
impl<K: Into<String>, V: Into<Value>, const N: usize> From<[(K, V); N]> for Condition {
fn from(entries: [(K, V); N]) -> Self {
entries.into_iter().fold(Self::new(), |c, (k, v)| c.with(k, v))
}
}
pub type Conditions = Vec<Condition>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConditionError(String);
impl ConditionError {
pub(crate) fn new(message: impl Into<String>) -> Self {
Self(message.into())
}
}
impl fmt::Display for ConditionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "internetdata: {}", self.0)
}
}
impl std::error::Error for ConditionError {}
pub fn from_json(raw: &Json) -> Result<Conditions, ConditionError> {
match raw {
Json::Array(entries) => entries.iter().map(object).collect(),
other => Ok(vec![object(other)?]),
}
}
fn object(raw: &Json) -> Result<Condition, ConditionError> {
let Json::Object(members) = raw else {
return Err(ConditionError(format!("a condition must be an object, got {raw}")));
};
members.iter().try_fold(Condition::new(), |c, (member, value)| {
Ok(c.with(member.clone(), value_from_json(value)?))
})
}
fn value_from_json(raw: &Json) -> Result<Value, ConditionError> {
Ok(match raw {
Json::Bool(value) => Value::Bool(*value),
Json::String(value) => Value::Text(value.clone()),
Json::Null => Value::Null,
Json::Number(value) => Value::Number(
value
.as_f64()
.ok_or_else(|| ConditionError(format!("{value} is not a finite number")))?,
),
Json::Array(entries) => {
Value::AnyOf(entries.iter().map(value_from_json).collect::<Result<_, _>>()?)
}
Json::Object(members) => {
if let Some(bound) = bound_from_json(members)? {
Value::Bound(bound)
} else {
Value::Nested(object(raw)?)
}
}
})
}
const BOUND_KEYS: [&str; 4] = ["gte", "gt", "lte", "lt"];
fn bound_from_json(
members: &serde_json::Map<String, Json>,
) -> Result<Option<Bound>, ConditionError> {
if members.is_empty() || !members.keys().all(|k| BOUND_KEYS.contains(&k.as_str())) {
return Ok(None);
}
let mut bound = Bound::default();
for (key, value) in members {
let n = value
.as_f64()
.ok_or_else(|| ConditionError(format!("bound {key} must be a number, got {value}")))?;
bound = match key.as_str() {
"gte" => bound.and_gte(n),
"gt" => bound.and_gt(n),
"lte" => bound.and_lte(n),
_ => bound.and_lt(n),
};
}
Ok(Some(bound))
}
pub(crate) fn matches(conditions: &[Condition], answer: &Json) -> bool {
conditions.iter().any(|one| matches_object(one, Some(answer)))
}
pub(crate) fn missing_members(conditions: &[Condition], answer: &Json) -> Vec<String> {
let mut missing: Vec<String> = Vec::new();
for one in conditions {
collect_missing(one, answer, "", &mut missing);
}
missing
}
fn collect_missing(condition: &Condition, served: &Json, prefix: &str, missing: &mut Vec<String>) {
for (member, want) in &condition.0 {
if constraints(want) == 0 {
continue;
}
let path = format!("{prefix}{member}");
let Some(got) = served.get(member).filter(|got| !got.is_null()) else {
if !missing.contains(&path) {
missing.push(path);
}
continue;
};
if let (Value::Nested(nested), Some(object)) = (want, got.as_object()) {
if !object.is_empty() {
collect_missing(nested, got, &format!("{path}."), missing);
}
}
}
}
pub(crate) fn validate(conditions: &[Condition]) -> Result<(), ConditionError> {
for one in conditions {
if one.0.values().map(constraints).sum::<usize>() == 0 {
return Err(ConditionError(format!(
"block condition {one:?} constrains nothing, which would block every request; \
a member set to false or null is ignored, so state the positive signals you \
act on"
)));
}
}
Ok(())
}
fn constraints(value: &Value) -> usize {
match value {
Value::Null | Value::Bool(false) => 0,
Value::AnyOf(entries) => entries.iter().map(constraints).sum(),
Value::Nested(nested) => nested.0.values().map(constraints).sum(),
Value::Bound(bound) => usize::from(!bound.is_empty()),
_ => 1,
}
}
fn matches_object(condition: &Condition, value: Option<&Json>) -> bool {
condition.0.iter().all(|(member, want)| {
constraints(want) == 0 || matches_value(want, value.and_then(|v| v.get(member)))
})
}
fn matches_value(want: &Value, got: Option<&Json>) -> bool {
match want {
Value::AnyOf(entries) => entries.iter().any(|entry| matches_value(entry, got)),
Value::Nested(nested) => got.is_some() && matches_object(nested, got),
Value::Bound(bound) => got.and_then(Json::as_f64).is_some_and(|n| bound.holds(n)),
Value::Text(text) => {
got.and_then(Json::as_str).is_some_and(|s| s.eq_ignore_ascii_case(text))
}
Value::Bool(value) => got.and_then(Json::as_bool) == Some(*value),
Value::Number(value) => got.and_then(Json::as_f64) == Some(*value),
Value::Null => false,
}
}