actix_settings/settings/
max_connection_rate.rs

1use std::fmt;
2
3use serde::de;
4
5use crate::{AsResult, Error, Parse};
6
7/// The maximum per-worker concurrent TLS connection limit.
8///
9/// All listeners will stop accepting connections when this limit is reached. It can be used to
10/// limit the global TLS CPU usage. By default max connections is set to a 256. Takes a string
11/// value: Either "default", or an integer N > 0 e.g. "6".
12#[derive(Debug, Clone, PartialEq, Eq, Hash)]
13pub enum MaxConnectionRate {
14    /// The default connection limit. See struct docs.
15    Default,
16
17    /// A specific connection limit.
18    Manual(usize),
19}
20
21impl Parse for MaxConnectionRate {
22    fn parse(string: &str) -> AsResult<Self> {
23        match string {
24            "default" => Ok(MaxConnectionRate::Default),
25            string => match string.parse::<usize>() {
26                Ok(val) => Ok(MaxConnectionRate::Manual(val)),
27                Err(_) => Err(InvalidValue! {
28                    expected: "an integer > 0",
29                    got: string,
30                }),
31            },
32        }
33    }
34}
35
36impl<'de> de::Deserialize<'de> for MaxConnectionRate {
37    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
38    where
39        D: de::Deserializer<'de>,
40    {
41        struct MaxConnectionRateVisitor;
42
43        impl de::Visitor<'_> for MaxConnectionRateVisitor {
44            type Value = MaxConnectionRate;
45
46            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
47                let msg = "Either \"default\" or a string containing an integer > 0";
48                f.write_str(msg)
49            }
50
51            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
52            where
53                E: de::Error,
54            {
55                match MaxConnectionRate::parse(value) {
56                    Ok(max_connection_rate) => Ok(max_connection_rate),
57                    Err(Error::InvalidValue { expected, got, .. }) => Err(
58                        de::Error::invalid_value(de::Unexpected::Str(&got), &expected),
59                    ),
60                    Err(_) => unreachable!(),
61                }
62            }
63        }
64
65        deserializer.deserialize_string(MaxConnectionRateVisitor)
66    }
67}