use std::fmt;
use chrono::Local;
use indexmap::IndexMap;
use crate::error::{Error, Result};
use crate::media::{normalize_image_src, normalize_watermark};
use crate::pyops;
use crate::value::Value;
pub const DEFAULT_MAX_ROWS: usize = 1_000_000;
pub const DEFAULT_MAX_BYTES: usize = 64 * 1024 * 1024;
const LIMIT_KEYS: [&str; 2] = ["max_rows", "max_bytes"];
const META_KEYS: [&str; 16] = [
"title",
"sub_title",
"company",
"mode",
"page",
"locale",
"direction",
"currency",
"accent_color",
"logo",
"watermark",
"printed_at",
"summary_side",
"source_note",
"empty_text",
"limits",
];
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Limits {
pub max_rows: Option<usize>,
pub max_bytes: Option<usize>,
}
impl Limits {
pub fn defaults() -> Self {
Self {
max_rows: Some(DEFAULT_MAX_ROWS),
max_bytes: Some(DEFAULT_MAX_BYTES),
}
}
pub fn none() -> Self {
Self::default()
}
pub fn is_empty(&self) -> bool {
self.max_rows.is_none() && self.max_bytes.is_none()
}
pub fn tightened_with(self, other: Limits) -> Self {
Self {
max_rows: merge_limit(self.max_rows, other.max_rows),
max_bytes: merge_limit(self.max_bytes, other.max_bytes),
}
}
pub fn to_value(self) -> Value {
let mut object = IndexMap::new();
if let Some(value) = self.max_rows {
object.insert("max_rows".to_string(), Value::UInt(value as u64));
}
if let Some(value) = self.max_bytes {
object.insert("max_bytes".to_string(), Value::UInt(value as u64));
}
Value::Object(object)
}
}
fn merge_limit(left: Option<usize>, right: Option<usize>) -> Option<usize> {
match (left, right) {
(Some(left), Some(right)) => Some(left.min(right)),
(Some(value), None) | (None, Some(value)) => Some(value),
(None, None) => None,
}
}
#[derive(Debug, Clone, Default)]
pub struct Meta {
object: IndexMap<String, Value>,
}
impl Meta {
pub fn from_object(object: IndexMap<String, Value>) -> Self {
Self { object }
}
pub fn as_object(&self) -> &IndexMap<String, Value> {
&self.object
}
pub fn to_value(&self) -> Value {
Value::Object(self.object.clone())
}
pub fn get(&self, key: &str) -> Option<&Value> {
self.object.get(key)
}
pub fn set(&mut self, key: impl Into<String>, value: impl Into<Value>) {
self.object.insert(key.into(), value.into());
}
pub fn title(&self) -> Option<&str> {
self.get("title").and_then(Value::as_str)
}
pub fn sub_title(&self) -> Option<&str> {
self.get("sub_title").and_then(Value::as_str)
}
pub fn company(&self) -> Option<&str> {
self.get("company").and_then(Value::as_str)
}
pub fn mode(&self) -> Option<&str> {
self.get("mode").and_then(Value::as_str)
}
pub fn locale(&self) -> String {
self.get("locale").and_then(Value::as_str).unwrap_or("pt-BR").to_string()
}
pub fn direction(&self) -> &str {
self.get("direction").and_then(Value::as_str).unwrap_or("ltr")
}
pub fn currency(&self) -> Option<&str> {
self.get("currency").and_then(Value::as_str)
}
pub fn accent_color(&self) -> Option<&str> {
self.get("accent_color").and_then(Value::as_str)
}
pub fn logo(&self) -> Option<&str> {
self.get("logo").and_then(Value::as_str)
}
pub fn watermark(&self) -> Option<&Value> {
self.get("watermark").filter(|value| !value.is_null())
}
pub fn page(&self) -> Option<&IndexMap<String, Value>> {
self.get("page").and_then(Value::as_object)
}
pub fn printed_at_text(&self) -> Option<String> {
self.get("printed_at").filter(|value| !value.is_null()).map(pyops::py_str)
}
pub fn summary_side(&self) -> Option<&str> {
self.get("summary_side").and_then(Value::as_str)
}
pub fn source_note(&self) -> Option<&str> {
self.get("source_note").and_then(Value::as_str)
}
pub fn empty_text(&self) -> Option<&Value> {
self.get("empty_text")
}
pub fn limits(&self) -> Option<Limits> {
self.get("limits")
.filter(|value| !value.is_null())
.and_then(|value| normalize_limits(value).ok())
}
}
#[derive(Debug, Clone)]
pub struct Payload {
pub raw: Value,
pub meta: Meta,
pub layout: Option<IndexMap<String, Value>>,
pub data: Vec<Value>,
pub sections: Option<Vec<IndexMap<String, Value>>>,
pub payload_limits: Option<Limits>,
}
#[derive(Default)]
struct Problems {
messages: Vec<String>,
total: usize,
}
impl Problems {
fn push(&mut self, path: &str, message: &str) {
self.total += 1;
if self.messages.len() < 3 {
self.messages.push(format!("{path}: {message}"));
}
}
fn finish(self) -> Result<()> {
if self.total == 0 {
return Ok(());
}
let more = if self.total > 3 {
format!(" (+{} more)", self.total - 3)
} else {
String::new()
};
let problems = if self.total == 1 { "problem" } else { "problems" };
Err(Error::payload(format!(
"Invalid payload ({} {problems}): {}{more}",
self.total,
self.messages.join("; ")
)))
}
}
pub fn type_name(value: &Value) -> &'static str {
match value {
Value::Null => "NoneType",
Value::Bool(_) => "bool",
Value::Int(_) | Value::UInt(_) => "int",
Value::Float(_) => "float",
Value::Decimal(_) => "Decimal",
Value::String(_) => "str",
Value::Date(_) => "date",
Value::DateTime(_) => "datetime",
Value::Array(_) => "list",
Value::Object(_) => "dict",
}
}
fn is_string_or_null(value: &Value) -> bool {
matches!(value, Value::String(_) | Value::Null)
}
fn validate_meta(meta: &Value, problems: &mut Problems) {
if meta.is_null() {
return;
}
let Some(object) = meta.as_object() else {
problems.push("meta", "Input should be a valid dictionary or instance of MetaInfo");
return;
};
for (key, value) in object {
if !META_KEYS.contains(&key.as_str()) {
problems.push(&format!("meta.{key}"), "Extra inputs are not permitted");
continue;
}
let string_field = matches!(
key.as_str(),
"title" | "sub_title" | "company" | "mode" | "locale" | "currency" | "accent_color" | "logo"
);
if key == "mode" && value.is_null() {
problems.push("meta.mode", "Input should be a valid string");
} else if string_field && !is_string_or_null(value) {
problems.push(&format!("meta.{key}"), "Input should be a valid string");
}
match key.as_str() {
"page" if !value.is_null() && !value.is_object() => {
problems.push("meta.page", "Input should be a valid dictionary");
}
"direction" if !value.is_null() => match value.as_str() {
Some("ltr" | "rtl") => {}
_ => problems.push("meta.direction", "Input should be 'ltr' or 'rtl'"),
},
_ => {}
}
}
}
pub fn validate_payload_shape(payload: &Value) -> Result<()> {
let Some(object) = payload.as_object() else {
return Err(Error::payload(format!(
"Invalid payload (must be an object): {}",
type_name(payload)
)));
};
let mut problems = Problems::default();
for key in object.keys() {
if !matches!(key.as_str(), "meta" | "layout" | "data" | "sections") {
problems.push(key, "Extra inputs are not permitted");
}
}
if let Some(meta) = object.get("meta") {
validate_meta(meta, &mut problems);
}
if let Some(layout) = object.get("layout") {
if !layout.is_null() && !layout.is_object() {
problems.push("layout", "Input should be a valid dictionary");
}
}
if let Some(data) = object.get("data") {
if !data.is_array() {
problems.push("data", "Input should be a valid list");
}
}
if let Some(sections) = object.get("sections") {
if !sections.is_null() {
match sections {
Value::Array(items) => {
for (index, item) in items.iter().enumerate() {
if !item.is_object() {
problems.push(&format!("sections.{index}"), "Input should be a valid dictionary");
}
}
}
_ => problems.push("sections", "Input should be a valid list"),
}
}
}
problems.finish()
}
pub fn with_meta_defaults(meta: Option<&Value>) -> Result<Meta> {
let mut object = match meta {
Some(Value::Object(object)) => object.clone(),
Some(Value::Null) | None => IndexMap::new(),
Some(_) => {
return Err(Error::payload(
"Invalid payload (1 problem): meta: Input should be a valid dictionary or instance of MetaInfo",
))
}
};
let printed_at_missing = object.get("printed_at").map(|value| !value.truthy()).unwrap_or(true);
if printed_at_missing {
object.insert(
"printed_at".to_string(),
Value::String(Local::now().format("%Y-%m-%d %H:%M").to_string()),
);
}
let direction_missing = object.get("direction").map(|value| !value.truthy()).unwrap_or(true);
if direction_missing {
object.insert("direction".to_string(), Value::String("ltr".to_string()));
}
if let Some(source_note) = object.get("source_note") {
if !source_note.is_null() {
match source_note.as_str() {
Some(text) if !text.is_empty() => {}
_ => return Err(Error::option("Invalid meta.source_note (must be a non-empty string)")),
}
}
}
if let Some(summary_side) = object.get("summary_side") {
if !summary_side.is_null() && !matches!(summary_side.as_str(), Some("top" | "bottom")) {
return Err(Error::option("Invalid meta.summary_side (expected top|bottom)"));
}
}
if let Some(logo) = object.get("logo").cloned() {
if !logo.is_null() {
let normalized = normalize_image_src(&logo, "meta.logo")?;
object.insert("logo".to_string(), Value::String(normalized));
}
}
if let Some(watermark) = object.get("watermark").cloned() {
if !watermark.is_null() {
let normalized = normalize_watermark(&watermark)?;
if let Some(watermark) = normalized {
object.insert("watermark".to_string(), watermark.to_value());
}
}
}
if let Some(limits) = object.get("limits").cloned() {
if !limits.is_null() {
let normalized = normalize_limits(&limits)?;
object.insert("limits".to_string(), normalized.to_value());
}
}
Ok(Meta::from_object(object))
}
pub fn normalize_limits(value: &Value) -> Result<Limits> {
let Some(object) = value.as_object() else {
return Err(Error::option("Invalid meta.limits (must be an object)"));
};
for key in object.keys() {
if !LIMIT_KEYS.contains(&key.as_str()) {
return Err(Error::option("Unknown meta.limits key (expected max_rows|max_bytes)"));
}
}
let mut limits = Limits::none();
for key in LIMIT_KEYS {
let Some(value) = object.get(key) else {
continue;
};
if value.is_null() {
continue;
}
let number = match value {
Value::Int(value) if *value >= 1 => *value as usize,
Value::UInt(value) if *value >= 1 => {
usize::try_from(*value).map_err(|_| Error::option(format!("Invalid meta.limits.{key} (must be a positive integer)")))?
}
_ => return Err(Error::option(format!("Invalid meta.limits.{key} (must be a positive integer)"))),
};
match key {
"max_rows" => limits.max_rows = Some(number),
"max_bytes" => limits.max_bytes = Some(number),
_ => {}
}
}
Ok(limits)
}
fn count_data_records(value: &Value) -> usize {
let mut count = 0usize;
let mut stack: Vec<&Value> = vec![value];
while let Some(node) = stack.pop() {
match node {
Value::Array(values) => stack.extend(values.iter()),
Value::Object(values) => {
count += 1;
stack.extend(values.values());
}
_ => {}
}
}
count
}
fn count_payload_records(payload: &Value) -> usize {
let Some(object) = payload.as_object() else {
return 0;
};
if object.contains_key("sections") {
let Some(sections) = object.get("sections").and_then(Value::as_array) else {
return 0;
};
let mut total = 0usize;
for section in sections {
let Some(section) = section.as_object() else {
continue;
};
let section_type = section.get("type").and_then(Value::as_str).unwrap_or("table");
match section_type {
"table" | "crosstab" => {
total += section.get("data").map(count_data_records).unwrap_or_default();
}
"kpi" => {
total += section.get("items").map(count_data_records).unwrap_or_default();
}
_ => {}
}
}
return total;
}
object.get("data").map(count_data_records).unwrap_or_default()
}
pub fn check_quotas(payload: &Value, limits: Limits) -> Result<()> {
if limits.is_empty() {
return Ok(());
}
if let Some(max_bytes) = limits.max_bytes {
let bytes = serde_json::to_vec(&payload.to_json())
.map_err(|error| Error::payload(format!("Payload is nested too deeply to measure its size: {error}")))?;
if bytes.len() > max_bytes {
return Err(Error::option(format!(
"Payload is {} bytes, exceeding the max_bytes limit ({max_bytes})",
bytes.len()
)));
}
}
if let Some(max_rows) = limits.max_rows {
let total = count_payload_records(payload);
if total > max_rows {
return Err(Error::option(format!(
"Payload has {total} data records, exceeding the max_rows limit ({max_rows})"
)));
}
}
Ok(())
}
pub fn normalize_payload(payload: &Value, operator_limits: Option<Limits>) -> Result<Payload> {
validate_payload_shape(payload)?;
let object = payload.as_object().expect("validated object");
let meta = with_meta_defaults(object.get("meta"))?;
let payload_limits = meta.limits();
let operator = operator_limits.unwrap_or_else(Limits::defaults);
let effective = operator.tightened_with(payload_limits.unwrap_or_default());
check_quotas(payload, effective)?;
let layout = object.get("layout").and_then(Value::as_object).cloned();
let data = object.get("data").and_then(Value::as_array).cloned().unwrap_or_default();
let sections = if object.contains_key("sections") {
Some(
object
.get("sections")
.and_then(Value::as_array)
.cloned()
.unwrap_or_default()
.into_iter()
.filter_map(|section| section.as_object().cloned())
.collect(),
)
} else {
None
};
Ok(Payload {
raw: payload.clone(),
meta,
layout,
data,
sections,
payload_limits,
})
}
impl fmt::Display for Limits {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
formatter,
"Limits {{ max_rows: {:?}, max_bytes: {:?} }}",
self.max_rows, self.max_bytes
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn value(value: serde_json::Value) -> Value {
Value::from_json(value)
}
#[test]
fn rejects_unknown_top_level_keys() {
let error = normalize_payload(&value(json!({"meta": {"title": "T"}, "data": [], "bogus": 1})), None).unwrap_err();
assert!(error.to_string().contains("Invalid payload"));
assert!(error.to_string().contains("bogus"));
}
#[test]
fn rejects_unknown_meta_keys_and_mistyped_values() {
let error = normalize_payload(&value(json!({"meta": {"title": "T", "bogus": 1}, "data": []})), None).unwrap_err();
assert!(error.to_string().contains("meta.bogus"));
let error = normalize_payload(&value(json!({"meta": {"title": 123}, "data": []})), None).unwrap_err();
assert!(error.to_string().contains("meta.title"));
}
#[test]
fn fills_printed_at_and_direction() {
let payload = normalize_payload(&value(json!({"meta": {"title": "T"}, "data": []})), None).unwrap();
assert!(payload.meta.get("printed_at").is_some());
assert_eq!(payload.meta.direction(), "ltr");
}
#[test]
fn quotas_only_tighten() {
let payload = value(json!({
"meta": {"title": "T", "limits": {"max_rows": 100}},
"data": [{"a": 1}, {"a": 2}]
}));
let error = normalize_payload(
&payload,
Some(Limits {
max_rows: Some(1),
max_bytes: None,
}),
)
.unwrap_err();
assert!(error.to_string().contains("max_rows limit (1)"));
}
#[test]
fn counts_nested_records() {
let payload = value(json!({"meta": {"title": "T"}, "data": [{"g": "x", "items": [{"a": 1}, {"a": 2}]}]}));
let error = normalize_payload(
&payload,
Some(Limits {
max_rows: Some(2),
max_bytes: None,
}),
)
.unwrap_err();
assert!(error.to_string().contains("3 data records"));
}
#[test]
fn sections_switch_the_pipeline() {
let payload = normalize_payload(&value(json!({"meta": {"title": "T"}, "sections": []})), None).unwrap();
assert!(payload.sections.is_some());
assert!(payload.data.is_empty());
}
#[test]
fn invalid_limits_fail_closed() {
for limits in [
json!("10"),
json!([10]),
json!({"max_rows": 0}),
json!({"max_rows": -1}),
json!({"max_rows": 1.5}),
json!({"max_rows": true}),
json!({"max_row": 5}),
] {
let payload = value(json!({"meta": {"title": "T", "limits": limits}, "data": []}));
assert!(normalize_payload(&payload, None).is_err());
}
}
}