Skip to main content

ic_bn_lib/http/shed/
mod.rs

1pub mod ewma;
2pub mod little;
3pub mod sharded;
4pub mod system;
5
6use anyhow::{Context, anyhow};
7use async_trait::async_trait;
8use clap::Args;
9use humantime::parse_duration;
10use std::{fmt::Debug, future::Future, pin::Pin, str::FromStr, time::Duration};
11
12use crate::http::Error;
13
14/// Boxed future, akin to futures::BoxFuture, but w/o lifetimes
15pub(crate) type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
16
17/// Trait to get system information
18#[async_trait]
19pub trait GetsSystemInfo: Send + Sync + Clone + 'static {
20    async fn cpu_usage(&self) -> Result<f64, Error>;
21    fn memory_usage(&self) -> Result<f64, Error>;
22    fn load_avg(&self) -> Result<(f64, f64, f64), Error>;
23}
24
25/// Trait to extract the shedding key from the given request
26pub trait TypeExtractor: Clone + Debug + Send + Sync + 'static {
27    /// The type of the request.
28    type Type: Clone + Debug + Send + Sync + Ord + 'static;
29    type Request: Send;
30
31    /// Extraction method, should return None response when the extraction failed
32    fn extract(&self, req: &Self::Request) -> Option<Self::Type>;
33}
34
35/// Reason for shedding
36#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
37pub enum ShedReason {
38    CPU,
39    Memory,
40    LoadAvg,
41    Latency,
42}
43
44/// Either an error from the wrapped service or message that the request was shed
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub enum ShedResponse<T> {
47    /// A response from the inner service.
48    Inner(T),
49    /// The request was shed due to overload.
50    Overload(ShedReason),
51}
52
53/// Options for system load shedder
54#[derive(Debug, Clone, Copy)]
55pub struct SystemOptions {
56    pub cpu: Option<f64>,
57    pub memory: Option<f64>,
58    pub loadavg_1: Option<f64>,
59    pub loadavg_5: Option<f64>,
60    pub loadavg_15: Option<f64>,
61}
62
63/// Request type and latency pair
64#[derive(Debug, Clone, Eq, PartialEq, Hash)]
65pub struct TypeLatency<T>(pub T, pub Duration);
66
67/// Generic parser for TypeLatency in "foo:<duration>" format.
68/// Supports anything that implements FromStr.
69impl<T: FromStr> FromStr for TypeLatency<T>
70where
71    T::Err: std::error::Error + Send + Sync + Sized + 'static,
72{
73    type Err = anyhow::Error;
74
75    fn from_str(s: &str) -> Result<Self, Self::Err> {
76        let (rtype, lat) = s
77            .split_once(":")
78            .ok_or_else(|| anyhow!("incorrect format"))?;
79
80        let rtype = T::from_str(rtype).context("unknown request type")?;
81        let lat = parse_duration(lat).context("unable to parse latency")?;
82
83        Ok(Self(rtype, lat))
84    }
85}
86
87/// Options for sharded load shedder
88#[derive(Debug, Clone)]
89pub struct ShardedOptions<T: TypeExtractor> {
90    pub extractor: T,
91    pub ewma_alpha: f64,
92    pub passthrough_count: u64,
93    pub latencies: Vec<TypeLatency<T::Type>>,
94}
95
96/// System load shedder CLI
97#[derive(Args, Clone, Debug, PartialEq)]
98pub struct ShedSystemCli {
99    /// EWMA alpha coefficient in [0.0, 1.0] range.
100    /// It represents the weight of the more recent measurements relative to the older ones.
101    #[clap(env, long, default_value = "0.8")]
102    pub shed_system_ewma: f64,
103
104    /// CPU load where to start shedding, range [0.0, 1.0]
105    #[clap(env, long)]
106    pub shed_system_cpu: Option<f64>,
107
108    /// Memory usage where to start shedding, range [0.0, 1.0]
109    #[clap(env, long)]
110    pub shed_system_memory: Option<f64>,
111
112    /// 1-minute load average where to start shedding, range [0.0, inf)
113    #[clap(env, long)]
114    pub shed_system_load_avg_1: Option<f64>,
115
116    /// 5-minute load average where to start shedding, range [0.0, inf)
117    #[clap(env, long)]
118    pub shed_system_load_avg_5: Option<f64>,
119
120    /// 15-minute load average where to start shedding, range [0.0, inf)
121    #[clap(env, long)]
122    pub shed_system_load_avg_15: Option<f64>,
123}
124
125impl From<ShedSystemCli> for SystemOptions {
126    fn from(v: ShedSystemCli) -> Self {
127        Self {
128            cpu: v.shed_system_cpu,
129            memory: v.shed_system_memory,
130            loadavg_1: v.shed_system_load_avg_1,
131            loadavg_5: v.shed_system_load_avg_5,
132            loadavg_15: v.shed_system_load_avg_15,
133        }
134    }
135}
136
137/// Sharded load shedder CLI
138#[derive(Args, Clone, Debug, PartialEq)]
139pub struct ShedShardedCli<T: FromStr + Clone + Send + Sync + 'static>
140where
141    T::Err: std::error::Error + Send + Sync + 'static,
142{
143    /// EWMA alpha coefficient in [0.0, 1.0] range.
144    /// It represents the weight of the more recent measurements relative to the older ones.
145    #[clap(env, long, default_value = "0.8")]
146    pub shed_sharded_ewma: f64,
147
148    /// Number of initial requests to allow through without shedding.
149    /// This allows for a gradual load buildup avoiding false positives.
150    #[clap(env, long, default_value = "1000")]
151    pub shed_sharded_passthrough: u64,
152
153    /// Request types and their target latency, colon separated e.g. "query:100ms".
154    /// This specifies target latency for Little's load-shedding algorithm for a given request type.
155    /// Can be specified several times.
156    /// Important: if the request type is not specified in the list then it's not shedded at all.
157    #[clap(env, long, value_delimiter = ',')]
158    pub shed_sharded_latency: Vec<TypeLatency<T>>,
159}
160
161#[cfg(test)]
162mod test {
163    use std::time::Duration;
164
165    use clap::Parser;
166
167    use crate::RequestType;
168
169    use super::*;
170
171    #[test]
172    fn test_type_latency() {
173        assert!(TypeLatency::<RequestType>::from_str("foo").is_err());
174        assert!(TypeLatency::<RequestType>::from_str(":").is_err());
175        assert!(TypeLatency::<RequestType>::from_str("foo:100ms").is_err());
176        assert!(TypeLatency::<RequestType>::from_str("query_v2:").is_err());
177        assert!(TypeLatency::<RequestType>::from_str("query_v2:1gigasecond").is_err());
178
179        assert_eq!(
180            TypeLatency::<RequestType>::from_str("query_v2:100ms").unwrap(),
181            TypeLatency::<RequestType>(RequestType::QueryV2, Duration::from_millis(100))
182        );
183
184        assert_eq!(
185            TypeLatency::<RequestType>::from_str("call_v3:1s").unwrap(),
186            TypeLatency::<RequestType>(RequestType::CallV3, Duration::from_millis(1000))
187        );
188    }
189
190    #[derive(clap::Parser)]
191    struct Cli {
192        #[command(flatten)]
193        sharded: ShedShardedCli<RequestType>,
194        #[command(flatten)]
195        system: ShedSystemCli,
196    }
197
198    #[test]
199    fn test_cli() {
200        let args: Vec<&str> = vec![];
201        Cli::parse_from(args);
202    }
203}