sword_layers/body_limit/
config.rs

1use byte_unit::Byte;
2use console::style;
3use serde::{Deserialize, Serialize};
4use std::str::FromStr;
5
6use crate::DisplayConfig;
7
8/// ### Body Limit Configuration
9/// Configuration for the Body Limit Layer
10/// This configuration allows you to set a maximum size for request bodies.
11///
12/// #### Fields:
13/// - `max_size`: A string representing the maximum allowed size for request bodies (e.g
14/// "1MB", "500KB").
15///
16/// - `parsed`: The parsed size in bytes (usize) derived from `max_size`.
17/// - `display`: A boolean indicating if the configuration should be displayed.
18#[derive(Debug, Clone, Serialize)]
19pub struct BodyLimitConfig {
20    pub max_size: String,
21
22    #[serde(skip)]
23    pub parsed: usize,
24
25    #[serde(default)]
26    pub display: bool,
27}
28
29impl DisplayConfig for BodyLimitConfig {
30    fn display(&self) {
31        if self.display {
32            println!("\n{}", style("Body Limit Configuration:").bold());
33            println!("  ↳  Max Body Size: {}", self.max_size);
34        }
35    }
36}
37
38impl Default for BodyLimitConfig {
39    fn default() -> Self {
40        let max_size = "10MB".to_string();
41        let parsed = Byte::from_str(&max_size)
42            .unwrap_or_else(|_| Byte::from_u64(10 * 1024 * 1024))
43            .as_u64();
44
45        BodyLimitConfig {
46            display: true,
47            max_size,
48            parsed: parsed as usize,
49        }
50    }
51}
52
53impl<'de> Deserialize<'de> for BodyLimitConfig {
54    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
55    where
56        D: serde::Deserializer<'de>,
57    {
58        use serde::de::{Error, MapAccess, Visitor};
59        use std::fmt;
60
61        struct BodyLimitVisitor;
62
63        impl<'de> Visitor<'de> for BodyLimitVisitor {
64            type Value = BodyLimitConfig;
65
66            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
67                formatter.write_str(
68                    "a map with 'enabled' (bool), 'max_size' (string), and optional 'display' (bool) fields",
69                )
70            }
71
72            // Deserialize from a map/object
73            fn visit_map<M>(self, mut map: M) -> Result<Self::Value, M::Error>
74            where
75                M: MapAccess<'de>,
76            {
77                let mut max_size = None;
78                let mut display = None;
79
80                while let Some(key) = map.next_key::<String>()? {
81                    match key.as_str() {
82                        "max_size" => max_size = Some(map.next_value()?),
83                        "display" => display = Some(map.next_value()?),
84                        _ => {
85                            let _: serde::de::IgnoredAny = map.next_value()?;
86                        }
87                    }
88                }
89
90                let max_size: String = max_size.ok_or_else(|| Error::missing_field("max_size"))?;
91
92                let parsed = Byte::from_str(&max_size)
93                    .map(|b| b.as_u64() as usize)
94                    .map_err(Error::custom)?;
95
96                Ok(BodyLimitConfig {
97                    max_size,
98                    parsed,
99                    display: display.unwrap_or_else(|| true),
100                })
101            }
102        }
103
104        deserializer.deserialize_any(BodyLimitVisitor)
105    }
106}