use lambda_http::http::StatusCode;
use serde_json::{Map, Value};
use super::failure::{Failure, FailureKind};
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Issues(Vec<(String, bool)>);
impl Issues {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn abort(&mut self, path: &str, message: impl Into<String>) {
self.0.push((format!("{path}: {}", message.into()), true));
}
pub fn check(&mut self, path: &str, message: impl Into<String>) {
self.0.push((format!("{path}: {}", message.into()), false));
}
pub fn message(&mut self, message: impl Into<String>) {
self.0.push((message.into(), false));
}
#[must_use]
pub fn mark(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn aborted_since(&self, mark: usize) -> bool {
self.0[mark.min(self.0.len())..]
.iter()
.any(|(_, aborting)| *aborting)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn into_result(self, code: &'static str) -> Result<(), Failure> {
if self.0.is_empty() {
return Ok(());
}
let message = self
.0
.into_iter()
.map(|(text, _)| text)
.collect::<Vec<_>>()
.join("; ");
Err(Failure::new(StatusCode::BAD_REQUEST, code, message).with_kind(FailureKind::Decode))
}
}
#[must_use]
pub fn type_name(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
fn wrong_type<T>(
expected: &str,
value: Option<&Value>,
path: &str,
issues: &mut Issues,
) -> Option<T> {
let message = match value {
None => "is required".to_owned(),
Some(value) => format!("expected {expected}, got {}", type_name(value)),
};
issues.abort(path, message);
None
}
fn counted(count: usize, noun: &str) -> String {
if count == 1 {
format!("{count} {noun}")
} else {
format!("{count} {noun}s")
}
}
#[must_use]
pub fn join(path: &str, key: &str) -> String {
if path.is_empty() {
key.to_owned()
} else {
format!("{path}.{key}")
}
}
pub fn check_unknown_keys(
object: &Map<String, Value>,
allowed: &[&str],
path: &str,
issues: &mut Issues,
) {
let unknown: Vec<&str> = object
.keys()
.map(String::as_str)
.filter(|key| !allowed.contains(key))
.collect();
check_unknown_keys_in(&unknown, path, issues);
}
pub fn check_unknown_keys_in(unknown: &[&str], path: &str, issues: &mut Issues) {
if unknown.is_empty() {
return;
}
let quoted: Vec<String> = unknown.iter().map(|key| format!("\"{key}\"")).collect();
let noun = if unknown.len() == 1 {
"field"
} else {
"fields"
};
issues.abort(path, format!("unknown {noun} {}", quoted.join(", ")));
}
pub fn expect_object<'a>(
value: Option<&'a Value>,
path: &str,
issues: &mut Issues,
) -> Option<&'a Map<String, Value>> {
match value {
Some(Value::Object(object)) => Some(object),
other => wrong_type("object", other, path, issues),
}
}
pub fn expect_string<'a>(
value: Option<&'a Value>,
path: &str,
issues: &mut Issues,
) -> Option<&'a str> {
match value {
Some(Value::String(text)) => Some(text),
other => wrong_type("string", other, path, issues),
}
}
pub fn expect_string_min<'a>(
value: Option<&'a Value>,
path: &str,
min: usize,
issues: &mut Issues,
) -> Option<&'a str> {
let text = expect_string(value, path, issues)?;
if text.encode_utf16().count() < min {
issues.check(
path,
format!("must be at least {} long", counted(min, "character")),
);
}
Some(text)
}
#[derive(Debug, Default, Clone, Copy, PartialEq)]
pub struct NumberRule {
pub int: bool,
pub min: Option<f64>,
pub positive: bool,
pub max: Option<f64>,
}
impl NumberRule {
#[must_use]
pub const fn int() -> Self {
Self {
int: true,
min: None,
positive: false,
max: None,
}
}
#[must_use]
pub const fn int_between(min: f64, max: f64) -> Self {
Self {
int: true,
min: Some(min),
positive: false,
max: Some(max),
}
}
}
pub fn expect_number(
value: Option<&Value>,
path: &str,
rule: &NumberRule,
issues: &mut Issues,
) -> Option<f64> {
let number = match value {
Some(Value::Number(number)) => number.as_f64().unwrap_or(f64::NAN),
other => return wrong_type("number", other, path, issues),
};
check_number(number, path, rule, issues).then_some(number)
}
pub fn check_number(number: f64, path: &str, rule: &NumberRule, issues: &mut Issues) -> bool {
if rule.int && number.fract() != 0.0 {
issues.abort(path, "must be an integer");
return false;
}
if !number.is_finite() {
issues.abort(path, "must be a finite number");
return false;
}
if rule.positive && number <= 0.0 {
issues.check(path, "must be greater than 0");
} else if let Some(min) = rule.min.filter(|min| number < *min) {
issues.check(path, format!("must be at least {min}"));
} else if let Some(max) = rule.max.filter(|max| number > *max) {
issues.check(path, format!("must be at most {max}"));
}
true
}
pub fn expect_bool(value: Option<&Value>, path: &str, issues: &mut Issues) -> Option<bool> {
match value {
Some(Value::Bool(flag)) => Some(*flag),
other => wrong_type("boolean", other, path, issues),
}
}
pub fn expect_array<'a>(
value: Option<&'a Value>,
path: &str,
issues: &mut Issues,
) -> Option<&'a [Value]> {
match value {
Some(Value::Array(items)) => Some(items),
other => wrong_type("array", other, path, issues),
}
}
pub fn check_array_size(
len: usize,
path: &str,
min: Option<usize>,
max: Option<usize>,
issues: &mut Issues,
) {
if let Some(min) = min.filter(|min| len < *min) {
issues.check(path, format!("must have at least {}", counted(min, "item")));
} else if let Some(max) = max.filter(|max| len > *max) {
issues.check(path, format!("must have at most {}", counted(max, "item")));
}
}