Skip to main content

rustfs_utils/
envs.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
15use std::{
16    any::type_name,
17    collections::BTreeSet,
18    collections::HashSet,
19    env,
20    sync::{Mutex, OnceLock},
21};
22use tracing::warn;
23
24/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
25/// 8-bit type: signed i8
26///
27/// #Parameters
28/// - `key`: The environment variable key to look up.
29/// - `default`: The default value to return if the environment variable is not set or parsing fails.
30///
31/// #Returns
32/// - `i8`: The parsed value as i8 if successful, otherwise the default value.
33///
34pub fn get_env_i8(key: &str, default: i8) -> i8 {
35    parse_env_value(key).unwrap_or(default)
36}
37
38/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
39/// 8-bit type: signed i8
40///
41/// #Parameters
42/// - `key`: The environment variable key to look up.
43///
44/// #Returns
45/// - `Option<i8>`: The parsed value as i8 if successful, otherwise None
46///
47pub fn get_env_opt_i8(key: &str) -> Option<i8> {
48    parse_env_value(key)
49}
50
51/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
52/// 8-bit type: unsigned u8
53///
54/// #Parameters
55/// - `key`: The environment variable key to look up.
56/// - `default`: The default value to return if the environment variable is not set or parsing fails.
57///
58/// #Returns
59/// - `u8`: The parsed value as u8 if successful, otherwise the default value.
60///
61pub fn get_env_u8(key: &str, default: u8) -> u8 {
62    parse_env_value(key).unwrap_or(default)
63}
64
65/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
66/// 8-bit type: unsigned u8
67///
68/// #Parameters
69/// - `key`: The environment variable key to look up.
70///
71/// #Returns
72/// - `Option<u8>`: The parsed value as u8 if successful, otherwise None
73///
74pub fn get_env_opt_u8(key: &str) -> Option<u8> {
75    parse_env_value(key)
76}
77
78static WARNED_ENV_MESSAGES: OnceLock<Mutex<HashSet<String>>> = OnceLock::new();
79
80fn log_once(key: &str, message: impl FnOnce() -> String) {
81    let seen = WARNED_ENV_MESSAGES.get_or_init(|| Mutex::new(HashSet::new()));
82    let mut seen = seen.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
83    if seen.insert(key.to_string()) {
84        warn!("{}", message());
85    }
86}
87
88fn external_alias_for_key(key: &str) -> Option<String> {
89    let suffix = key.strip_prefix("RUSTFS_")?;
90    if is_external_compatible_suffix(suffix) {
91        Some(format!("{}{}", external_env_prefix(), suffix))
92    } else {
93        None
94    }
95}
96
97fn resolve_env_with_aliases(key: &str, deprecated: &[&str]) -> Option<(String, String)> {
98    if let Ok(value) = env::var(key) {
99        return Some((key.to_string(), value));
100    }
101
102    if let Some((alias, value)) = deprecated
103        .iter()
104        .find_map(|alias| env::var(alias).ok().map(|value| (*alias, value)))
105    {
106        let deprecated_key = format!("env_alias:{alias}->{key}");
107        log_once(&deprecated_key, || {
108            format!("Environment variable {alias} is deprecated, use {key} instead")
109        });
110        return Some((alias.to_string(), value));
111    }
112
113    let alias = external_alias_for_key(key)?;
114    let value = env::var(&alias).ok()?;
115    let deprecated_key = format!("env_alias:{alias}->{key}");
116    log_once(&deprecated_key, || {
117        format!("Environment variable {alias} is deprecated, use {key} instead")
118    });
119    Some((alias, value))
120}
121
122const EXTERNAL_ENV_PREFIX_BYTES: [u8; 6] = [77, 73, 78, 73, 79, 95];
123
124const EXTERNAL_COMPATIBLE_SUFFIXES: &[&str] = &[
125    "ACCESS_KEY",
126    "ACCESS_KEY_FILE",
127    "ADDRESS",
128    "API_OBJECT_MAX_VERSIONS",
129    "API_XFF_HEADER",
130    "AUDIT_WEBHOOK_AUTH_TOKEN",
131    "AUDIT_WEBHOOK_CLIENT_CERT",
132    "AUDIT_WEBHOOK_CLIENT_KEY",
133    "AUDIT_WEBHOOK_ENABLE",
134    "AUDIT_WEBHOOK_ENDPOINT",
135    "AUDIT_WEBHOOK_QUEUE_DIR",
136    "COMPRESS_ENABLE",
137    "COMPRESS_EXTENSIONS",
138    "COMPRESS_MIME_TYPES",
139    "CONSOLE_ADDRESS",
140    "DRIVE_ACTIVE_MONITORING",
141    "ERASURE_SET_DRIVE_COUNT",
142    "IDENTITY_OPENID_CLAIM_NAME",
143    "IDENTITY_OPENID_CLAIM_PREFIX",
144    "IDENTITY_OPENID_CLIENT_ID",
145    "IDENTITY_OPENID_CLIENT_SECRET",
146    "IDENTITY_OPENID_CONFIG_URL",
147    "IDENTITY_OPENID_DISPLAY_NAME",
148    "IDENTITY_OPENID_ISSUER",
149    "IDENTITY_OPENID_REDIRECT_URI",
150    "IDENTITY_OPENID_SCOPES",
151    "ILM_EXPIRATION_WORKERS",
152    "LICENSE",
153    "NOTIFY_MQTT_BROKER",
154    "NOTIFY_MQTT_ENABLE",
155    "NOTIFY_MQTT_KEEP_ALIVE_INTERVAL",
156    "NOTIFY_MQTT_PASSWORD",
157    "NOTIFY_MQTT_QOS",
158    "NOTIFY_MQTT_QUEUE_DIR",
159    "NOTIFY_MQTT_QUEUE_LIMIT",
160    "NOTIFY_MQTT_RECONNECT_INTERVAL",
161    "NOTIFY_MQTT_TOPIC",
162    "NOTIFY_MQTT_USERNAME",
163    "NOTIFY_WEBHOOK_AUTH_TOKEN",
164    "NOTIFY_WEBHOOK_CLIENT_CERT",
165    "NOTIFY_WEBHOOK_CLIENT_KEY",
166    "NOTIFY_WEBHOOK_ENABLE",
167    "NOTIFY_WEBHOOK_ENDPOINT",
168    "NOTIFY_WEBHOOK_QUEUE_DIR",
169    "NOTIFY_WEBHOOK_QUEUE_LIMIT",
170    "POLICY_PLUGIN_AUTH_TOKEN",
171    "POLICY_PLUGIN_URL",
172    "PORT",
173    "REGION",
174    "ROOT_PASSWORD",
175    "ROOT_USER",
176    "SCANNER_CYCLE",
177    "SCANNER_SPEED",
178    "SECRET_KEY",
179    "SECRET_KEY_FILE",
180    "STORAGE_CLASS_INLINE_BLOCK",
181    "STORAGE_CLASS_OPTIMIZE",
182    "STORAGE_CLASS_RRS",
183    "STORAGE_CLASS_STANDARD",
184    "VERSION",
185    "VOLUMES",
186];
187
188const EXTERNAL_DYNAMIC_COMPATIBLE_PREFIXES: &[&str] = &["AUDIT_MQTT_", "AUDIT_WEBHOOK_", "NOTIFY_MQTT_", "NOTIFY_WEBHOOK_"];
189
190#[derive(Debug, Default, Clone, PartialEq, Eq)]
191pub struct ExternalEnvCompatReport {
192    pub mapped_pairs: Vec<(String, String)>,
193    pub conflict_keys: Vec<String>,
194}
195
196impl ExternalEnvCompatReport {
197    pub fn mapped_count(&self) -> usize {
198        self.mapped_pairs.len()
199    }
200
201    pub fn conflict_count(&self) -> usize {
202        self.conflict_keys.len()
203    }
204}
205
206fn external_env_prefix() -> &'static str {
207    static PREFIX: OnceLock<String> = OnceLock::new();
208    PREFIX
209        .get_or_init(|| EXTERNAL_ENV_PREFIX_BYTES.iter().map(|&byte| char::from(byte)).collect())
210        .as_str()
211}
212
213fn is_external_compatible_suffix(suffix: &str) -> bool {
214    EXTERNAL_COMPATIBLE_SUFFIXES.contains(&suffix)
215        || EXTERNAL_DYNAMIC_COMPATIBLE_PREFIXES
216            .iter()
217            .any(|prefix| suffix.starts_with(prefix))
218}
219
220fn build_external_env_compat_report_from_entries<I>(entries: I) -> ExternalEnvCompatReport
221where
222    I: IntoIterator<Item = (String, String)>,
223{
224    let env_map: std::collections::BTreeMap<String, String> = entries.into_iter().collect();
225    let mut mapped_pairs = BTreeSet::new();
226    let mut conflict_keys = BTreeSet::new();
227    let source_prefix = external_env_prefix();
228
229    for (source_key, source_value) in env_map.iter() {
230        let Some(suffix) = source_key.strip_prefix(source_prefix) else {
231            continue;
232        };
233        if !is_external_compatible_suffix(suffix) {
234            continue;
235        }
236        let rustfs_key = format!("RUSTFS_{suffix}");
237        match env_map.get(&rustfs_key) {
238            None => {
239                mapped_pairs.insert((source_key.clone(), rustfs_key));
240            }
241            Some(rustfs_value) if rustfs_value != source_value => {
242                conflict_keys.insert(rustfs_key);
243            }
244            Some(_) => {}
245        }
246    }
247
248    ExternalEnvCompatReport {
249        mapped_pairs: mapped_pairs.into_iter().collect(),
250        conflict_keys: conflict_keys.into_iter().collect(),
251    }
252}
253
254/// Build compatibility plan between source-prefixed variables and `RUSTFS_*`.
255///
256/// Precedence rule:
257/// - If both `RUSTFS_*` and source-prefixed variables exist, keep `RUSTFS_*` and record a conflict.
258/// - If only source-prefixed variables exist, mark them as mappable to `RUSTFS_*`.
259pub fn build_external_env_compat_report() -> ExternalEnvCompatReport {
260    build_external_env_compat_report_from_entries(env::vars())
261}
262
263fn parse_env_value<T>(key: &str) -> Option<T>
264where
265    T: std::str::FromStr,
266{
267    let (used_key, value) = resolve_env_with_aliases(key, &[])?;
268    value
269        .parse::<T>()
270        .map_err(|_| {
271            log_once(&format!("env_invalid_value:{used_key}"), || {
272                format!("Invalid {} value for {used_key}. Treating as unset.", type_name::<T>())
273            });
274        })
275        .ok()
276}
277
278pub fn get_env_str_with_aliases(key: &str, deprecated: &[&str], default: &str) -> String {
279    resolve_env_with_aliases(key, deprecated).map_or_else(|| default.to_string(), |(_, value)| value)
280}
281
282pub fn get_env_bool_with_aliases(key: &str, deprecated: &[&str], default: bool) -> bool {
283    let Some((used_key, value)) = resolve_env_with_aliases(key, deprecated) else {
284        return default;
285    };
286
287    parse_bool_str(&value).unwrap_or_else(|| {
288        log_once(
289            &format!("env_invalid_bool:{used_key}"),
290            || {
291                format!(
292                    "Invalid bool value for {used_key}: {value}. Supported values are true/false,1/0,yes/no,on/off. Treating as unset."
293                )
294            },
295        );
296        default
297    })
298}
299
300/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
301/// 16-bit type: signed i16
302///
303/// #Parameters
304/// - `key`: The environment variable key to look up.
305/// - `default`: The default value to return if the environment variable is not set or parsing fails.
306///
307/// #Returns
308/// - `i16`: The parsed value as i16 if successful, otherwise the default value.
309///
310pub fn get_env_i16(key: &str, default: i16) -> i16 {
311    parse_env_value(key).unwrap_or(default)
312}
313/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
314/// 16-bit type: signed i16
315///
316/// #Parameters
317/// - `key`: The environment variable key to look up.
318///
319/// #Returns
320/// - `Option<i16>`: The parsed value as i16 if successful, otherwise None
321///
322pub fn get_env_opt_i16(key: &str) -> Option<i16> {
323    parse_env_value(key)
324}
325
326/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
327/// 16-bit type: unsigned u16
328///
329/// #Parameters
330/// - `key`: The environment variable key to look up.
331/// - `default`: The default value to return if the environment variable is not set or parsing fails.
332///
333/// #Returns
334/// - `u16`: The parsed value as u16 if successful, otherwise the default value.
335///
336pub fn get_env_u16(key: &str, default: u16) -> u16 {
337    parse_env_value(key).unwrap_or(default)
338}
339/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
340/// 16-bit type: unsigned u16
341///
342/// #Parameters
343/// - `key`: The environment variable key to look up.
344///
345/// #Returns
346/// - `Option<u16>`: The parsed value as u16 if successful, otherwise None
347///
348pub fn get_env_u16_opt(key: &str) -> Option<u16> {
349    parse_env_value(key)
350}
351/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
352/// 16-bit type: unsigned u16
353///
354/// #Parameters
355/// - `key`: The environment variable key to look up.
356///
357/// #Returns
358/// - `Option<u16>`: The parsed value as u16 if successful, otherwise None
359///
360pub fn get_env_opt_u16(key: &str) -> Option<u16> {
361    get_env_u16_opt(key)
362}
363
364/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
365/// 32-bit type: signed i32
366///
367/// #Parameters
368/// - `key`: The environment variable key to look up.
369///
370/// #Returns
371/// - `i32`: The parsed value as i32 if successful, otherwise the default value.
372///
373pub fn get_env_i32(key: &str, default: i32) -> i32 {
374    parse_env_value(key).unwrap_or(default)
375}
376
377/// Retrieve an i32 environment variable with deprecated aliases and a default fallback.
378///
379/// Canonical `key` takes precedence over deprecated aliases when both are present.
380pub fn get_env_i32_with_aliases(key: &str, deprecated: &[&str], default: i32) -> i32 {
381    let Some((used_key, value)) = resolve_env_with_aliases(key, deprecated) else {
382        return default;
383    };
384
385    value.parse::<i32>().unwrap_or_else(|_| {
386        log_once(&format!("env_invalid_i32:{used_key}"), || {
387            format!("Invalid i32 value for {used_key}: {value}. Using default behavior.")
388        });
389        default
390    })
391}
392
393/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
394/// 32-bit type: signed i32
395///
396/// #Parameters
397/// - `key`: The environment variable key to look up.
398///
399/// #Returns
400/// - `Option<i32>`: The parsed value as i32 if successful, otherwise None
401///
402pub fn get_env_opt_i32(key: &str) -> Option<i32> {
403    parse_env_value(key)
404}
405
406/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
407/// 32-bit type: unsigned u32
408///
409/// #Parameters
410/// - `key`: The environment variable key to look up.
411/// - `default`: The default value to return if the environment variable is not set or parsing fails.
412///
413/// #Returns
414/// - `u32`: The parsed value as u32 if successful, otherwise the default value.
415///
416pub fn get_env_u32(key: &str, default: u32) -> u32 {
417    parse_env_value(key).unwrap_or(default)
418}
419/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
420/// 32-bit type: unsigned u32
421///
422/// #Parameters
423/// - `key`: The environment variable key to look up.
424///
425/// #Returns
426/// - `Option<u32>`: The parsed value as u32 if successful, otherwise None
427///
428pub fn get_env_opt_u32(key: &str) -> Option<u32> {
429    parse_env_value(key)
430}
431/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
432///
433/// #Parameters
434/// - `key`: The environment variable key to look up.
435/// - `default`: The default value to return if the environment variable is not set or parsing
436///
437/// #Returns
438/// - `f32`: The parsed value as f32 if successful, otherwise the default value
439///
440pub fn get_env_f32(key: &str, default: f32) -> f32 {
441    parse_env_value(key).unwrap_or(default)
442}
443/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
444///
445/// #Parameters
446/// - `key`: The environment variable key to look up.
447///
448/// #Returns
449/// - `Option<f32>`: The parsed value as f32 if successful, otherwise None
450///
451pub fn get_env_opt_f32(key: &str) -> Option<f32> {
452    parse_env_value(key)
453}
454
455/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
456///
457/// #Parameters
458/// - `key`: The environment variable key to look up.
459/// - `default`: The default value to return if the environment variable is not set or parsing
460///
461/// #Returns
462/// - `i64`: The parsed value as i64 if successful, otherwise the default value
463///
464pub fn get_env_i64(key: &str, default: i64) -> i64 {
465    parse_env_value(key).unwrap_or(default)
466}
467/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
468///
469/// #Parameters
470/// - `key`: The environment variable key to look up.
471///
472/// #Returns
473/// - `Option<i64>`: The parsed value as i64 if successful, otherwise None
474///
475pub fn get_env_opt_i64(key: &str) -> Option<i64> {
476    parse_env_value(key)
477}
478
479/// Retrieve an environment variable as a specific type, returning Option<Option<i64>> if not set or parsing fails.
480///
481/// #Parameters
482/// - `key`: The environment variable key to look up.
483///
484/// #Returns
485/// - `Option<Option<i64>>`: The parsed value as i64 if successful, otherwise None
486///
487pub fn get_env_opt_opt_i64(key: &str) -> Option<Option<i64>> {
488    resolve_env_with_aliases(key, &[]).map(|(_, value)| value.parse().ok())
489}
490
491/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
492///
493/// #Parameters
494/// - `key`: The environment variable key to look up.
495/// - `default`: The default value to return if the environment variable is not set or parsing
496///
497/// #Returns
498/// - `u64`: The parsed value as u64 if successful, otherwise the default value.
499///
500pub fn get_env_u64(key: &str, default: u64) -> u64 {
501    parse_env_value(key).unwrap_or(default)
502}
503
504/// Retrieve an environment variable as an unsigned 64-bit integer, returning `None` if not set or parsing fails.
505/// Deprecated aliases are also supported with warning logging.
506///
507/// #Parameters
508/// - `key`: The canonical environment variable key to look up.
509/// - `deprecated`: A list of deprecated keys kept for compatibility.
510///
511/// #Returns
512/// - `Option<u64>`: The parsed value if a key is found and valid, otherwise `None`.
513///
514pub fn get_env_opt_u64_with_aliases(key: &str, deprecated: &[&str]) -> Option<u64> {
515    let (used_key, value) = resolve_env_with_aliases(key, deprecated)?;
516    value
517        .parse::<u64>()
518        .map_err(|_| {
519            log_once(&format!("env_invalid_u64:{used_key}"), || {
520                format!("Invalid u64 value for {used_key}: {value}. Using default behavior.")
521            });
522        })
523        .ok()
524}
525
526/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
527///
528/// #Parameters
529/// - `key`: The environment variable key to look up.
530///
531/// #Returns
532/// - `Option<u64>`: The parsed value as u64 if successful, otherwise None
533///
534pub fn get_env_opt_u64(key: &str) -> Option<u64> {
535    parse_env_value(key)
536}
537
538/// Outcome of reading and parsing an environment variable.
539///
540/// Unlike the `get_env_opt_*` helpers, this distinguishes an absent variable
541/// from one that is present but fails to parse, so callers can treat a
542/// malformed value as a hard configuration error instead of silently falling
543/// back to a default.
544#[derive(Debug, Clone, PartialEq, Eq)]
545pub enum EnvParseOutcome<T> {
546    /// The variable (and any alias) is not set.
547    Absent,
548    /// The variable is set but its value failed to parse into `T`.
549    Invalid,
550    /// The variable is set and parsed successfully.
551    Parsed(T),
552}
553
554/// Read an environment variable and report whether it is absent, present but
555/// malformed, or parsed successfully.
556///
557/// #Parameters
558/// - `key`: The environment variable key to look up (deprecated aliases apply).
559///
560/// #Returns
561/// - `EnvParseOutcome<T>`: `Absent`, `Invalid`, or `Parsed(value)`.
562pub fn get_env_parse_outcome<T>(key: &str) -> EnvParseOutcome<T>
563where
564    T: std::str::FromStr,
565{
566    let Some((used_key, value)) = resolve_env_with_aliases(key, &[]) else {
567        return EnvParseOutcome::Absent;
568    };
569
570    match value.parse::<T>() {
571        Ok(parsed) => EnvParseOutcome::Parsed(parsed),
572        Err(_) => {
573            log_once(&format!("env_invalid_value:{used_key}"), || {
574                format!("Invalid {} value for {used_key}. Treating as unset.", type_name::<T>())
575            });
576            EnvParseOutcome::Invalid
577        }
578    }
579}
580
581/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
582///
583/// #Parameters
584/// - `key`: The environment variable key to look up.
585/// - `default`: The default value to return if the environment variable is not set or parsing
586///
587/// #Returns
588/// - `f64`: The parsed value as f64 if successful, otherwise the default value.
589///
590pub fn get_env_f64(key: &str, default: f64) -> f64 {
591    parse_env_value(key).unwrap_or(default)
592}
593
594/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
595///
596/// #Parameters
597/// - `key`: The environment variable key to look up.
598///
599/// #Returns
600/// - `Option<f64>`: The parsed value as f64 if successful, otherwise None
601///
602pub fn get_env_opt_f64(key: &str) -> Option<f64> {
603    parse_env_value(key)
604}
605
606/// Retrieve an environment variable as a specific type, with a default value if not set or parsing fails.
607///
608/// #Parameters
609/// - `key`: The environment variable key to look up.
610/// - `default`: The default value to return if the environment variable is not set or parsing
611///
612/// #Returns
613/// - `usize`: The parsed value as usize if successful, otherwise the default value.
614///
615pub fn get_env_usize(key: &str, default: usize) -> usize {
616    parse_env_value(key).unwrap_or(default)
617}
618/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
619///
620/// #Parameters
621/// - `key`: The environment variable key to look up.
622///
623/// #Returns
624/// - `Option<usize>`: The parsed value as usize if successful, otherwise None
625///
626pub fn get_env_usize_opt(key: &str) -> Option<usize> {
627    parse_env_value(key)
628}
629
630/// Retrieve an environment variable as a specific type, returning None if not set or parsing fails.
631///
632/// #Parameters
633/// - `key`: The environment variable key to look up.
634///
635/// #Returns
636/// - `Option<usize>`: The parsed value as usize if successful, otherwise None
637///
638pub fn get_env_opt_usize(key: &str) -> Option<usize> {
639    get_env_usize_opt(key)
640}
641
642/// Retrieve an environment variable as a String, with a default value if not set.
643///
644/// #Parameters
645/// - `key`: The environment variable key to look up.
646/// - `default`: The default string value to return if the environment variable is not set.
647///
648/// #Returns
649/// - `String`: The environment variable value if set, otherwise the default value.
650///
651pub fn get_env_str(key: &str, default: &str) -> String {
652    get_env_str_with_aliases(key, &[], default)
653}
654
655/// Retrieve an environment variable as a String, returning None if not set.
656///
657/// #Parameters
658/// - `key`: The environment variable key to look up.
659///
660/// #Returns
661/// - `Option<String>`: The environment variable value if set, otherwise None.
662///
663pub fn get_env_opt_str(key: &str) -> Option<String> {
664    resolve_env_with_aliases(key, &[]).map(|(_, value)| value)
665}
666
667/// Retrieve an environment variable as a boolean, with a default value if not set or parsing fails.
668///
669/// #Parameters
670/// - `key`: The environment variable key to look up.
671/// - `default`: The default boolean value to return if the environment variable is not set or cannot be parsed.
672///
673/// #Returns
674/// - `bool`: The parsed boolean value if successful, otherwise the default value.
675///
676pub fn get_env_bool(key: &str, default: bool) -> bool {
677    get_env_bool_with_aliases(key, &[], default)
678}
679
680/// Parse a string into a boolean value.
681///
682/// #Parameters
683/// - `s`: The string to parse.
684///
685/// #Returns
686/// - `Option<bool>`: The parsed boolean value if successful, otherwise None.
687///
688fn parse_bool_str(s: &str) -> Option<bool> {
689    match s.trim().to_ascii_lowercase().as_str() {
690        "1" | "t" | "true" | "on" | "yes" | "ok" | "success" | "active" | "enabled" => Some(true),
691        "0" | "f" | "false" | "off" | "no" | "not_ok" | "failure" | "inactive" | "disabled" => Some(false),
692        _ => None,
693    }
694}
695
696/// Retrieve an environment variable as a boolean, returning None if not set or parsing fails.
697///
698/// #Parameters
699/// - `key`: The environment variable key to look up.
700///
701/// #Returns
702/// - `Option<bool>`: The parsed boolean value if successful, otherwise None.
703///
704pub fn get_env_opt_bool(key: &str) -> Option<bool> {
705    let (used_key, value) = resolve_env_with_aliases(key, &[])?;
706    parse_bool_str(&value).or_else(|| {
707        log_once(&format!("env_invalid_bool_optional:{used_key}"), || {
708            format!("Invalid bool value for {used_key}: {value}. Supported values are true/false,1/0,yes/no,on/off.")
709        });
710        None
711    })
712}
713
714/// Copy supported external-prefix variables such as `MINIO_*` into their
715/// canonical `RUSTFS_*` names in the current process when the canonical key is
716/// missing.
717#[allow(unsafe_code)]
718pub fn apply_external_env_compat() -> ExternalEnvCompatReport {
719    let report = build_external_env_compat_report();
720    for (source_key, rustfs_key) in &report.mapped_pairs {
721        if let Ok(value) = env::var(source_key) {
722            // SAFETY: this helper is intended for early startup bootstrap
723            // before any background threads are created.
724            unsafe {
725                env::set_var(rustfs_key, value);
726            }
727        }
728    }
729    report
730}
731
732#[cfg(test)]
733mod tests {
734    use super::{
735        EnvParseOutcome, apply_external_env_compat, build_external_env_compat_report_from_entries, get_env_bool_with_aliases,
736        get_env_f64, get_env_i32_with_aliases, get_env_opt_f64, get_env_opt_u64, get_env_parse_outcome, get_env_str, get_env_u64,
737    };
738
739    fn source_key(suffix: &str) -> String {
740        let mut key = super::external_env_prefix().to_string();
741        key.push_str(suffix);
742        key
743    }
744
745    #[test]
746    fn source_value_is_mapped_when_rustfs_missing() {
747        let report =
748            build_external_env_compat_report_from_entries(vec![(source_key("STORAGE_CLASS_STANDARD"), "EC:2".to_string())]);
749        assert_eq!(report.mapped_count(), 1);
750        assert!(
751            report
752                .mapped_pairs
753                .iter()
754                .any(|(input_key, rustfs_key)| input_key == &source_key("STORAGE_CLASS_STANDARD")
755                    && rustfs_key == "RUSTFS_STORAGE_CLASS_STANDARD")
756        );
757        assert_eq!(report.conflict_count(), 0);
758    }
759
760    #[test]
761    fn scanner_aliases_are_mapped_when_rustfs_missing() {
762        let report = build_external_env_compat_report_from_entries(vec![
763            (source_key("SCANNER_SPEED"), "slow".to_string()),
764            (source_key("SCANNER_CYCLE"), "600".to_string()),
765        ]);
766        assert_eq!(report.mapped_count(), 2);
767        assert!(
768            report
769                .mapped_pairs
770                .iter()
771                .any(|(input_key, rustfs_key)| input_key == &source_key("SCANNER_SPEED") && rustfs_key == "RUSTFS_SCANNER_SPEED")
772        );
773        assert!(
774            report
775                .mapped_pairs
776                .iter()
777                .any(|(input_key, rustfs_key)| input_key == &source_key("SCANNER_CYCLE") && rustfs_key == "RUSTFS_SCANNER_CYCLE")
778        );
779        assert_eq!(report.conflict_count(), 0);
780    }
781
782    #[test]
783    fn rustfs_value_takes_precedence_on_conflict() {
784        let report = build_external_env_compat_report_from_entries(vec![
785            ("RUSTFS_ERASURE_SET_DRIVE_COUNT".to_string(), "8".to_string()),
786            (source_key("ERASURE_SET_DRIVE_COUNT"), "16".to_string()),
787        ]);
788        assert_eq!(report.mapped_count(), 0);
789        assert_eq!(report.conflict_count(), 1);
790        assert!(report.conflict_keys.iter().any(|key| key == "RUSTFS_ERASURE_SET_DRIVE_COUNT"));
791    }
792
793    #[test]
794    fn dynamic_notify_suffix_is_mapped() {
795        let report =
796            build_external_env_compat_report_from_entries(vec![(source_key("NOTIFY_WEBHOOK_ENABLE_PRIMARY"), "on".to_string())]);
797        assert_eq!(report.mapped_count(), 1);
798        assert!(
799            report
800                .mapped_pairs
801                .iter()
802                .any(|(input_key, rustfs_key)| input_key == &source_key("NOTIFY_WEBHOOK_ENABLE_PRIMARY")
803                    && rustfs_key == "RUSTFS_NOTIFY_WEBHOOK_ENABLE_PRIMARY")
804        );
805        assert_eq!(report.conflict_count(), 0);
806    }
807
808    #[test]
809    fn unrelated_source_key_is_ignored() {
810        let report = build_external_env_compat_report_from_entries(vec![(source_key("UNKNOWN_COMPAT_TEST"), "1".to_string())]);
811        assert_eq!(report.mapped_count(), 0);
812        assert_eq!(report.conflict_count(), 0);
813    }
814
815    #[test]
816    fn minio_alias_is_used_for_rustfs_reads() {
817        temp_env::with_var("MINIO_ROOT_USER", Some("compat-admin"), || {
818            temp_env::with_var_unset("RUSTFS_ROOT_USER", || {
819                assert_eq!(get_env_str("RUSTFS_ROOT_USER", "default-user"), "compat-admin");
820            });
821        });
822    }
823
824    #[test]
825    fn rustfs_bool_env_takes_precedence_over_minio_alias() {
826        temp_env::with_var("RUSTFS_UNSAFE_BYPASS_DISK_CHECK", Some("false"), || {
827            temp_env::with_var("MINIO_CI", Some("1"), || {
828                assert!(!get_env_bool_with_aliases("RUSTFS_UNSAFE_BYPASS_DISK_CHECK", &["MINIO_CI"], true,));
829            });
830        });
831    }
832
833    #[test]
834    fn i32_alias_value_is_used_when_canonical_missing() {
835        temp_env::with_var_unset("RUSTFS_TEST_I32", || {
836            temp_env::with_var("RUSTFS_TEST_I32_LEGACY", Some("12"), || {
837                assert_eq!(get_env_i32_with_aliases("RUSTFS_TEST_I32", &["RUSTFS_TEST_I32_LEGACY"], 8), 12);
838            });
839        });
840    }
841
842    #[test]
843    fn i32_canonical_value_takes_precedence_over_alias() {
844        temp_env::with_var("RUSTFS_TEST_I32", Some("9"), || {
845            temp_env::with_var("RUSTFS_TEST_I32_LEGACY", Some("12"), || {
846                assert_eq!(get_env_i32_with_aliases("RUSTFS_TEST_I32", &["RUSTFS_TEST_I32_LEGACY"], 8), 9);
847            });
848        });
849    }
850
851    #[test]
852    fn i32_invalid_alias_value_falls_back_to_default() {
853        temp_env::with_var_unset("RUSTFS_TEST_I32", || {
854            temp_env::with_var("RUSTFS_TEST_I32_LEGACY", Some("not-an-i32"), || {
855                assert_eq!(get_env_i32_with_aliases("RUSTFS_TEST_I32", &["RUSTFS_TEST_I32_LEGACY"], 8), 8);
856            });
857        });
858    }
859
860    #[test]
861    fn invalid_u64_value_falls_back_to_default_and_optional_none() {
862        temp_env::with_var("RUSTFS_TEST_U64", Some("not-a-u64"), || {
863            assert_eq!(get_env_u64("RUSTFS_TEST_U64", 42), 42);
864            assert_eq!(get_env_opt_u64("RUSTFS_TEST_U64"), None);
865        });
866    }
867
868    #[test]
869    fn invalid_f64_value_falls_back_to_default_and_optional_none() {
870        temp_env::with_var("RUSTFS_TEST_F64", Some("not-a-f64"), || {
871            assert_eq!(get_env_f64("RUSTFS_TEST_F64", 0.25), 0.25);
872            assert_eq!(get_env_opt_f64("RUSTFS_TEST_F64"), None);
873        });
874    }
875
876    #[test]
877    fn env_parse_outcome_distinguishes_absent_invalid_and_parsed() {
878        temp_env::with_var_unset("RUSTFS_TEST_OUTCOME", || {
879            assert_eq!(get_env_parse_outcome::<u64>("RUSTFS_TEST_OUTCOME"), EnvParseOutcome::Absent);
880        });
881        temp_env::with_var("RUSTFS_TEST_OUTCOME", Some("not-a-u64"), || {
882            assert_eq!(get_env_parse_outcome::<u64>("RUSTFS_TEST_OUTCOME"), EnvParseOutcome::Invalid);
883        });
884        temp_env::with_var("RUSTFS_TEST_OUTCOME", Some("42"), || {
885            assert_eq!(get_env_parse_outcome::<u64>("RUSTFS_TEST_OUTCOME"), EnvParseOutcome::Parsed(42));
886        });
887    }
888
889    #[test]
890    fn apply_external_env_compat_copies_missing_rustfs_keys() {
891        temp_env::with_var("MINIO_ROOT_USER", Some("compat-admin"), || {
892            temp_env::with_var_unset("RUSTFS_ROOT_USER", || {
893                let report = apply_external_env_compat();
894                assert!(
895                    report
896                        .mapped_pairs
897                        .iter()
898                        .any(|(source_key, rustfs_key)| source_key == "MINIO_ROOT_USER" && rustfs_key == "RUSTFS_ROOT_USER")
899                );
900                assert_eq!(std::env::var("RUSTFS_ROOT_USER").as_deref(), Ok("compat-admin"));
901            });
902        });
903    }
904
905    #[test]
906    fn external_env_compat_includes_api_object_max_versions() {
907        let report =
908            build_external_env_compat_report_from_entries([("MINIO_API_OBJECT_MAX_VERSIONS".to_string(), "50000".to_string())]);
909
910        assert_eq!(
911            report.mapped_pairs,
912            vec![("MINIO_API_OBJECT_MAX_VERSIONS".to_string(), "RUSTFS_API_OBJECT_MAX_VERSIONS".to_string())]
913        );
914    }
915}