Skip to main content

redup_bootstrap/
error.rs

1//! Ошибки сборки и запуска инстанса.
2
3use std::fmt;
4
5use redup_config::Problems;
6
7/// Ошибка точки жизненного цикла модуля: любая ошибка модуля с текстом на английском.
8pub type ModuleError = Box<dyn std::error::Error + Send + Sync + 'static>;
9
10/// Ошибка сборки и запуска инстанса.
11#[derive(Debug)]
12pub enum Error {
13    /// Конфигурацию не приняли: ошибки собраны все сразу, с путём к каждому полю.
14    Config {
15        /// Кто владеет конфигурацией: платформа или модуль.
16        owner: String,
17        /// Найденные ошибки.
18        problems: Problems,
19    },
20    /// Модуль не создался.
21    Create {
22        /// Имя модуля.
23        module: &'static str,
24        /// Ошибка, которую вернула точка создания.
25        source: ModuleError,
26    },
27    /// Модуль не запустился.
28    Start {
29        /// Имя модуля.
30        module: &'static str,
31        /// Ошибка, которую вернула точка запуска.
32        source: ModuleError,
33    },
34    /// Два модуля объявили одно имя.
35    DuplicateModule {
36        /// Повторившееся имя.
37        name: &'static str,
38    },
39    /// Обязательная связь указывает на выключенный модуль.
40    Off {
41        /// Имя выключенного модуля-поставщика.
42        module: &'static str,
43    },
44    /// Зависимость зарегистрирована неверно.
45    Dependency {
46        /// Модуль, который регистрирует зависимость.
47        module: &'static str,
48        /// Имя зависимости.
49        name: String,
50        /// Что не так.
51        reason: &'static str,
52    },
53    /// Слушатель не открылся.
54    Bind {
55        /// Адрес слушателя.
56        address: String,
57        /// Ошибка сокета.
58        source: std::io::Error,
59    },
60    /// Точка жизненного цикла инстанса вызвана не в своём состоянии.
61    State {
62        /// Действие, которое невозможно: `be started`, `be stopped`.
63        action: &'static str,
64    },
65    /// gRPC-службы не привязались или отражение не собралось.
66    Grpc {
67        /// Ошибка привязки инфраструктурных служб.
68        source: ModuleError,
69    },
70    /// REST-поверхность не собралась: маршруты, дескрипторы или общий порт.
71    Rest {
72        /// Причина.
73        source: ModuleError,
74    },
75    /// HTTP-поверхность интеграции не собралась: маршруты, порт или имя.
76    Surface {
77        /// Имя поверхности.
78        what: &'static str,
79        /// Причина.
80        reason: String,
81    },
82    /// Телеметрию не удалось завести.
83    Telemetry {
84        /// Что не удалось: `register the platform metrics`, `start the trace export`.
85        action: &'static str,
86        /// Причина.
87        source: ModuleError,
88    },
89}
90
91impl fmt::Display for Error {
92    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93        match self {
94            Self::Config { owner, problems } => {
95                write!(f, "the configuration of {owner} is rejected: {problems}")
96            }
97            Self::Create { module, source } => {
98                write!(f, "module '{module}' failed to be created: {source}")
99            }
100            Self::Start { module, source } => {
101                write!(f, "module '{module}' failed to start: {source}")
102            }
103            Self::DuplicateModule { name } => {
104                write!(f, "module name '{name}' is declared twice in the instance")
105            }
106            Self::Off { module } => write!(
107                f,
108                "module '{module}' is off: its configuration section is absent or null, \
109                 but another module requires it"
110            ),
111            Self::Dependency {
112                module,
113                name,
114                reason,
115            } => {
116                write!(f, "dependency '{module}/{name}' {reason}")
117            }
118            Self::Bind { address, source } => {
119                write!(f, "listener '{address}' failed to start: {source}")
120            }
121            Self::State { action } => {
122                write!(f, "the instance cannot {action} in its current state")
123            }
124            Self::Grpc { source } => write!(f, "the gRPC server failed to start: {source}"),
125            Self::Rest { source } => write!(f, "the REST surface failed to start: {source}"),
126            Self::Surface { what, reason } => {
127                write!(f, "the HTTP surface '{what}' failed to start: {reason}")
128            }
129            Self::Telemetry { action, source } => {
130                write!(f, "telemetry failed to {action}: {source}")
131            }
132        }
133    }
134}
135
136impl std::error::Error for Error {
137    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
138        match self {
139            Self::Config { problems, .. } => Some(problems),
140            Self::Create { source, .. }
141            | Self::Start { source, .. }
142            | Self::Grpc { source }
143            | Self::Telemetry { source, .. } => Some(source.as_ref()),
144            Self::Bind { source, .. } => Some(source),
145            _ => None,
146        }
147    }
148}
149
150#[cfg(test)]
151mod tests {
152    use super::Error;
153
154    #[test]
155    fn off_names_the_module() {
156        let error = Error::Off { module: "Storage" };
157        assert_eq!(
158            error.to_string(),
159            "module 'Storage' is off: its configuration section is absent or null, but another \
160             module requires it"
161        );
162    }
163}