omni_dev/utils/env.rs
1//! Environment-variable dependency-injection seam.
2//!
3//! Production code reads the process environment only through an
4//! [`EnvSource`]. The real implementation, [`SystemEnv`], delegates to
5//! [`std::env::var`]; tests inject a pure in-memory fake
6//! (`crate::test_support::env::MapEnv`) instead of mutating the
7//! process-global environment.
8//!
9//! This removes the shared mutable global that the cross-module test race
10//! (issue #821) and the per-module env mutexes (#950, #1030) were fighting
11//! over: a test that constructs its own [`EnvSource`] never touches process
12//! env, so it needs no lock and runs fully in parallel. See
13//! [STYLE-0027](../../docs/STYLE_GUIDE.md) and `docs/plan/issue-1030-env-di.md`.
14//!
15//! `EnvSource` abstracts the **raw** environment only. The
16//! settings.json fallback layer composes on top of it — see
17//! [`crate::utils::settings`].
18
19/// A read-only view of environment variables.
20///
21/// Implemented by [`SystemEnv`] (the real process environment) in production
22/// and by an in-memory map in tests, so env-parsing boundaries can be tested
23/// without mutating the process-global environment.
24pub trait EnvSource {
25 /// Returns the value of `key`, or `None` if it is unset (or, for the
26 /// process environment, not valid Unicode).
27 fn var(&self, key: &str) -> Option<String>;
28
29 /// Returns the first set value among `keys`, in order.
30 fn var_any(&self, keys: &[&str]) -> Option<String> {
31 keys.iter().find_map(|k| self.var(k))
32 }
33}
34
35/// The real process environment, backed by [`std::env::var`].
36///
37/// This is the production [`EnvSource`]; pass `&SystemEnv` from the thin
38/// env-resolving wrapper that fronts each boundary seam.
39#[derive(Debug, Clone, Copy, Default)]
40pub struct SystemEnv;
41
42impl EnvSource for SystemEnv {
43 fn var(&self, key: &str) -> Option<String> {
44 std::env::var(key).ok()
45 }
46}
47
48/// `&T` is an `EnvSource` whenever `T` is, so callers can pass `&SystemEnv`
49/// or `&map_env` to functions taking `&impl EnvSource` without ceremony.
50impl<T: EnvSource + ?Sized> EnvSource for &T {
51 fn var(&self, key: &str) -> Option<String> {
52 (**self).var(key)
53 }
54}
55
56#[cfg(test)]
57#[allow(clippy::unwrap_used)]
58mod tests {
59 use super::*;
60 use crate::test_support::env::MapEnv;
61
62 #[test]
63 fn map_env_returns_inserted_values_and_none_otherwise() {
64 let env = MapEnv::new().with("USE_OPENAI", "true");
65 assert_eq!(env.var("USE_OPENAI").as_deref(), Some("true"));
66 assert_eq!(env.var("MISSING"), None);
67 }
68
69 #[test]
70 fn var_any_returns_first_set_key() {
71 let env = MapEnv::new().with("ANTHROPIC_API_KEY", "k");
72 assert_eq!(
73 env.var_any(&["CLAUDE_API_KEY", "ANTHROPIC_API_KEY"])
74 .as_deref(),
75 Some("k")
76 );
77 assert_eq!(env.var_any(&["A", "B"]), None);
78 }
79
80 #[test]
81 fn reference_forwards_to_inner_source() {
82 let env = MapEnv::new().with("K", "v");
83 fn read(src: &impl EnvSource) -> Option<String> {
84 src.var("K")
85 }
86 // &MapEnv must itself satisfy `impl EnvSource`.
87 assert_eq!(read(&&env).as_deref(), Some("v"));
88 }
89}