hyperlane-plugin-env 23.3.0

A zero-dependency .env parser, layered typed environment configuration loader, redacting SecretValue wrapper, and HYPERLANE_* ServerConfig builder plugin for the Hyperlane framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use super::*;

/// Formats [`EnvError`] for diagnostics.
impl Display for EnvError {
    /// Renders a human-readable environment configuration error.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Missing(k) => write!(f, "{ERR_MISSING}: {k}"),
            Self::Parse { key, reason } => write!(f, "{ERR_PARSE} '{key}': {reason}"),
            Self::Syntax { line, reason } => write!(f, "{ERR_SYNTAX} at line {line}: {reason}"),
            Self::Io(msg) => write!(f, "{ERR_IO}: {msg}"),
        }
    }
}

/// Marks [`EnvError`] as a standard error type.
impl Error for EnvError {}

/// Constructors and safe exposure methods for [`SecretValue`].
impl SecretValue {
    /// Wraps a raw secret string in [`SecretValue`].
    ///
    /// # Arguments
    ///
    /// - `S` - Secret value.
    ///
    /// # Returns
    ///
    /// - `Self` - Redacting wrapper.
    pub fn new<S>(value: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            inner: value.into(),
        }
    }

    /// Explicitly exposes the underlying secret slice at the exact use site.
    ///
    /// # Returns
    ///
    /// - `&str` - Underlying secret value.
    #[inline(always)]
    pub fn expose(&self) -> &str {
        let Self { inner } = self;
        inner.as_str()
    }

    /// Reports whether the secret is empty.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when empty.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        let Self { inner } = self;
        inner.is_empty()
    }
}

/// Redacts [`SecretValue`] in `Debug` output.
impl Debug for SecretValue {
    /// Writes `[REDACTED]`.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(REDACTED_MARKER)
    }
}

/// Redacts [`SecretValue`] in `Display` output.
impl Display for SecretValue {
    /// Writes `[REDACTED]`.
    ///
    /// # Arguments
    ///
    /// - `&mut Formatter<'_>` - Output formatter.
    ///
    /// # Returns
    ///
    /// - `fmt::Result` - Formatting outcome.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.write_str(REDACTED_MARKER)
    }
}

/// Layered loading, typed extraction, and Hyperlane [`ServerConfig`] assembly for [`EnvPlugin`].
impl EnvPlugin {
    /// Creates an empty [`EnvPlugin`] with no prefix.
    ///
    /// # Returns
    ///
    /// - `Self` - Empty configuration loader.
    pub fn new() -> Self {
        Self::default()
    }

    /// Loads current OS process environment variables into a new [`EnvPlugin`].
    ///
    /// # Returns
    ///
    /// - `Self` - Configuration populated from OS environment.
    pub fn from_process_env() -> Self {
        let mut loader: Self = Self::new();
        let _: &mut Self = loader.merge_process_env();
        loader
    }

    /// Parses `.env` text into a new [`EnvPlugin`].
    ///
    /// # Arguments
    ///
    /// - `&str` - `.env` content string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, EnvError>` - Loaded environment configuration or syntax error.
    pub fn from_dotenv_str(content: &str) -> Result<Self, EnvError> {
        let values: BTreeMap<String, String> = parse_dotenv(content)?;
        Ok(Self {
            prefix: String::new(),
            values,
        })
    }

    /// Sets the automatic key prefix (for example [`DEFAULT_ENV_PREFIX`] `"HYPERLANE_"`).
    ///
    /// # Arguments
    ///
    /// - `S` - Prefix string.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated loader.
    pub fn with_prefix<S>(self, prefix: S) -> Self
    where
        S: Into<String>,
    {
        Self {
            prefix: prefix.into(),
            ..self
        }
    }

    /// Initializes the global [`EnvPlugin`] singleton once.
    ///
    /// # Arguments
    ///
    /// - `Self` - Loaded environment configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init(plugin: Self) -> &'static Self {
        ENV_PLUGIN.get_or_init(|| plugin)
    }

    /// Returns the initialized global [`EnvPlugin`], if initialized.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        ENV_PLUGIN.get()
    }

    /// Merges all entries from a `.env` file on disk into `self`.
    ///
    /// # Arguments
    ///
    /// - `&Path` - Path to `.env` file.
    ///
    /// # Returns
    ///
    /// - `Result<&mut Self, EnvError>` - Mutable reference or I/O/syntax error.
    pub fn merge_dotenv_file(&mut self, path: &Path) -> Result<&mut Self, EnvError> {
        let content: String =
            fs::read_to_string(path).map_err(|e: io::Error| EnvError::Io(e.to_string()))?;
        let parsed: BTreeMap<String, String> = parse_dotenv(&content)?;
        let Self { values, .. } = self;
        values.extend(parsed);
        Ok(self)
    }

    /// Merges OS process environment variables on top of existing entries.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for chaining.
    pub fn merge_process_env(&mut self) -> &mut Self {
        let Self { values, .. } = self;
        for (k, v) in env::vars() {
            let _: Option<String> = values.insert(k, v);
        }
        self
    }

    /// Sets or overrides a single key-value pair.
    ///
    /// # Arguments
    ///
    /// - `K` - Key name.
    /// - `V` - Value string.
    ///
    /// # Returns
    ///
    /// - `&mut Self` - Mutable reference for chaining.
    pub fn set<K, V>(&mut self, key: K, value: V) -> &mut Self
    where
        K: Into<String>,
        V: Into<String>,
    {
        let Self { values, .. } = self;
        let _: Option<String> = values.insert(key.into(), value.into());
        self
    }

    /// Resolves the full lookup key by prepending `prefix` when configured.
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical key name.
    ///
    /// # Returns
    ///
    /// - `String` - Prefixed key name.
    fn full_key(&self, key: &str) -> String {
        let Self { prefix, .. } = self;
        if prefix.is_empty() {
            key.to_owned()
        } else {
            format!("{prefix}{key}")
        }
    }

    /// Looks up a raw string value by key (honoring any configured prefix).
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical key name.
    ///
    /// # Returns
    ///
    /// - `Option<&str>` - Stored string value if present.
    pub fn get_str(&self, key: &str) -> Option<&str> {
        let Self { values, .. } = self;
        let resolved: String = self.full_key(key);
        values.get(&resolved).map(String::as_str)
    }

    /// Reads a required string value or returns [`EnvError::Missing`].
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical key name.
    ///
    /// # Returns
    ///
    /// - `Result<String, EnvError>` - String value or missing error.
    pub fn require_string(&self, key: &str) -> Result<String, EnvError> {
        self.get_str(key)
            .map(str::to_owned)
            .ok_or_else(|| EnvError::Missing(self.full_key(key)))
    }

    /// Reads a secret value wrapped in [`SecretValue`].
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical key name.
    ///
    /// # Returns
    ///
    /// - `Result<SecretValue, EnvError>` - Secret wrapper or missing error.
    pub fn require_secret(&self, key: &str) -> Result<SecretValue, EnvError> {
        self.require_string(key).map(SecretValue::new)
    }

    /// Parses an optional value into any [`FromStr`] type.
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical key name.
    ///
    /// # Returns
    ///
    /// - `Result<Option<T>, EnvError>` - Parsed value if set, `Ok(None)` if absent, or parse error.
    pub fn get_parse<T>(&self, key: &str) -> Result<Option<T>, EnvError>
    where
        T: FromStr,
        T::Err: Display,
    {
        let Some(raw) = self.get_str(key) else {
            return Ok(None);
        };
        let parsed: T = raw
            .trim()
            .parse::<T>()
            .map_err(|e: T::Err| EnvError::Parse {
                key: self.full_key(key),
                reason: e.to_string(),
            })?;
        Ok(Some(parsed))
    }

    /// Parses an optional human-friendly boolean (`true/false/1/0/yes/no/on/off`).
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical key name.
    ///
    /// # Returns
    ///
    /// - `Result<Option<bool>, EnvError>` - Parsed bool, `None` when absent, or parse error.
    pub fn get_bool(&self, key: &str) -> Result<Option<bool>, EnvError> {
        let Some(raw) = self.get_str(key) else {
            return Ok(None);
        };
        let lower: String = raw.trim().to_ascii_lowercase();
        match lower.as_str() {
            BOOL_TRUE | "1" | "yes" | "on" => Ok(Some(true)),
            BOOL_FALSE | "0" | "no" | "off" => Ok(Some(false)),
            _ => Err(EnvError::Parse {
                key: self.full_key(key),
                reason: ERR_INVALID_BOOL.to_owned(),
            }),
        }
    }

    /// Parses an optional duration string (`"250ms"`, `"30s"`, `"5m"`, `"1h"`).
    ///
    /// # Arguments
    ///
    /// - `&str` - Logical key name.
    ///
    /// # Returns
    ///
    /// - `Result<Option<Duration>, EnvError>` - Parsed duration, `None` when absent, or parse error.
    pub fn get_duration(&self, key: &str) -> Result<Option<Duration>, EnvError> {
        let Some(raw) = self.get_str(key) else {
            return Ok(None);
        };
        let t: &str = raw.trim();
        let dur: Option<Duration> = if let Some(s) = t.strip_suffix("ms") {
            s.trim().parse::<u64>().ok().map(Duration::from_millis)
        } else if let Some(s) = t.strip_suffix('s') {
            s.trim().parse::<u64>().ok().map(Duration::from_secs)
        } else if let Some(s) = t.strip_suffix('m') {
            s.trim()
                .parse::<u64>()
                .ok()
                .map(|v: u64| Duration::from_secs(v.saturating_mul(60)))
        } else if let Some(s) = t.strip_suffix('h') {
            s.trim()
                .parse::<u64>()
                .ok()
                .map(|v: u64| Duration::from_secs(v.saturating_mul(3600)))
        } else {
            t.parse::<u64>().ok().map(Duration::from_secs)
        };
        match dur {
            Some(d) => Ok(Some(d)),
            None => Err(EnvError::Parse {
                key: self.full_key(key),
                reason: ERR_INVALID_DURATION.to_owned(),
            }),
        }
    }

    /// Builds a Hyperlane [`ServerConfig`] from `ADDRESS`/`HOST`+`PORT`, `NODELAY`, `TTL`, `PROTOCOL`, and `TLS_CERT`/`TLS_KEY`.
    ///
    /// # Returns
    ///
    /// - `Result<ServerConfig, EnvError>` - Populated [`ServerConfig`] or parse error.
    pub fn load_server_config(&self) -> Result<ServerConfig, EnvError> {
        let mut cfg: ServerConfig = ServerConfig::default();
        if let Some(addr) = self.get_str(KEY_ADDRESS) {
            cfg.set_address(addr.trim());
        } else if let (Some(host), Some(port)) = (self.get_str(KEY_HOST), self.get_str(KEY_PORT)) {
            cfg.set_address(format!("{}:{}", host.trim(), port.trim()));
        }
        if let Some(nodelay) = self.get_bool(KEY_NODELAY)? {
            cfg.set_nodelay(Some(nodelay));
        }
        let ttl: Option<u32> = self.get_parse(KEY_TTL)?;
        if let Some(ttl_val) = ttl {
            cfg.set_ttl(Some(ttl_val));
        }
        if let Some(proto_raw) = self.get_str(KEY_PROTOCOL) {
            let proto: ServerProtocol = match proto_raw.trim().to_ascii_lowercase().as_str() {
                PROTO_HTTP1 => ServerProtocol::Http1,
                PROTO_HTTP2 => ServerProtocol::Http2,
                PROTO_HTTP3 => ServerProtocol::Http3,
                _ => {
                    return Err(EnvError::Parse {
                        key: self.full_key(KEY_PROTOCOL),
                        reason: ERR_INVALID_PROTOCOL.to_owned(),
                    });
                }
            };
            cfg.set_protocol(proto);
        }
        if let (Some(cert), Some(key)) = (self.get_str(KEY_TLS_CERT), self.get_str(KEY_TLS_KEY)) {
            cfg.set_tls(Some(TlsConfig::new(
                cert.trim().to_owned(),
                key.trim().to_owned(),
            )));
        }
        Ok(cfg)
    }
}