Skip to main content

redup_bootstrap/
grpc_config.rs

1//! Настройки gRPC: слушатель, таймауты, сжатие, раскрытие ошибок и клиенты.
2
3use std::time::Duration;
4
5use redup_bootstrap_client::ClientConfig;
6use redup_bootstrap_grpc::{CompressionMode, Exposure};
7use redup_config::{Config, Report};
8
9/// Настройки gRPC инстанса: слушатель, умолчания вызовов, сжатие, ошибки и клиенты.
10///
11/// Нет секции — gRPC-слушатель выключен, а клиенты получают умолчания.
12#[derive(Debug, Clone, PartialEq, Eq, Config)]
13#[config(validate)]
14pub struct GrpcConfig {
15    /// Адрес, на котором слушатель принимает соединения.
16    host: String,
17    /// Порт слушателя. Ноль — свободный порт, выбранный операционной системой.
18    port: u16,
19    /// Таймаут одиночного вызова по умолчанию.
20    default_time_out: Duration,
21    /// Таймаут потока по умолчанию.
22    default_stream_time_out: Duration,
23    /// Предел одновременных вызовов одной службы. `~` — без предела. Инфраструктурные службы
24    /// предела не знают.
25    concurrent_requests_limit: Option<u32>,
26    /// Режим сжатия gRPC.
27    default_compression: CompressionMode,
28    /// Порог сжатия, в байтах: сообщения короче не сжимаются.
29    compression_threshold: u64,
30    /// Раскрытие ошибок на порту gRPC.
31    errors: ErrorConfig,
32    /// Настройки исходящих каналов.
33    client: ClientConfig,
34}
35
36/// Раскрытие ошибок: режим и включение стека.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Config)]
38pub struct ErrorConfig {
39    /// Режим раскрытия.
40    exposure: Exposure,
41    /// Передавать стек в `DebugInfo`.
42    debug_info: bool,
43}
44
45impl Default for ErrorConfig {
46    fn default() -> Self {
47        Self {
48            exposure: Exposure::default(),
49            debug_info: true,
50        }
51    }
52}
53
54impl ErrorConfig {
55    /// Режим раскрытия ошибок.
56    pub fn exposure(&self) -> Exposure {
57        self.exposure
58    }
59
60    /// Передавать ли стек.
61    pub fn debug_info(&self) -> bool {
62        self.debug_info
63    }
64}
65
66impl Default for GrpcConfig {
67    fn default() -> Self {
68        Self {
69            host: "0.0.0.0".to_owned(),
70            port: 4200,
71            default_time_out: Duration::from_secs(15),
72            default_stream_time_out: Duration::from_secs(15 * 60),
73            concurrent_requests_limit: None,
74            default_compression: CompressionMode::default(),
75            compression_threshold: 1024,
76            errors: ErrorConfig::default(),
77            client: ClientConfig::default(),
78        }
79    }
80}
81
82impl GrpcConfig {
83    /// Адрес слушателя.
84    pub fn host(&self) -> &str {
85        &self.host
86    }
87
88    /// Порт слушателя.
89    pub fn port(&self) -> u16 {
90        self.port
91    }
92
93    /// Таймаут одиночного вызова.
94    pub fn default_time_out(&self) -> Duration {
95        self.default_time_out
96    }
97
98    /// Таймаут потока.
99    pub fn default_stream_time_out(&self) -> Duration {
100        self.default_stream_time_out
101    }
102
103    /// Предел одновременных вызовов одной службы.
104    pub fn concurrent_requests_limit(&self) -> Option<u32> {
105        self.concurrent_requests_limit
106    }
107
108    /// Режим сжатия.
109    pub fn default_compression(&self) -> CompressionMode {
110        self.default_compression
111    }
112
113    /// Порог сжатия.
114    pub fn compression_threshold(&self) -> u64 {
115        self.compression_threshold
116    }
117
118    /// Настройки ошибок.
119    pub fn errors(&self) -> ErrorConfig {
120        self.errors
121    }
122
123    /// Настройки клиентов.
124    pub fn client(&self) -> &ClientConfig {
125        &self.client
126    }
127
128    fn validate(&self, report: &mut Report) {
129        if self.port > 65534 {
130            report.error("port", "The listener port must be below 65535.");
131        }
132        if self.default_time_out.is_zero() {
133            report.error("default_time_out", "The call timeout must be positive.");
134        }
135        if self.default_stream_time_out.is_zero() {
136            report.error(
137                "default_stream_time_out",
138                "The stream timeout must be positive.",
139            );
140        }
141        if self.concurrent_requests_limit == Some(0) {
142            report.error(
143                "concurrent_requests_limit",
144                "The concurrency limit must be positive; use ~ to disable it.",
145            );
146        }
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use redup_config::{Source, load};
153
154    use super::GrpcConfig;
155
156    #[test]
157    fn defaults_apply_without_a_section() {
158        let config = GrpcConfig::default();
159        assert_eq!(config.host(), "0.0.0.0");
160        assert_eq!(config.port(), 4200);
161        assert_eq!(config.default_time_out().as_secs(), 15);
162        assert_eq!(config.default_stream_time_out().as_secs(), 900);
163        assert_eq!(config.compression_threshold(), 1024);
164        assert!(config.errors().debug_info());
165    }
166
167    #[test]
168    fn section_is_read_from_the_common_file() {
169        let directory = tempfile::tempdir().expect("a temporary directory");
170        std::fs::write(
171            directory.path().join("config.yaml"),
172            "grpc:\n\
173             \x20 port: 0\n\
174             \x20 defaultTimeOut: 3s\n\
175             \x20 concurrentRequestsLimit: 8\n\
176             \x20 compressionThreshold: 2ki\n\
177             \x20 errors:\n\
178             \x20   exposure: safe\n\
179             \x20   debugInfo: false\n",
180        )
181        .expect("the configuration file");
182        let loaded = load::<GrpcConfig>(&Source::directory(directory.path()))
183            .expect("the configuration is accepted");
184        let value = loaded.value;
185        assert_eq!(value.port(), 0);
186        assert_eq!(value.default_time_out().as_secs(), 3);
187        assert_eq!(value.concurrent_requests_limit(), Some(8));
188        assert_eq!(value.compression_threshold(), 2048);
189        assert!(!value.errors().debug_info());
190    }
191
192    #[test]
193    fn zero_limit_is_rejected() {
194        let directory = tempfile::tempdir().expect("a temporary directory");
195        std::fs::write(
196            directory.path().join("config.yaml"),
197            "grpc:\n  concurrentRequestsLimit: 0\n",
198        )
199        .expect("the configuration file");
200        let problems = load::<GrpcConfig>(&Source::directory(directory.path()))
201            .expect_err("the configuration is rejected");
202        assert!(
203            problems.to_string().contains("concurrentRequestsLimit"),
204            "{problems}"
205        );
206    }
207}