Skip to main content

redup_bootstrap_client/
config.rs

1//! Настройки исходящих gRPC-каналов.
2
3use std::time::Duration;
4
5use redup_config::{Config, Report};
6
7/// Нижняя граница окна потока HTTP/2.
8const MIN_STREAM_WINDOW: u64 = 64 * 1024;
9/// Верхняя граница окна потока HTTP/2 — предел HTTP/2.
10const MAX_STREAM_WINDOW: u64 = 16 * 1024 * 1024;
11/// Нижняя граница периода keepalive: чаще шлют только нездоровые клиенты.
12const MIN_KEEP_ALIVE: Duration = Duration::from_secs(10);
13/// Период keepalive, ниже которого сервер может ответить `too_many_pings`.
14const SAFE_KEEP_ALIVE: Duration = Duration::from_secs(300);
15
16/// Настройки каналов `grpc.client`: их получает каждый клиент, созданный фабрикой.
17#[derive(Debug, Clone, PartialEq, Eq, Config)]
18#[config(validate)]
19pub struct ClientConfig {
20    /// Таймаут установки соединения. `~` — без ограничения.
21    connect_timeout: Option<Duration>,
22    /// Сколько держать простаивающее соединение. `~` — умолчание транспорта.
23    ///
24    /// Tonic не умеет закрывать простаивающие соединения сам: значение принимается, но пока не
25    /// действует.
26    idle_timeout: Option<Duration>,
27    /// Предел входящего сообщения, в байтах.
28    max_receive_message_size: u64,
29    /// Предел исходящего сообщения, в байтах. `~` — без предела.
30    max_send_message_size: Option<u64>,
31    /// Начальное окно потока HTTP/2, в байтах: 64 КиБ — 16 МиБ. `~` — умолчание транспорта.
32    ///
33    /// Увеличенное окно обходит потерю ответа при медленном чтении потока.
34    stream_window_size: Option<u64>,
35    /// Проверка живости соединения. `~` — выключена.
36    keep_alive: Option<KeepAliveConfig>,
37}
38
39impl Default for ClientConfig {
40    fn default() -> Self {
41        Self {
42            connect_timeout: Some(Duration::from_secs(15)),
43            idle_timeout: None,
44            max_receive_message_size: 1024 * 1024 * 1024,
45            max_send_message_size: None,
46            stream_window_size: Some(16 * 1024 * 1024),
47            keep_alive: None,
48        }
49    }
50}
51
52impl ClientConfig {
53    /// Таймаут установки соединения.
54    pub fn connect_timeout(&self) -> Option<Duration> {
55        self.connect_timeout
56    }
57
58    /// Сколько держать простаивающее соединение.
59    pub fn idle_timeout(&self) -> Option<Duration> {
60        self.idle_timeout
61    }
62
63    /// Предел входящего сообщения.
64    pub fn max_receive_message_size(&self) -> u64 {
65        self.max_receive_message_size
66    }
67
68    /// Предел исходящего сообщения.
69    pub fn max_send_message_size(&self) -> Option<u64> {
70        self.max_send_message_size
71    }
72
73    /// Начальное окно потока HTTP/2.
74    pub fn stream_window_size(&self) -> Option<u64> {
75        self.stream_window_size
76    }
77
78    /// Настройки keepalive.
79    pub fn keep_alive(&self) -> Option<&KeepAliveConfig> {
80        self.keep_alive.as_ref()
81    }
82
83    fn validate(&self, report: &mut Report) {
84        if let Some(window) = self.stream_window_size
85            && !(MIN_STREAM_WINDOW..=MAX_STREAM_WINDOW).contains(&window)
86        {
87            report.error(
88                "stream_window_size",
89                format!(
90                    "The stream window must be between {MIN_STREAM_WINDOW} and {MAX_STREAM_WINDOW} \
91                     bytes, got {window}."
92                ),
93            );
94        }
95        if let Some(keep_alive) = &self.keep_alive {
96            if keep_alive.ping_delay < MIN_KEEP_ALIVE {
97                report.error(
98                    "keep_alive",
99                    format!(
100                        "The keepalive period must be at least {} seconds.",
101                        MIN_KEEP_ALIVE.as_secs()
102                    ),
103                );
104            } else if keep_alive.ping_delay < SAFE_KEEP_ALIVE {
105                report.warning(
106                    "keep_alive",
107                    format!(
108                        "A keepalive period below {} minutes may make the server answer \
109                         too_many_pings.",
110                        SAFE_KEEP_ALIVE.as_secs() / 60
111                    ),
112                );
113            }
114            if keep_alive.ping_timeout.is_zero() {
115                report.error("keep_alive", "The keepalive timeout must be positive.");
116            }
117        }
118    }
119}
120
121/// Проверка живости соединения.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Config)]
123pub struct KeepAliveConfig {
124    /// Период отправки ping.
125    ping_delay: Duration,
126    /// Ожидание ответа на ping.
127    ping_timeout: Duration,
128    /// Слать ping, только когда идут запросы, или и в простое.
129    policy: KeepAlivePolicy,
130}
131
132impl Default for KeepAliveConfig {
133    fn default() -> Self {
134        Self {
135            ping_delay: Duration::from_secs(60),
136            ping_timeout: Duration::from_secs(20),
137            policy: KeepAlivePolicy::WithActiveRequests,
138        }
139    }
140}
141
142impl KeepAliveConfig {
143    /// Период отправки ping.
144    pub fn ping_delay(&self) -> Duration {
145        self.ping_delay
146    }
147
148    /// Ожидание ответа на ping.
149    pub fn ping_timeout(&self) -> Duration {
150        self.ping_timeout
151    }
152
153    /// Когда слать ping.
154    pub fn policy(&self) -> KeepAlivePolicy {
155        self.policy
156    }
157}
158
159/// Когда слать ping.
160#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Config)]
161pub enum KeepAlivePolicy {
162    /// Только когда идут запросы.
163    #[default]
164    WithActiveRequests,
165    /// И в простое.
166    WhileIdle,
167}
168
169#[cfg(test)]
170mod tests {
171    use redup_config::{Source, load};
172
173    use super::{ClientConfig, KeepAlivePolicy};
174
175    #[test]
176    fn defaults_apply_without_a_section() {
177        let config = ClientConfig::default();
178        assert_eq!(
179            config.connect_timeout(),
180            Some(std::time::Duration::from_secs(15))
181        );
182        assert_eq!(config.max_receive_message_size(), 1024 * 1024 * 1024);
183        assert_eq!(config.stream_window_size(), Some(16 * 1024 * 1024));
184        assert!(config.keep_alive().is_none());
185    }
186
187    #[test]
188    fn section_is_read_from_the_common_file() {
189        let directory = tempfile::tempdir().expect("a temporary directory");
190        std::fs::write(
191            directory.path().join("config.yaml"),
192            "client:\n\
193             \x20 connectTimeout: 3s\n\
194             \x20 streamWindowSize: 1Mi\n\
195             \x20 keepAlive:\n\
196             \x20   pingDelay: 2m\n\
197             \x20   policy: whileIdle\n",
198        )
199        .expect("the configuration file");
200        let loaded = load::<ClientConfig>(&Source::directory(directory.path()))
201            .expect("the configuration is accepted");
202        let value = loaded.value;
203        assert_eq!(
204            value.connect_timeout(),
205            Some(std::time::Duration::from_secs(3))
206        );
207        assert_eq!(value.stream_window_size(), Some(1024 * 1024));
208        let keep_alive = value.keep_alive().expect("keepalive is on");
209        assert_eq!(keep_alive.policy(), KeepAlivePolicy::WhileIdle);
210    }
211
212    #[test]
213    fn too_narrow_a_window_is_rejected() {
214        let directory = tempfile::tempdir().expect("a temporary directory");
215        std::fs::write(
216            directory.path().join("config.yaml"),
217            "client:\n  streamWindowSize: 1ki\n",
218        )
219        .expect("the configuration file");
220        let problems = load::<ClientConfig>(&Source::directory(directory.path()))
221            .expect_err("the configuration is rejected");
222        assert!(
223            problems.to_string().contains("streamWindowSize"),
224            "{problems}"
225        );
226    }
227}