Skip to main content

rustfs_obs/
config.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Observability configuration for RustFS.
16//!
17//! All configuration is read from environment variables. The canonical list of
18//! variable names and their defaults lives in `rustfs-config/src/observability/mod.rs`.
19//!
20//! Two public structs are provided:
21//! - [`OtelConfig`] — the primary flat configuration that drives every backend.
22//! - [`AppConfig`] — a thin wrapper used when the config is embedded inside a
23//!   larger application configuration struct.
24
25use rustfs_config::observability::{
26    DEFAULT_OBS_ENVIRONMENT_PRODUCTION, DEFAULT_OBS_LOG_CLEANUP_INTERVAL_SECONDS, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES,
27    DEFAULT_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM, DEFAULT_OBS_LOG_DELETE_EMPTY_FILES,
28    DEFAULT_OBS_LOG_DRY_RUN, DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL, DEFAULT_OBS_LOG_MATCH_MODE,
29    DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS,
30    DEFAULT_OBS_LOG_PARALLEL_COMPRESS, DEFAULT_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
31    DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, DEFAULT_OBS_LOG_ZSTD_WORKERS, ENV_OBS_ENDPOINT, ENV_OBS_ENDPOINT_HEADERS,
32    ENV_OBS_ENDPOINT_LOGS_HEADERS, ENV_OBS_ENDPOINT_LOGS_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_METRICS_HEADERS,
33    ENV_OBS_ENDPOINT_METRICS_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_TIMEOUT_MILLIS, ENV_OBS_ENDPOINT_TRACES_HEADERS,
34    ENV_OBS_ENDPOINT_TRACES_TIMEOUT_MILLIS, ENV_OBS_ENVIRONMENT, ENV_OBS_LOG_CLEANUP_INTERVAL_SECONDS,
35    ENV_OBS_LOG_COMPRESS_OLD_FILES, ENV_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS, ENV_OBS_LOG_COMPRESSION_ALGORITHM,
36    ENV_OBS_LOG_DELETE_EMPTY_FILES, ENV_OBS_LOG_DIRECTORY, ENV_OBS_LOG_DRY_RUN, ENV_OBS_LOG_ENDPOINT,
37    ENV_OBS_LOG_EXCLUDE_PATTERNS, ENV_OBS_LOG_FILENAME, ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL, ENV_OBS_LOG_KEEP_FILES,
38    ENV_OBS_LOG_MATCH_MODE, ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES, ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES,
39    ENV_OBS_LOG_MIN_FILE_AGE_SECONDS, ENV_OBS_LOG_PARALLEL_COMPRESS, ENV_OBS_LOG_PARALLEL_WORKERS, ENV_OBS_LOG_ROTATION_TIME,
40    ENV_OBS_LOG_STDOUT_ENABLED, ENV_OBS_LOG_ZSTD_COMPRESSION_LEVEL, ENV_OBS_LOG_ZSTD_FALLBACK_TO_GZIP, ENV_OBS_LOG_ZSTD_WORKERS,
41    ENV_OBS_LOGGER_LEVEL, ENV_OBS_LOGS_EXPORT_ENABLED, ENV_OBS_METER_INTERVAL, ENV_OBS_METRIC_ENDPOINT,
42    ENV_OBS_METRICS_EXPORT_ENABLED, ENV_OBS_PROFILING_ENDPOINT, ENV_OBS_PROFILING_EXPORT_ENABLED, ENV_OBS_SAMPLE_RATIO,
43    ENV_OBS_SERVICE_NAME, ENV_OBS_SERVICE_VERSION, ENV_OBS_TLS_CA_FILE, ENV_OBS_TRACE_ENDPOINT, ENV_OBS_TRACES_EXPORT_ENABLED,
44    ENV_OBS_USE_STDOUT,
45};
46use rustfs_config::{
47    APP_NAME, DEFAULT_LOG_KEEP_FILES, DEFAULT_LOG_LEVEL, DEFAULT_LOG_ROTATION_TIME, DEFAULT_OBS_LOG_FILENAME,
48    DEFAULT_OBS_LOGS_EXPORT_ENABLED, DEFAULT_OBS_METRICS_EXPORT_ENABLED, DEFAULT_OBS_PROFILING_EXPORT_ENABLED,
49    DEFAULT_OBS_TRACES_EXPORT_ENABLED, ENVIRONMENT, METER_INTERVAL, SAMPLE_RATIO, SERVICE_VERSION, USE_STDOUT,
50};
51use rustfs_utils::{
52    get_env_bool, get_env_bool_with_aliases, get_env_f64, get_env_opt_bool, get_env_opt_str, get_env_opt_u64, get_env_str,
53    get_env_u64, get_env_usize,
54};
55use serde::{Deserialize, Serialize};
56use std::env;
57#[cfg(test)]
58use std::sync::{Mutex, OnceLock};
59
60const LEGACY_ENV_OBS_PROFILING_ENABLED: &str = "RUSTFS_OBS_PROFILING_ENABLED";
61
62fn get_env_nonempty_str(name: &str, default: &str) -> String {
63    match env::var(name) {
64        Ok(value) if !value.trim().is_empty() => value,
65        _ => default.to_string(),
66    }
67}
68
69/// Full observability configuration used by all telemetry backends.
70///
71/// Fields are grouped into three logical sections:
72///
73/// ## OpenTelemetry / OTLP export
74/// Controls whether and where traces, metrics, and logs are exported over the
75/// wire using the OTLP/HTTP protocol.
76///
77/// ## Local logging
78/// Controls the rolling-file appender: directory, filename, rotation policy,
79/// and the number of files to retain.
80///
81/// ## Log cleanup
82/// Controls the background cleanup task: size limits, compression, retention
83/// of compressed archives, exclusion patterns, and dry-run mode.
84///
85/// # Design Notes
86///
87/// - All fields are `Option<T>` to allow partial configuration via environment
88///   variables with sensible defaults provided by constants in `rustfs-config`.
89/// - `log_keep_files` is used to derive the rolling-appender's upper bound on
90///   retained files (if enabled) and to set the cleaner's retained-file ceiling.
91///
92/// # Example
93/// ```no_run
94/// use rustfs_obs::OtelConfig;
95///
96/// // Build from environment variables (typical production usage).
97/// let config = OtelConfig::new();
98///
99/// // Build with an explicit OTLP endpoint.
100/// let config = OtelConfig::extract_otel_config_from_env(
101///     Some("http://otel-collector:4318".to_string())
102/// );
103///
104/// // Compression related env mapping examples:
105/// // RUSTFS_OBS_LOG_COMPRESSION_ALGORITHM=zstd
106/// // RUSTFS_OBS_LOG_PARALLEL_COMPRESS=true
107/// // RUSTFS_OBS_LOG_PARALLEL_WORKERS=6
108/// ```
109#[derive(Debug, Deserialize, Serialize, Clone)]
110pub struct OtelConfig {
111    // ── OTLP export ──────────────────────────────────────────────────────────
112    /// Root OTLP/HTTP endpoint (e.g. `http://otel-collector:4318`).
113    /// Per-signal endpoints below take precedence when set.
114    pub endpoint: String,
115    /// Dedicated trace endpoint; overrides `endpoint` + `/v1/traces` fallback.
116    pub trace_endpoint: Option<String>,
117    /// Dedicated metrics endpoint; overrides `endpoint` + `/v1/metrics` fallback.
118    pub metric_endpoint: Option<String>,
119    /// Dedicated log endpoint; overrides `endpoint` + `/v1/logs` fallback.
120    pub log_endpoint: Option<String>,
121    /// Headers applied to all OTLP signals when using HTTP exporter.
122    /// Format: comma-separated `key=value` pairs with URL-encoded values, for
123    /// example: `Authorization=Bearer%20abc%20123,X-Scope-OrgID=my-tenant`.
124    /// URL-encode reserved characters in values such as spaces, commas, and `=`.
125    pub endpoint_headers: Option<String>,
126    /// Additional headers for traces; merged on top of `endpoint_headers`.
127    /// Uses the same comma-separated `key=value` format with URL-encoded values.
128    pub trace_headers: Option<String>,
129    /// Additional headers for metrics; merged on top of `endpoint_headers`.
130    /// Uses the same comma-separated `key=value` format with URL-encoded values.
131    pub metric_headers: Option<String>,
132    /// Additional headers for logs; merged on top of `endpoint_headers`.
133    /// Uses the same comma-separated `key=value` format with URL-encoded values.
134    pub log_headers: Option<String>,
135    /// Timeout (milliseconds) for all OTLP HTTP exports.
136    pub endpoint_timeout_millis: Option<u64>,
137    /// Timeout (milliseconds) for trace OTLP HTTP export.
138    pub trace_timeout_millis: Option<u64>,
139    /// Timeout (milliseconds) for metrics OTLP HTTP export.
140    pub metric_timeout_millis: Option<u64>,
141    /// Timeout (milliseconds) for log OTLP HTTP export.
142    pub log_timeout_millis: Option<u64>,
143    /// Absolute path to a PEM bundle whose certificates are added to the
144    /// system trust roots used by OTLP/HTTP exporters.
145    pub tls_ca_file: Option<String>,
146    /// Dedicated profiling endpoint.
147    pub profiling_endpoint: Option<String>,
148    /// Whether to export distributed traces (default: `true`).
149    pub traces_export_enabled: Option<bool>,
150    /// Whether to export metrics (default: `true`).
151    pub metrics_export_enabled: Option<bool>,
152    /// Whether to export logs via OTLP (default: `true`).
153    pub logs_export_enabled: Option<bool>,
154    /// Whether to export profiles via pyroscope (default: `true`).
155    pub profiling_export_enabled: Option<bool>,
156    /// **[OTLP-only]** Mirror all signals to stdout in addition to OTLP export.
157    /// Only applies when an OTLP endpoint is configured.
158    pub use_stdout: Option<bool>,
159    /// Fraction of traces to sample, `0.0`–`1.0` (default: `1.0`).
160    pub sample_ratio: Option<f64>,
161    /// Metrics export interval in seconds (default: `30`).
162    pub meter_interval: Option<u64>,
163    /// OTel `service.name` attribute (default: `APP_NAME`).
164    pub service_name: Option<String>,
165    /// OTel `service.version` attribute (default: `SERVICE_VERSION`).
166    pub service_version: Option<String>,
167    /// Deployment environment tag, e.g. `production` or `development`.
168    pub environment: Option<String>,
169
170    // ── Local logging ─────────────────────────────────────────────────────────
171    /// Minimum log level directive (default: `error`).
172    /// Respects `RUST_LOG` syntax when set via environment.
173    pub logger_level: Option<String>,
174    /// When `true`, a stdout JSON layer is always attached regardless of the
175    /// active backend (default: `false` in production, `true` otherwise).
176    pub log_stdout_enabled: Option<bool>,
177    /// Directory where rolling log files are written.
178    /// When absent or empty, logging falls back to stdout-only mode.
179    pub log_directory: Option<String>,
180    /// Base name for log files (without date suffix), e.g. `rustfs`.
181    /// Used for both rolling-appender naming and cleanup scanning.
182    pub log_filename: Option<String>,
183    /// Rotation time granularity: `"minutely"`, `"hourly"`, or `"daily"`
184    /// (default: `"hourly"`; any unrecognized value falls back to `"daily"`).
185    pub log_rotation_time: Option<String>,
186    /// Number of rolling log files to retain (default: `30`).
187    /// Used by both the rolling-appender (as a loose upper bound) and the
188    /// background cleaner (as the minimum retention count).
189    pub log_keep_files: Option<usize>,
190
191    // ── Log cleanup ───────────────────────────────────────────────────────────
192    /// Hard ceiling on the total size (bytes) of all log files (default: 2 GiB).
193    pub log_max_total_size_bytes: Option<u64>,
194    /// Per-file size ceiling (bytes); `0` means unlimited (default: `0`).
195    pub log_max_single_file_size_bytes: Option<u64>,
196    /// Compress eligible files with gzip before deletion (default: `true`).
197    pub log_compress_old_files: Option<bool>,
198    /// Gzip compression level `1`–`9` (default: `6`).
199    pub log_gzip_compression_level: Option<u32>,
200    /// Compression algorithm: `gzip` or `zstd` (default: `zstd`).
201    pub log_compression_algorithm: Option<String>,
202    /// Enable crossbeam work-stealing parallel compression (default: `true`).
203    pub log_parallel_compress: Option<bool>,
204    /// Worker count for parallel compression (default: `6`).
205    pub log_parallel_workers: Option<usize>,
206    /// Zstd compression level `1`–`21` (default: `8`).
207    pub log_zstd_compression_level: Option<i32>,
208    /// Fallback to gzip when zstd compression fails (default: `true`).
209    pub log_zstd_fallback_to_gzip: Option<bool>,
210    /// Internal zstdmt workers per job (default: `1`).
211    pub log_zstd_workers: Option<usize>,
212    /// Delete compressed archives older than this many days; `0` = keep forever
213    /// (default: `30`).
214    pub log_compressed_file_retention_days: Option<u64>,
215    /// Comma-separated glob patterns for files that must never be cleaned up.
216    pub log_exclude_patterns: Option<String>,
217    /// Delete zero-byte log files during cleanup (default: `true`).
218    pub log_delete_empty_files: Option<bool>,
219    /// A file younger than this many seconds is never touched (default: `3600`).
220    pub log_min_file_age_seconds: Option<u64>,
221    /// How often the background cleanup task runs, in seconds (default: `1800`).
222    pub log_cleanup_interval_seconds: Option<u64>,
223    /// Log what *would* be deleted without actually removing anything
224    /// (default: `false`).
225    pub log_dry_run: Option<bool>,
226    /// File matching mode: "prefix" or "suffix" (default: "suffix").
227    pub log_match_mode: Option<String>,
228}
229
230impl OtelConfig {
231    /// Build an [`OtelConfig`] from environment variables.
232    ///
233    /// The optional `endpoint` argument sets the root OTLP endpoint. If it is
234    /// `None` or an empty string the value is read from the
235    /// `RUSTFS_OBS_ENDPOINT` environment variable instead.
236    ///
237    /// When no endpoint is configured at all, `use_stdout` is forced to `true`
238    /// so that logs are still visible during development.
239    ///
240    /// # Example
241    /// ```no_run
242    /// use rustfs_obs::OtelConfig;
243    ///
244    /// // Read everything from env vars.
245    /// let config = OtelConfig::extract_otel_config_from_env(None);
246    ///
247    /// // Override the endpoint programmatically.
248    /// let config = OtelConfig::extract_otel_config_from_env(
249    ///     Some("http://localhost:4318".to_string())
250    /// );
251    /// ```
252    pub fn extract_otel_config_from_env(endpoint: Option<String>) -> OtelConfig {
253        let endpoint = match endpoint {
254            Some(ep) if !ep.is_empty() => ep,
255            _ => env::var(ENV_OBS_ENDPOINT).unwrap_or_default(),
256        };
257
258        // Force stdout when there is no remote endpoint so that operators
259        // always have *some* log output in the default configuration.
260        let use_stdout = if endpoint.is_empty() {
261            true
262        } else {
263            get_env_bool(ENV_OBS_USE_STDOUT, USE_STDOUT)
264        };
265
266        // The canonical log directory is resolved only when explicitly set via
267        // environment variable. When absent or empty, logging falls back to
268        // stdout-only mode (not file-rolling).
269        let log_directory = match std::env::var(ENV_OBS_LOG_DIRECTORY) {
270            Ok(val) if !val.is_empty() => Some(val),
271            _ => None,
272        };
273
274        // `log_keep_files` is the single source of truth for file retention count.
275        // It defaults to `DEFAULT_LOG_KEEP_FILES` (30).
276        let mut log_keep_files = get_env_usize(ENV_OBS_LOG_KEEP_FILES, DEFAULT_LOG_KEEP_FILES);
277        if log_keep_files == 0 {
278            log_keep_files = DEFAULT_LOG_KEEP_FILES;
279        }
280        let log_keep_files = Some(log_keep_files);
281
282        // `log_rotation_time` drives the rolling-appender rotation period.
283        let log_rotation_time = Some(get_env_str(ENV_OBS_LOG_ROTATION_TIME, DEFAULT_LOG_ROTATION_TIME));
284
285        OtelConfig {
286            // OTLP
287            endpoint,
288            trace_endpoint: get_env_opt_str(ENV_OBS_TRACE_ENDPOINT),
289            metric_endpoint: get_env_opt_str(ENV_OBS_METRIC_ENDPOINT),
290            log_endpoint: get_env_opt_str(ENV_OBS_LOG_ENDPOINT),
291            endpoint_headers: get_env_opt_str(ENV_OBS_ENDPOINT_HEADERS),
292            trace_headers: get_env_opt_str(ENV_OBS_ENDPOINT_TRACES_HEADERS),
293            metric_headers: get_env_opt_str(ENV_OBS_ENDPOINT_METRICS_HEADERS),
294            log_headers: get_env_opt_str(ENV_OBS_ENDPOINT_LOGS_HEADERS),
295            endpoint_timeout_millis: get_env_opt_u64(ENV_OBS_ENDPOINT_TIMEOUT_MILLIS),
296            trace_timeout_millis: get_env_opt_u64(ENV_OBS_ENDPOINT_TRACES_TIMEOUT_MILLIS),
297            metric_timeout_millis: get_env_opt_u64(ENV_OBS_ENDPOINT_METRICS_TIMEOUT_MILLIS),
298            log_timeout_millis: get_env_opt_u64(ENV_OBS_ENDPOINT_LOGS_TIMEOUT_MILLIS),
299            tls_ca_file: get_env_opt_str(ENV_OBS_TLS_CA_FILE)
300                .map(|path| path.trim().to_string())
301                .filter(|path| !path.is_empty()),
302            profiling_endpoint: get_env_opt_str(ENV_OBS_PROFILING_ENDPOINT),
303            traces_export_enabled: Some(get_env_bool(ENV_OBS_TRACES_EXPORT_ENABLED, DEFAULT_OBS_TRACES_EXPORT_ENABLED)),
304            metrics_export_enabled: Some(get_env_bool(ENV_OBS_METRICS_EXPORT_ENABLED, DEFAULT_OBS_METRICS_EXPORT_ENABLED)),
305            logs_export_enabled: Some(get_env_bool(ENV_OBS_LOGS_EXPORT_ENABLED, DEFAULT_OBS_LOGS_EXPORT_ENABLED)),
306            profiling_export_enabled: Some(get_env_bool_with_aliases(
307                ENV_OBS_PROFILING_EXPORT_ENABLED,
308                &[LEGACY_ENV_OBS_PROFILING_ENABLED],
309                DEFAULT_OBS_PROFILING_EXPORT_ENABLED,
310            )),
311            use_stdout: Some(use_stdout),
312            sample_ratio: Some(get_env_f64(ENV_OBS_SAMPLE_RATIO, SAMPLE_RATIO)),
313            meter_interval: Some(get_env_u64(ENV_OBS_METER_INTERVAL, METER_INTERVAL)),
314            service_name: Some(get_env_str(ENV_OBS_SERVICE_NAME, APP_NAME)),
315            service_version: Some(get_env_str(ENV_OBS_SERVICE_VERSION, SERVICE_VERSION)),
316            environment: Some(get_env_str(ENV_OBS_ENVIRONMENT, ENVIRONMENT)),
317            // Local logging
318            logger_level: Some(get_env_str(ENV_OBS_LOGGER_LEVEL, DEFAULT_LOG_LEVEL)),
319            log_stdout_enabled: get_env_opt_bool(ENV_OBS_LOG_STDOUT_ENABLED),
320            log_directory,
321            log_filename: Some(get_env_nonempty_str(ENV_OBS_LOG_FILENAME, DEFAULT_OBS_LOG_FILENAME)),
322            log_rotation_time,
323            log_keep_files,
324            // Log cleanup
325            log_max_total_size_bytes: Some(get_env_u64(ENV_OBS_LOG_MAX_TOTAL_SIZE_BYTES, DEFAULT_OBS_LOG_MAX_TOTAL_SIZE_BYTES)),
326            log_max_single_file_size_bytes: Some(get_env_u64(
327                ENV_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES,
328                DEFAULT_OBS_LOG_MAX_SINGLE_FILE_SIZE_BYTES,
329            )),
330            log_compress_old_files: Some(get_env_bool(ENV_OBS_LOG_COMPRESS_OLD_FILES, DEFAULT_OBS_LOG_COMPRESS_OLD_FILES)),
331            log_gzip_compression_level: Some(get_env_u64(
332                ENV_OBS_LOG_GZIP_COMPRESSION_LEVEL,
333                DEFAULT_OBS_LOG_GZIP_COMPRESSION_LEVEL as u64,
334            ) as u32),
335            log_compression_algorithm: Some(get_env_str(
336                ENV_OBS_LOG_COMPRESSION_ALGORITHM,
337                DEFAULT_OBS_LOG_COMPRESSION_ALGORITHM,
338            )),
339            log_parallel_compress: Some(get_env_bool(ENV_OBS_LOG_PARALLEL_COMPRESS, DEFAULT_OBS_LOG_PARALLEL_COMPRESS)),
340            log_parallel_workers: Some(get_env_usize(ENV_OBS_LOG_PARALLEL_WORKERS, DEFAULT_OBS_LOG_PARALLEL_WORKERS)),
341            log_zstd_compression_level: Some(get_env_u64(
342                ENV_OBS_LOG_ZSTD_COMPRESSION_LEVEL,
343                DEFAULT_OBS_LOG_ZSTD_COMPRESSION_LEVEL as u64,
344            ) as i32),
345            log_zstd_fallback_to_gzip: Some(get_env_bool(
346                ENV_OBS_LOG_ZSTD_FALLBACK_TO_GZIP,
347                DEFAULT_OBS_LOG_ZSTD_FALLBACK_TO_GZIP,
348            )),
349            log_zstd_workers: Some(get_env_usize(ENV_OBS_LOG_ZSTD_WORKERS, DEFAULT_OBS_LOG_ZSTD_WORKERS)),
350            log_compressed_file_retention_days: Some(get_env_u64(
351                ENV_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS,
352                DEFAULT_OBS_LOG_COMPRESSED_FILE_RETENTION_DAYS,
353            )),
354            log_exclude_patterns: get_env_opt_str(ENV_OBS_LOG_EXCLUDE_PATTERNS),
355            log_delete_empty_files: Some(get_env_bool(ENV_OBS_LOG_DELETE_EMPTY_FILES, DEFAULT_OBS_LOG_DELETE_EMPTY_FILES)),
356            log_min_file_age_seconds: Some(get_env_u64(ENV_OBS_LOG_MIN_FILE_AGE_SECONDS, DEFAULT_OBS_LOG_MIN_FILE_AGE_SECONDS)),
357            log_cleanup_interval_seconds: Some(get_env_u64(
358                ENV_OBS_LOG_CLEANUP_INTERVAL_SECONDS,
359                DEFAULT_OBS_LOG_CLEANUP_INTERVAL_SECONDS,
360            )),
361            log_dry_run: Some(get_env_bool(ENV_OBS_LOG_DRY_RUN, DEFAULT_OBS_LOG_DRY_RUN)),
362            log_match_mode: Some(get_env_str(ENV_OBS_LOG_MATCH_MODE, DEFAULT_OBS_LOG_MATCH_MODE)),
363        }
364    }
365
366    /// Create a new [`OtelConfig`] populated entirely from environment variables.
367    ///
368    /// Equivalent to `OtelConfig::extract_otel_config_from_env(None)`.
369    ///
370    /// # Example
371    /// ```no_run
372    /// use rustfs_obs::OtelConfig;
373    /// let config = OtelConfig::new();
374    /// ```
375    pub fn new() -> Self {
376        Self::extract_otel_config_from_env(None)
377    }
378}
379
380impl Default for OtelConfig {
381    fn default() -> Self {
382        Self::new()
383    }
384}
385
386/// Top-level application configuration that embeds [`OtelConfig`].
387///
388/// Use this when the observability config lives inside a larger `AppConfig`
389/// struct, e.g. when deserialising from a config file that also contains other
390/// application settings.
391///
392/// # Example
393/// ```
394/// use rustfs_obs::AppConfig;
395///
396/// let config = AppConfig::new_with_endpoint(None);
397/// ```
398#[derive(Debug, Deserialize, Clone)]
399pub struct AppConfig {
400    pub observability: OtelConfig,
401}
402
403impl AppConfig {
404    /// Create an [`AppConfig`] with all observability settings read from the
405    /// environment (no explicit endpoint override).
406    pub fn new() -> Self {
407        Self {
408            observability: OtelConfig::default(),
409        }
410    }
411
412    /// Create an [`AppConfig`] with an explicit OTLP endpoint.
413    ///
414    /// # Arguments
415    /// * `endpoint` - Root OTLP/HTTP endpoint URL, or `None` to read from env.
416    ///
417    /// # Example
418    /// ```no_run
419    /// use rustfs_obs::AppConfig;
420    ///
421    /// let config = AppConfig::new_with_endpoint(Some("http://localhost:4318".to_string()));
422    /// ```
423    pub fn new_with_endpoint(endpoint: Option<String>) -> Self {
424        Self {
425            observability: OtelConfig::extract_otel_config_from_env(endpoint),
426        }
427    }
428}
429
430impl Default for AppConfig {
431    fn default() -> Self {
432        Self::new()
433    }
434}
435
436/// Returns `true` when the current runtime environment is `production`.
437///
438/// Reads the `RUSTFS_OBS_ENVIRONMENT` environment variable and compares it
439/// case-insensitively against the string `"production"`.
440pub fn is_production_environment() -> bool {
441    get_env_str(ENV_OBS_ENVIRONMENT, ENVIRONMENT).eq_ignore_ascii_case(DEFAULT_OBS_ENVIRONMENT_PRODUCTION)
442}
443
444#[cfg(test)]
445mod tests {
446    use super::*;
447
448    static PROFILING_ENV_TEST_LOCK: OnceLock<Mutex<()>> = OnceLock::new();
449
450    fn with_profiling_env_lock<F>(f: F)
451    where
452        F: FnOnce(),
453    {
454        let _guard = PROFILING_ENV_TEST_LOCK.get_or_init(|| Mutex::new(())).lock().unwrap();
455        f();
456    }
457
458    fn extract_profiling_export_enabled() -> Option<bool> {
459        OtelConfig::extract_otel_config_from_env(None).profiling_export_enabled
460    }
461
462    #[test]
463    fn profiling_export_defaults_to_disabled_when_unset() {
464        with_profiling_env_lock(|| {
465            temp_env::with_var_unset(ENV_OBS_PROFILING_EXPORT_ENABLED, || {
466                temp_env::with_var_unset(LEGACY_ENV_OBS_PROFILING_ENABLED, || {
467                    assert_eq!(extract_profiling_export_enabled(), Some(DEFAULT_OBS_PROFILING_EXPORT_ENABLED));
468                });
469            });
470        });
471    }
472
473    #[test]
474    fn profiling_export_accepts_legacy_env_alias() {
475        with_profiling_env_lock(|| {
476            temp_env::with_var_unset(ENV_OBS_PROFILING_EXPORT_ENABLED, || {
477                temp_env::with_var(LEGACY_ENV_OBS_PROFILING_ENABLED, Some("true"), || {
478                    assert_eq!(extract_profiling_export_enabled(), Some(true));
479                });
480            });
481        });
482    }
483
484    #[test]
485    fn canonical_profiling_toggle_has_priority_over_legacy_alias() {
486        with_profiling_env_lock(|| {
487            temp_env::with_var(LEGACY_ENV_OBS_PROFILING_ENABLED, Some("true"), || {
488                temp_env::with_var(ENV_OBS_PROFILING_EXPORT_ENABLED, Some("false"), || {
489                    assert_eq!(extract_profiling_export_enabled(), Some(false));
490                });
491            });
492        });
493    }
494
495    #[test]
496    fn empty_log_filename_falls_back_to_default() {
497        with_profiling_env_lock(|| {
498            temp_env::with_var(ENV_OBS_LOG_FILENAME, Some(""), || {
499                let config = OtelConfig::extract_otel_config_from_env(None);
500                assert_eq!(config.log_filename.as_deref(), Some(DEFAULT_OBS_LOG_FILENAME));
501            });
502        });
503    }
504
505    #[test]
506    fn stdout_mirror_environment_preserves_unset_true_and_false() {
507        with_profiling_env_lock(|| {
508            temp_env::with_var_unset(ENV_OBS_LOG_STDOUT_ENABLED, || {
509                assert_eq!(OtelConfig::extract_otel_config_from_env(None).log_stdout_enabled, None);
510            });
511            temp_env::with_var(ENV_OBS_LOG_STDOUT_ENABLED, Some("true"), || {
512                assert_eq!(OtelConfig::extract_otel_config_from_env(None).log_stdout_enabled, Some(true));
513            });
514            temp_env::with_var(ENV_OBS_LOG_STDOUT_ENABLED, Some("false"), || {
515                assert_eq!(OtelConfig::extract_otel_config_from_env(None).log_stdout_enabled, Some(false));
516            });
517        });
518    }
519
520    #[test]
521    fn otlp_tls_ca_file_environment_preserves_unset_empty_and_configured_values() {
522        with_profiling_env_lock(|| {
523            temp_env::with_var_unset(ENV_OBS_TLS_CA_FILE, || {
524                assert_eq!(OtelConfig::extract_otel_config_from_env(None).tls_ca_file, None);
525            });
526            temp_env::with_var(ENV_OBS_TLS_CA_FILE, Some(""), || {
527                assert_eq!(OtelConfig::extract_otel_config_from_env(None).tls_ca_file, None);
528            });
529            temp_env::with_var(ENV_OBS_TLS_CA_FILE, Some("/etc/rustfs/otlp-ca.pem"), || {
530                assert_eq!(
531                    OtelConfig::extract_otel_config_from_env(None).tls_ca_file.as_deref(),
532                    Some("/etc/rustfs/otlp-ca.pem")
533                );
534            });
535        });
536    }
537}