nginx-discovery 0.4.0

Parse, analyze, and extract information from NGINX configurations
Documentation
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Network check types and results
//!
//! This module defines the **core data structures** used by the network
//! health-checking subsystem.
//!
//! ## Scope and responsibilities
//!
//! - Types in this module are **pure data containers**
//! - No I/O, networking, async, or side effects are performed here
//! - All execution logic lives in sibling modules (e.g. `ssl`, `dns`, `upstream`)
//!
//! ## Design principles
//!
//! - All check results follow a **normalized shape**
//! - Severity and health status are explicitly modeled
//! - Structures are optimized for:
//!   - CLI output
//!   - JSON serialization
//!   - Aggregation and reporting
//!
//! This mirrors how large frameworks (e.g. Kubernetes, Django system checks)
//! separate **evaluation** from **representation**.

use std::time::Duration;

/* ============================================================
 * Health status & severity
 * ============================================================
 */

/// Overall health status of a network check.
///
/// This represents **what happened**, independent of urgency.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum HealthStatus {
    /// Check succeeded with no issues.
    Healthy,

    /// Check succeeded but non-fatal issues were detected.
    Degraded,

    /// Check failed and the system is unhealthy.
    Unhealthy,

    /// Check could not be executed due to an internal error.
    Error,

    /// Check was intentionally skipped or not applicable.
    NotApplicable,
}

impl std::fmt::Display for HealthStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Healthy => "HEALTHY",
            Self::Degraded => "DEGRADED",
            Self::Unhealthy => "UNHEALTHY",
            Self::Error => "ERROR",
            Self::NotApplicable => "N/A",
        };
        write!(f, "{s}")
    }
}

/// Severity level associated with a health-check result.
///
/// This represents **how urgent** the outcome is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CheckSeverity {
    /// Informational only; no action required.
    Info,

    /// Warning; action recommended.
    Warning,

    /// Error; action required.
    Error,

    /// Critical; immediate action required.
    Critical,
}

impl std::fmt::Display for CheckSeverity {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Info => "INFO",
            Self::Warning => "WARNING",
            Self::Error => "ERROR",
            Self::Critical => "CRITICAL",
        };
        write!(f, "{s}")
    }
}

/* ============================================================
 * Generic health check
 * ============================================================
 */

/// Normalized result type used by **all** network checks.
///
/// This type allows heterogeneous checks (SSL, DNS, ports, upstreams)
/// to be aggregated and displayed uniformly.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HealthCheckResult {
    /// Final health status.
    pub status: HealthStatus,

    /// Human-readable summary message.
    pub message: String,

    /// Severity level.
    pub severity: CheckSeverity,

    /// Optional diagnostic details.
    pub details: Option<String>,

    /// Optional latency measurement.
    pub latency: Option<Duration>,
}

impl HealthCheckResult {
    /// Create a healthy result.
    #[must_use]
    pub fn healthy(message: impl Into<String>) -> Self {
        Self {
            status: HealthStatus::Healthy,
            message: message.into(),
            severity: CheckSeverity::Info,
            details: None,
            latency: None,
        }
    }

    /// Create a degraded result.
    #[must_use]
    pub fn degraded(message: impl Into<String>) -> Self {
        Self {
            status: HealthStatus::Degraded,
            message: message.into(),
            severity: CheckSeverity::Warning,
            details: None,
            latency: None,
        }
    }

    /// Create an unhealthy result.
    #[must_use]
    pub fn unhealthy(message: impl Into<String>) -> Self {
        Self {
            status: HealthStatus::Unhealthy,
            message: message.into(),
            severity: CheckSeverity::Error,
            details: None,
            latency: None,
        }
    }

    /// Create an error result.
    #[must_use]
    pub fn error(message: impl Into<String>) -> Self {
        Self {
            status: HealthStatus::Error,
            message: message.into(),
            severity: CheckSeverity::Critical,
            details: None,
            latency: None,
        }
    }

    /// Attach diagnostic details.
    #[must_use]
    pub fn with_details(mut self, details: impl Into<String>) -> Self {
        self.details = Some(details.into());
        self
    }

    /// Attach latency information.
    #[must_use]
    pub fn with_latency(mut self, latency: Duration) -> Self {
        self.latency = Some(latency);
        self
    }
}

/* ============================================================
 * SSL check
 * ============================================================
 */

/// Result of an SSL/TLS certificate validation.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SslCheckResult {
    /// Health status of the SSL check.
    pub status: HealthStatus,

    /// Summary message.
    pub message: String,

    /// Severity level.
    pub severity: CheckSeverity,

    /// Optional diagnostic details.
    pub details: Option<String>,

    /// Certificate expiration timestamp (UTC).
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,

    /// Days remaining until certificate expiration.
    pub days_until_expiry: Option<i64>,

    /// Certificate issuer (distinguished name).
    pub issuer: Option<String>,

    /// Certificate subject (distinguished name).
    pub subject: Option<String>,
}

/* ============================================================
 * Port check
 * ============================================================
 */

/// Result of a TCP port availability check.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct PortCheckResult {
    /// Health status of the port check.
    pub status: HealthStatus,

    /// Summary message.
    pub message: String,

    /// Severity level.
    pub severity: CheckSeverity,

    /// Optional diagnostic details.
    pub details: Option<String>,

    /// Port number that was checked.
    pub port: u16,

    /// Hostname or IP address.
    pub address: String,

    /// Whether the port is accepting connections.
    pub is_listening: bool,

    /// Optional connection latency.
    pub latency: Option<Duration>,
}

/* ============================================================
 * DNS resolution
 * ============================================================
 */

/// Result of a DNS resolution check.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DnsCheckResult {
    /// Health status of the DNS check.
    pub status: HealthStatus,

    /// Summary message.
    pub message: String,

    /// Severity level.
    pub severity: CheckSeverity,

    /// Optional diagnostic details.
    pub details: Option<String>,

    /// Hostname that was resolved.
    pub hostname: String,

    /// Resolved IP addresses.
    pub addresses: Vec<String>,

    /// Time taken to resolve DNS.
    pub resolution_time: Option<Duration>,
}

/* ============================================================
 * Network execution options
 * ============================================================
 */

/// Configuration controlling which network checks are executed.
///
/// This struct is intentionally explicit rather than compact, as
/// configuration clarity is preferred over minimalism.
#[derive(Debug, Clone)]
#[allow(clippy::struct_excessive_bools)]
pub struct NetworkCheckOptions {
    /// Whether to check upstream backends.
    pub check_upstreams: bool,

    /// Whether to validate SSL certificates.
    pub check_ssl: bool,

    /// Whether to check TCP ports.
    pub check_ports: bool,

    /// Whether to perform DNS resolution.
    pub check_dns: bool,

    /// Per-check timeout.
    pub timeout: Duration,

    /// Number of retry attempts.
    pub retries: usize,

    /// Execute checks concurrently.
    pub parallel: bool,

    /// Continue executing checks after failures.
    pub continue_on_error: bool,
}

impl Default for NetworkCheckOptions {
    fn default() -> Self {
        Self {
            check_upstreams: true,
            check_ssl: true,
            check_ports: true,
            check_dns: true,
            timeout: Duration::from_secs(5),
            retries: 3,
            parallel: true,
            continue_on_error: true,
        }
    }
}

impl NetworkCheckOptions {
    /// Enable only upstream checks.
    #[must_use]
    pub fn upstreams_only() -> Self {
        Self {
            check_upstreams: true,
            check_ssl: false,
            check_ports: false,
            check_dns: false,
            ..Default::default()
        }
    }

    /// Enable only SSL checks.
    #[must_use]
    pub fn ssl_only() -> Self {
        Self {
            check_upstreams: false,
            check_ssl: true,
            check_ports: false,
            check_dns: false,
            ..Default::default()
        }
    }

    /// Enable only port checks.
    #[must_use]
    pub fn ports_only() -> Self {
        Self {
            check_upstreams: false,
            check_ssl: false,
            check_ports: true,
            check_dns: false,
            ..Default::default()
        }
    }

    /// Enable only DNS checks.
    #[must_use]
    pub fn dns_only() -> Self {
        Self {
            check_upstreams: false,
            check_ssl: false,
            check_ports: false,
            check_dns: true,
            ..Default::default()
        }
    }
}

/* ============================================================
 * DNS validation
 * ============================================================
 */

/// Result of DNS configuration validation.
///
/// This is distinct from DNS *resolution* and focuses on correctness
/// of authoritative records.
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DnsValidationResult {
    /// Domain name that was validated.
    pub domain: String,

    /// NS records discovered for the domain.
    pub ns_records: Option<Vec<String>>,

    /// SOA record, if available.
    pub soa_record: Option<String>,

    /// Whether the DNS configuration is valid.
    pub is_valid: bool,
}