brinkhaustools/
app.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;

use crate::diagnosis::SelfDiagnosisEngine;
use crate::heartbeat::HeartbeatEngine;
use crate::logging::{LoggingConfig, LoggingHelper};
use crate::settings::Settings;
use crate::shutdown::ShutdownHandler;
use crate::status::{run_status_loop, StatusEngine};
use crate::version::VersionInformation;

/// Builder for constructing an [`App`] instance.
pub struct AppBuilder {
    name: String,
    settings_path: Option<PathBuf>,
    log_dir: Option<PathBuf>,
    version_file: Option<PathBuf>,
    heartbeat_timeout: Duration,
    install_signal_handlers: bool,
    #[cfg(feature = "fleet")]
    fleet_config: Option<PathBuf>,
    #[cfg(feature = "fleet")]
    fleet_group: Option<String>,
    #[cfg(feature = "fleet")]
    fleet_group_priority: Option<i64>,
    #[cfg(feature = "fleet")]
    fleet_sort_priority: Option<i64>,
    #[cfg(feature = "fleet")]
    fleet_branding: Option<String>,
}

impl AppBuilder {
    /// Set the settings file path.
    pub fn settings(mut self, path: impl Into<PathBuf>) -> Self {
        self.settings_path = Some(path.into());
        self
    }

    /// Set the log directory.
    pub fn logging(mut self, dir: impl Into<PathBuf>) -> Self {
        self.log_dir = Some(dir.into());
        self
    }

    /// Set the version file path.
    pub fn version_file(mut self, path: impl Into<PathBuf>) -> Self {
        self.version_file = Some(path.into());
        self
    }

    /// Set the heartbeat timeout.
    pub fn heartbeat_timeout(mut self, timeout: Duration) -> Self {
        self.heartbeat_timeout = timeout;
        self
    }

    /// Whether to install SIGTERM/SIGINT signal handlers.
    pub fn signal_handlers(mut self, install: bool) -> Self {
        self.install_signal_handlers = install;
        self
    }

    /// Enable FleetManager reporting from the given config file. Opt-in: if this
    /// is never called, no fleet monitor is created and nothing is sent.
    #[cfg(feature = "fleet")]
    pub fn fleet_config(mut self, path: impl Into<PathBuf>) -> Self {
        self.fleet_config = Some(path.into());
        self
    }

    /// Optional fleet supergroup (software-specific). The installation site
    /// (location/Aufstellungsort) comes from the fleet config file instead.
    #[cfg(feature = "fleet")]
    pub fn fleet_group(mut self, group: impl Into<String>) -> Self {
        self.fleet_group = Some(group.into());
        self
    }

    /// Optional group sort priority.
    #[cfg(feature = "fleet")]
    pub fn fleet_group_priority(mut self, priority: i64) -> Self {
        self.fleet_group_priority = Some(priority);
        self
    }

    /// Optional machine sort priority within the group.
    #[cfg(feature = "fleet")]
    pub fn fleet_sort_priority(mut self, priority: i64) -> Self {
        self.fleet_sort_priority = Some(priority);
        self
    }

    /// Brand this software runs under (e.g. "uttec"), sent in every heartbeat.
    /// Machine-wide identity (serial, name, stream) comes from the fleet config.
    #[cfg(feature = "fleet")]
    pub fn fleet_branding(mut self, branding: impl Into<String>) -> Self {
        self.fleet_branding = Some(branding.into());
        self
    }

    /// Build the App instance.
    pub fn build(self) -> App {
        let shutdown = ShutdownHandler::new();

        let settings = self.settings_path.map(Settings::new);

        let logging = self.log_dir.and_then(|dir| {
            LoggingHelper::new(LoggingConfig {
                log_dir: dir,
                ..Default::default()
            })
            .ok()
        });

        let diagnosis = Arc::new(SelfDiagnosisEngine::new());
        let status = Arc::new(StatusEngine::new());
        let heartbeat = Arc::new(HeartbeatEngine::new(self.heartbeat_timeout));
        let version = self.version_file.map(|p| Arc::new(VersionInformation::load(p)));

        // Register built-in status sources
        status.register_source(diagnosis.clone() as Arc<dyn crate::status::StatusSource>);
        status.register_source(heartbeat.clone() as Arc<dyn crate::status::StatusSource>);
        if let Some(ref v) = version {
            status.register_source(v.clone() as Arc<dyn crate::status::StatusSource>);
        }

        // Fleet monitor (opt-in via .fleet_config(); switchable, never forced).
        #[cfg(feature = "fleet")]
        let fleet = {
            let group = self.fleet_group.clone();
            let group_priority = self.fleet_group_priority;
            let sort_priority = self.fleet_sort_priority;
            let branding = self.fleet_branding.clone();
            self.fleet_config.map(|path| {
                let version_str = version.as_ref().map(|v| v.version().to_string());
                let monitor = Arc::new(crate::monitor::StatusMonitor::new(
                    path.to_str(),
                    Some(diagnosis.clone()),
                    &self.name,
                    version_str.as_deref(),
                    Some(shutdown.clone()),
                    Some(status.clone()),
                    group,
                    group_priority,
                    sort_priority,
                ));
                monitor.set_branding(branding);
                status.register_source(monitor.clone() as Arc<dyn crate::status::StatusSource>);
                monitor
            })
        };

        App {
            name: self.name,
            shutdown,
            settings,
            logging,
            diagnosis,
            status,
            heartbeat,
            version,
            #[cfg(feature = "fleet")]
            fleet,
        }
    }
}

/// Central wiring object connecting all infrastructure components.
///
/// Create via [`App::builder`].
pub struct App {
    pub name: String,
    pub shutdown: ShutdownHandler,
    pub settings: Option<Settings>,
    pub logging: Option<LoggingHelper>,
    pub diagnosis: Arc<SelfDiagnosisEngine>,
    pub status: Arc<StatusEngine>,
    pub heartbeat: Arc<HeartbeatEngine>,
    pub version: Option<Arc<VersionInformation>>,
    #[cfg(feature = "fleet")]
    pub fleet: Option<Arc<crate::monitor::StatusMonitor>>,
}

impl App {
    /// Create a builder for an App.
    pub fn builder(name: &str) -> AppBuilder {
        AppBuilder {
            name: name.to_string(),
            settings_path: None,
            log_dir: None,
            version_file: None,
            heartbeat_timeout: Duration::from_secs(300),
            install_signal_handlers: false,
            #[cfg(feature = "fleet")]
            fleet_config: None,
            #[cfg(feature = "fleet")]
            fleet_group: None,
            #[cfg(feature = "fleet")]
            fleet_group_priority: None,
            #[cfg(feature = "fleet")]
            fleet_sort_priority: None,
            #[cfg(feature = "fleet")]
            fleet_branding: None,
        }
    }

    /// Start all background workers (status collection, and fleet if enabled).
    pub fn start(&self) {
        run_status_loop(self.status.clone(), self.shutdown.clone());
        #[cfg(feature = "fleet")]
        if let Some(ref fleet) = self.fleet {
            crate::monitor::run_fleet_loops(fleet.clone(), self.shutdown.clone());
        }
        log::info!("App '{}' started", self.name);
    }

    /// Trigger shutdown and stop all workers.
    pub fn stop(&self) {
        self.shutdown.trigger();
        self.status.stop();
        log::info!("App '{}' stopped", self.name);
    }

    /// Block until shutdown.
    pub fn wait(&self) {
        self.shutdown.wait();
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_minimal_builder() {
        let app = App::builder("test").build();
        assert_eq!(app.name, "test");
        assert!(!app.shutdown.is_shutdown());
        assert!(app.settings.is_none());
        assert!(app.logging.is_none());
        assert!(app.version.is_none());
    }

    #[test]
    fn test_full_builder() {
        let dir = tempfile::tempdir().unwrap();
        let settings_path = dir.path().join("settings.json");
        let log_dir = dir.path().join("logs");
        let version_path = dir.path().join("version.json");

        std::fs::write(&version_path, r#"{"Version": "1.0.0"}"#).unwrap();

        let app = App::builder("full-test")
            .settings(&settings_path)
            .logging(&log_dir)
            .version_file(&version_path)
            .heartbeat_timeout(Duration::from_secs(60))
            .build();

        assert!(app.settings.is_some());
        assert!(app.logging.is_some());
        assert!(app.version.is_some());
        assert_eq!(app.version.as_ref().unwrap().version(), "1.0.0");
    }

    #[test]
    fn test_start_and_stop() {
        let app = App::builder("lifecycle-test").build();
        app.start();
        std::thread::sleep(Duration::from_millis(100));
        app.stop();
        assert!(app.shutdown.is_shutdown());
    }

    #[test]
    fn test_wait_blocks() {
        let app = App::builder("wait-test").build();
        let shutdown = app.shutdown.clone();
        std::thread::spawn(move || {
            std::thread::sleep(Duration::from_millis(100));
            shutdown.trigger();
        });
        app.wait();
        assert!(app.shutdown.is_shutdown());
    }

    #[test]
    fn test_components_wired() {
        let app = App::builder("wired-test").build();
        app.diagnosis.notify(100, "test", crate::diagnosis::Severity::Info);
        let status = app.status.collect();
        assert!(status["RunTimeTests"].is_object());
        assert!(status["Heartbeat manager"].is_object());
    }
}