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