Skip to main content

hyperlane_plugin_env/
impl.rs

1use super::*;
2
3/// Formats [`EnvError`] for diagnostics.
4impl Display for EnvError {
5    /// Renders a human-readable environment configuration error.
6    ///
7    /// # Arguments
8    ///
9    /// - `&mut Formatter<'_>` - Output formatter.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - Formatting outcome.
14    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
15        match self {
16            Self::Missing(k) => write!(f, "{ERR_MISSING}: {k}"),
17            Self::Parse { key, reason } => write!(f, "{ERR_PARSE} '{key}': {reason}"),
18            Self::Syntax { line, reason } => write!(f, "{ERR_SYNTAX} at line {line}: {reason}"),
19            Self::Io(msg) => write!(f, "{ERR_IO}: {msg}"),
20        }
21    }
22}
23
24/// Marks [`EnvError`] as a standard error type.
25impl Error for EnvError {}
26
27/// Constructors and safe exposure methods for [`SecretValue`].
28impl SecretValue {
29    /// Wraps a raw secret string in [`SecretValue`].
30    ///
31    /// # Arguments
32    ///
33    /// - `S` - Secret value.
34    ///
35    /// # Returns
36    ///
37    /// - `Self` - Redacting wrapper.
38    pub fn new<S>(value: S) -> Self
39    where
40        S: Into<String>,
41    {
42        Self {
43            inner: value.into(),
44        }
45    }
46
47    /// Explicitly exposes the underlying secret slice at the exact use site.
48    ///
49    /// # Returns
50    ///
51    /// - `&str` - Underlying secret value.
52    #[inline(always)]
53    pub fn expose(&self) -> &str {
54        let Self { inner } = self;
55        inner.as_str()
56    }
57
58    /// Reports whether the secret is empty.
59    ///
60    /// # Returns
61    ///
62    /// - `bool` - `true` when empty.
63    #[inline(always)]
64    pub fn is_empty(&self) -> bool {
65        let Self { inner } = self;
66        inner.is_empty()
67    }
68}
69
70/// Redacts [`SecretValue`] in `Debug` output.
71impl Debug for SecretValue {
72    /// Writes `[REDACTED]`.
73    ///
74    /// # Arguments
75    ///
76    /// - `&mut Formatter<'_>` - Output formatter.
77    ///
78    /// # Returns
79    ///
80    /// - `fmt::Result` - Formatting outcome.
81    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
82        f.write_str(REDACTED_MARKER)
83    }
84}
85
86/// Redacts [`SecretValue`] in `Display` output.
87impl Display for SecretValue {
88    /// Writes `[REDACTED]`.
89    ///
90    /// # Arguments
91    ///
92    /// - `&mut Formatter<'_>` - Output formatter.
93    ///
94    /// # Returns
95    ///
96    /// - `fmt::Result` - Formatting outcome.
97    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
98        f.write_str(REDACTED_MARKER)
99    }
100}
101
102/// Layered loading, typed extraction, and Hyperlane [`ServerConfig`] assembly for [`EnvPlugin`].
103impl EnvPlugin {
104    /// Creates an empty [`EnvPlugin`] with no prefix.
105    ///
106    /// # Returns
107    ///
108    /// - `Self` - Empty configuration loader.
109    pub fn new() -> Self {
110        Self::default()
111    }
112
113    /// Loads current OS process environment variables into a new [`EnvPlugin`].
114    ///
115    /// # Returns
116    ///
117    /// - `Self` - Configuration populated from OS environment.
118    pub fn from_process_env() -> Self {
119        let mut loader: Self = Self::new();
120        let _: &mut Self = loader.merge_process_env();
121        loader
122    }
123
124    /// Parses `.env` text into a new [`EnvPlugin`].
125    ///
126    /// # Arguments
127    ///
128    /// - `&str` - `.env` content string.
129    ///
130    /// # Returns
131    ///
132    /// - `Result<Self, EnvError>` - Loaded environment configuration or syntax error.
133    pub fn from_dotenv_str(content: &str) -> Result<Self, EnvError> {
134        let values: BTreeMap<String, String> = parse_dotenv(content)?;
135        Ok(Self {
136            prefix: String::new(),
137            values,
138        })
139    }
140
141    /// Sets the automatic key prefix (for example [`DEFAULT_ENV_PREFIX`] `"HYPERLANE_"`).
142    ///
143    /// # Arguments
144    ///
145    /// - `S` - Prefix string.
146    ///
147    /// # Returns
148    ///
149    /// - `Self` - Updated loader.
150    pub fn with_prefix<S>(self, prefix: S) -> Self
151    where
152        S: Into<String>,
153    {
154        Self {
155            prefix: prefix.into(),
156            ..self
157        }
158    }
159
160    /// Initializes the global [`EnvPlugin`] singleton once.
161    ///
162    /// # Arguments
163    ///
164    /// - `Self` - Loaded environment configuration.
165    ///
166    /// # Returns
167    ///
168    /// - `&'static Self` - Reference to the global plugin.
169    pub fn init(plugin: Self) -> &'static Self {
170        ENV_PLUGIN.get_or_init(|| plugin)
171    }
172
173    /// Returns the initialized global [`EnvPlugin`], if initialized.
174    ///
175    /// # Returns
176    ///
177    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
178    #[inline(always)]
179    pub fn get() -> Option<&'static Self> {
180        ENV_PLUGIN.get()
181    }
182
183    /// Merges all entries from a `.env` file on disk into `self`.
184    ///
185    /// # Arguments
186    ///
187    /// - `&Path` - Path to `.env` file.
188    ///
189    /// # Returns
190    ///
191    /// - `Result<&mut Self, EnvError>` - Mutable reference or I/O/syntax error.
192    pub fn merge_dotenv_file(&mut self, path: &Path) -> Result<&mut Self, EnvError> {
193        let content: String =
194            fs::read_to_string(path).map_err(|e: io::Error| EnvError::Io(e.to_string()))?;
195        let parsed: BTreeMap<String, String> = parse_dotenv(&content)?;
196        let Self { values, .. } = self;
197        values.extend(parsed);
198        Ok(self)
199    }
200
201    /// Merges OS process environment variables on top of existing entries.
202    ///
203    /// # Returns
204    ///
205    /// - `&mut Self` - Mutable reference for chaining.
206    pub fn merge_process_env(&mut self) -> &mut Self {
207        let Self { values, .. } = self;
208        for (k, v) in env::vars() {
209            let _: Option<String> = values.insert(k, v);
210        }
211        self
212    }
213
214    /// Sets or overrides a single key-value pair.
215    ///
216    /// # Arguments
217    ///
218    /// - `K` - Key name.
219    /// - `V` - Value string.
220    ///
221    /// # Returns
222    ///
223    /// - `&mut Self` - Mutable reference for chaining.
224    pub fn set<K, V>(&mut self, key: K, value: V) -> &mut Self
225    where
226        K: Into<String>,
227        V: Into<String>,
228    {
229        let Self { values, .. } = self;
230        let _: Option<String> = values.insert(key.into(), value.into());
231        self
232    }
233
234    /// Resolves the full lookup key by prepending `prefix` when configured.
235    ///
236    /// # Arguments
237    ///
238    /// - `&str` - Logical key name.
239    ///
240    /// # Returns
241    ///
242    /// - `String` - Prefixed key name.
243    fn full_key(&self, key: &str) -> String {
244        let Self { prefix, .. } = self;
245        if prefix.is_empty() {
246            key.to_owned()
247        } else {
248            format!("{prefix}{key}")
249        }
250    }
251
252    /// Looks up a raw string value by key (honoring any configured prefix).
253    ///
254    /// # Arguments
255    ///
256    /// - `&str` - Logical key name.
257    ///
258    /// # Returns
259    ///
260    /// - `Option<&str>` - Stored string value if present.
261    pub fn get_str(&self, key: &str) -> Option<&str> {
262        let Self { values, .. } = self;
263        let resolved: String = self.full_key(key);
264        values.get(&resolved).map(String::as_str)
265    }
266
267    /// Reads a required string value or returns [`EnvError::Missing`].
268    ///
269    /// # Arguments
270    ///
271    /// - `&str` - Logical key name.
272    ///
273    /// # Returns
274    ///
275    /// - `Result<String, EnvError>` - String value or missing error.
276    pub fn require_string(&self, key: &str) -> Result<String, EnvError> {
277        self.get_str(key)
278            .map(str::to_owned)
279            .ok_or_else(|| EnvError::Missing(self.full_key(key)))
280    }
281
282    /// Reads a secret value wrapped in [`SecretValue`].
283    ///
284    /// # Arguments
285    ///
286    /// - `&str` - Logical key name.
287    ///
288    /// # Returns
289    ///
290    /// - `Result<SecretValue, EnvError>` - Secret wrapper or missing error.
291    pub fn require_secret(&self, key: &str) -> Result<SecretValue, EnvError> {
292        self.require_string(key).map(SecretValue::new)
293    }
294
295    /// Parses an optional value into any [`FromStr`] type.
296    ///
297    /// # Arguments
298    ///
299    /// - `&str` - Logical key name.
300    ///
301    /// # Returns
302    ///
303    /// - `Result<Option<T>, EnvError>` - Parsed value if set, `Ok(None)` if absent, or parse error.
304    pub fn get_parse<T>(&self, key: &str) -> Result<Option<T>, EnvError>
305    where
306        T: FromStr,
307        T::Err: Display,
308    {
309        let Some(raw) = self.get_str(key) else {
310            return Ok(None);
311        };
312        let parsed: T = raw
313            .trim()
314            .parse::<T>()
315            .map_err(|e: T::Err| EnvError::Parse {
316                key: self.full_key(key),
317                reason: e.to_string(),
318            })?;
319        Ok(Some(parsed))
320    }
321
322    /// Parses an optional human-friendly boolean (`true/false/1/0/yes/no/on/off`).
323    ///
324    /// # Arguments
325    ///
326    /// - `&str` - Logical key name.
327    ///
328    /// # Returns
329    ///
330    /// - `Result<Option<bool>, EnvError>` - Parsed bool, `None` when absent, or parse error.
331    pub fn get_bool(&self, key: &str) -> Result<Option<bool>, EnvError> {
332        let Some(raw) = self.get_str(key) else {
333            return Ok(None);
334        };
335        let lower: String = raw.trim().to_ascii_lowercase();
336        match lower.as_str() {
337            BOOL_TRUE | "1" | "yes" | "on" => Ok(Some(true)),
338            BOOL_FALSE | "0" | "no" | "off" => Ok(Some(false)),
339            _ => Err(EnvError::Parse {
340                key: self.full_key(key),
341                reason: ERR_INVALID_BOOL.to_owned(),
342            }),
343        }
344    }
345
346    /// Parses an optional duration string (`"250ms"`, `"30s"`, `"5m"`, `"1h"`).
347    ///
348    /// # Arguments
349    ///
350    /// - `&str` - Logical key name.
351    ///
352    /// # Returns
353    ///
354    /// - `Result<Option<Duration>, EnvError>` - Parsed duration, `None` when absent, or parse error.
355    pub fn get_duration(&self, key: &str) -> Result<Option<Duration>, EnvError> {
356        let Some(raw) = self.get_str(key) else {
357            return Ok(None);
358        };
359        let t: &str = raw.trim();
360        let dur: Option<Duration> = if let Some(s) = t.strip_suffix("ms") {
361            s.trim().parse::<u64>().ok().map(Duration::from_millis)
362        } else if let Some(s) = t.strip_suffix('s') {
363            s.trim().parse::<u64>().ok().map(Duration::from_secs)
364        } else if let Some(s) = t.strip_suffix('m') {
365            s.trim()
366                .parse::<u64>()
367                .ok()
368                .map(|v: u64| Duration::from_secs(v.saturating_mul(60)))
369        } else if let Some(s) = t.strip_suffix('h') {
370            s.trim()
371                .parse::<u64>()
372                .ok()
373                .map(|v: u64| Duration::from_secs(v.saturating_mul(3600)))
374        } else {
375            t.parse::<u64>().ok().map(Duration::from_secs)
376        };
377        match dur {
378            Some(d) => Ok(Some(d)),
379            None => Err(EnvError::Parse {
380                key: self.full_key(key),
381                reason: ERR_INVALID_DURATION.to_owned(),
382            }),
383        }
384    }
385
386    /// Builds a Hyperlane [`ServerConfig`] from `ADDRESS`/`HOST`+`PORT`, `NODELAY`, `TTL`, `PROTOCOL`, and `TLS_CERT`/`TLS_KEY`.
387    ///
388    /// # Returns
389    ///
390    /// - `Result<ServerConfig, EnvError>` - Populated [`ServerConfig`] or parse error.
391    pub fn load_server_config(&self) -> Result<ServerConfig, EnvError> {
392        let mut cfg: ServerConfig = ServerConfig::default();
393        if let Some(addr) = self.get_str(KEY_ADDRESS) {
394            cfg.set_address(addr.trim());
395        } else if let (Some(host), Some(port)) = (self.get_str(KEY_HOST), self.get_str(KEY_PORT)) {
396            cfg.set_address(format!("{}:{}", host.trim(), port.trim()));
397        }
398        if let Some(nodelay) = self.get_bool(KEY_NODELAY)? {
399            cfg.set_nodelay(Some(nodelay));
400        }
401        let ttl: Option<u32> = self.get_parse(KEY_TTL)?;
402        if let Some(ttl_val) = ttl {
403            cfg.set_ttl(Some(ttl_val));
404        }
405        if let Some(proto_raw) = self.get_str(KEY_PROTOCOL) {
406            let proto: ServerProtocol = match proto_raw.trim().to_ascii_lowercase().as_str() {
407                PROTO_HTTP1 => ServerProtocol::Http1,
408                PROTO_HTTP2 => ServerProtocol::Http2,
409                PROTO_HTTP3 => ServerProtocol::Http3,
410                _ => {
411                    return Err(EnvError::Parse {
412                        key: self.full_key(KEY_PROTOCOL),
413                        reason: ERR_INVALID_PROTOCOL.to_owned(),
414                    });
415                }
416            };
417            cfg.set_protocol(proto);
418        }
419        if let (Some(cert), Some(key)) = (self.get_str(KEY_TLS_CERT), self.get_str(KEY_TLS_KEY)) {
420            cfg.set_tls(Some(TlsConfig::new(
421                cert.trim().to_owned(),
422                key.trim().to_owned(),
423            )));
424        }
425        Ok(cfg)
426    }
427}