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