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
14pub(crate) type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
16
17#[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
25pub trait TypeExtractor: Clone + Debug + Send + Sync + 'static {
27 type Type: Clone + Debug + Send + Sync + Ord + 'static;
29 type Request: Send;
30
31 fn extract(&self, req: &Self::Request) -> Option<Self::Type>;
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
37pub enum ShedReason {
38 CPU,
39 Memory,
40 LoadAvg,
41 Latency,
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
46pub enum ShedResponse<T> {
47 Inner(T),
49 Overload(ShedReason),
51}
52
53#[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#[derive(Debug, Clone, Eq, PartialEq, Hash)]
65pub struct TypeLatency<T>(pub T, pub Duration);
66
67impl<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#[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#[derive(Args, Clone, Debug, PartialEq)]
98pub struct ShedSystemCli {
99 #[clap(env, long, default_value = "0.8")]
102 pub shed_system_ewma: f64,
103
104 #[clap(env, long)]
106 pub shed_system_cpu: Option<f64>,
107
108 #[clap(env, long)]
110 pub shed_system_memory: Option<f64>,
111
112 #[clap(env, long)]
114 pub shed_system_load_avg_1: Option<f64>,
115
116 #[clap(env, long)]
118 pub shed_system_load_avg_5: Option<f64>,
119
120 #[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#[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 #[clap(env, long, default_value = "0.8")]
146 pub shed_sharded_ewma: f64,
147
148 #[clap(env, long, default_value = "1000")]
151 pub shed_sharded_passthrough: u64,
152
153 #[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}