Skip to main content

redup_bootstrap/
bootstrap_config.rs

1//! Конфигурация платформы.
2
3use redup_config::Config;
4
5use crate::control_config::ControlConfig;
6use crate::grpc_config::GrpcConfig;
7use crate::memory_config::MemoryConfig;
8use crate::rest_config::RestConfig;
9use crate::telemetry::{LogsConfig, MetricsConfig, TracingConfig};
10use crate::watchers_config::WatchersConfig;
11
12/// Конфигурация платформы: секция `bootstrap` общего файла или файл `Configs/Bootstrap.yaml`.
13///
14/// Секции `logs`, `metrics` и `tracing` описаны в модуле телеметрии.
15#[derive(Debug, Clone, Config)]
16pub struct BootstrapConfig {
17    /// Наблюдение за зависимостями.
18    watchers: WatchersConfig,
19    /// Управление инстансом: остановка и защита от нехватки памяти.
20    control: ControlConfig,
21    /// Память процесса: настройка системного аллокатора.
22    memory: MemoryConfig,
23    /// REST-слушатель инфраструктурных путей. Нет секции — слушатель выключен.
24    rest: Option<RestConfig>,
25    /// gRPC-слушатель и клиенты. Нет секции — слушатель выключен, клиенты с умолчаниями.
26    grpc: Option<GrpcConfig>,
27    /// Журнал службы.
28    logs: LogsConfig,
29    /// Метрики службы.
30    metrics: MetricsConfig,
31    /// Трассировка: экспорт отрезков в коллектор.
32    tracing: TracingConfig,
33}
34
35impl Default for BootstrapConfig {
36    fn default() -> Self {
37        Self {
38            watchers: WatchersConfig::default(),
39            control: ControlConfig::default(),
40            memory: MemoryConfig::default(),
41            rest: Some(RestConfig::default()),
42            grpc: None,
43            logs: LogsConfig::default(),
44            metrics: MetricsConfig::default(),
45            tracing: TracingConfig::default(),
46        }
47    }
48}
49
50impl BootstrapConfig {
51    /// Наблюдение за зависимостями.
52    pub fn watchers(&self) -> WatchersConfig {
53        self.watchers
54    }
55
56    /// Управление инстансом.
57    pub fn control(&self) -> ControlConfig {
58        self.control
59    }
60
61    /// Память процесса.
62    pub fn memory(&self) -> MemoryConfig {
63        self.memory
64    }
65
66    /// REST-слушатель, если включён.
67    pub fn rest(&self) -> Option<&RestConfig> {
68        self.rest.as_ref()
69    }
70
71    /// gRPC-слушатель, если включён.
72    pub fn grpc(&self) -> Option<&GrpcConfig> {
73        self.grpc.as_ref()
74    }
75
76    /// Журнал службы.
77    pub fn logs(&self) -> LogsConfig {
78        self.logs
79    }
80
81    /// Метрики службы.
82    pub fn metrics(&self) -> &MetricsConfig {
83        &self.metrics
84    }
85
86    /// Трассировка.
87    pub fn tracing(&self) -> &TracingConfig {
88        &self.tracing
89    }
90}
91
92#[cfg(test)]
93mod tests {
94    use redup_bootstrap_grpc::Exposure;
95    use redup_config::{Source, load};
96
97    use super::BootstrapConfig;
98    use crate::detection::Detection;
99    use crate::watch_mode::WatchMode;
100
101    #[test]
102    fn defaults_apply_without_a_section() {
103        let config = BootstrapConfig::default();
104        assert_eq!(config.watchers().mode(), WatchMode::Once);
105        assert_eq!(config.control().drain_timeout().as_secs(), 5);
106        assert!(config.control().oom().is_none());
107        assert_eq!(config.memory().mmap_threshold(), Some(2 * 1024 * 1024));
108        let rest = config.rest().expect("the listener is on by default");
109        assert_eq!(rest.port(), 8080);
110        assert_eq!(rest.concurrent_requests_limit(), 128);
111        assert_eq!(rest.compression_threshold(), 1024);
112    }
113
114    #[test]
115    fn memory_threshold_is_disabled_by_null_in_the_common_file() {
116        let directory = tempfile::tempdir().expect("a temporary directory");
117        std::fs::write(
118            directory.path().join("config.yaml"),
119            "bootstrap:\n\
120             \x20 memory:\n\
121             \x20   mmapThreshold: ~\n",
122        )
123        .expect("the configuration file");
124        let source = Source::directory(directory.path());
125        let loaded = load::<BootstrapConfig>(&source).expect("the configuration is accepted");
126        assert_eq!(loaded.value.memory().mmap_threshold(), None);
127    }
128
129    #[test]
130    fn transcoding_section_is_read() {
131        let directory = tempfile::tempdir().expect("a temporary directory");
132        std::fs::write(
133            directory.path().join("config.yaml"),
134            "bootstrap:\n\
135             \x20 grpc:\n\
136             \x20   host: 127.0.0.1\n\
137             \x20   port: 14200\n\
138             \x20   transcoding:\n\
139             \x20     port: 18081\n\
140             \x20     enableOpenApi: false\n\
141             \x20     removeEnumPrefix: false\n\
142             \x20     errorExposure: full\n",
143        )
144        .expect("the configuration file");
145        let source = Source::directory(directory.path());
146        let loaded = load::<BootstrapConfig>(&source).expect("the configuration is accepted");
147        let grpc = loaded.value.grpc().expect("the gRPC listener");
148        let transcoding = grpc.transcoding().expect("transcoding is on");
149        assert_eq!(transcoding.port(), 18081);
150        assert!(!transcoding.enable_open_api());
151        assert!(!transcoding.remove_enum_prefix());
152        assert_eq!(transcoding.error_exposure(), Exposure::Full);
153    }
154
155    #[test]
156    fn section_is_read_from_the_common_file() {
157        let directory = tempfile::tempdir().expect("a temporary directory");
158        std::fs::write(
159            directory.path().join("config.yaml"),
160            "bootstrap:\n\
161             \x20 watchers:\n\
162             \x20   mode: startupThenObserve\n\
163             \x20   pullDelay: 3s\n\
164             \x20 control:\n\
165             \x20   drainTimeout: 12s\n\
166             \x20   oom:\n\
167             \x20     detection: boundary\n\
168             \x20 rest: ~\n",
169        )
170        .expect("the configuration file");
171        let source = Source::directory(directory.path());
172        let loaded = load::<BootstrapConfig>(&source).expect("the configuration is accepted");
173        let value = loaded.value;
174        assert_eq!(value.watchers().mode(), WatchMode::StartupThenObserve);
175        assert_eq!(value.watchers().pull_delay().as_secs(), 3);
176        assert_eq!(value.control().drain_timeout().as_secs(), 12);
177        assert_eq!(
178            value.control().oom().expect("oom is on").detection(),
179            Detection::Boundary
180        );
181        assert!(value.rest().is_none());
182    }
183}