Skip to main content

astrs_node_api/
env.rs

1//! The environment surface a node reads at start-up (blueprint §24.2).
2//!
3//! Everything here is *read*, never written: a node inspects its environment
4//! once, during `init`, and from then on the values live in typed fields. The
5//! module exists so that the set of variables AstRS reads is enumerable in one
6//! place — `astrs doctor` (§17) prints exactly this table.
7//!
8//! | Variable | Read by | Default |
9//! |---|---|---|
10//! | `ASTRS_NODE_CONFIG` | [`crate::Node::init_from_env`] | — (required) |
11//! | `ASTRS_RUN_PARENT_PID` | the orphan guard (§4.2) | no guard |
12//! | `ASTRS_DAEMON_PORT` | dynamic attach (§8.3) | 7408 |
13//! | `ASTRS_RUNTIME_DIR` | dynamic attach | `$XDG_RUNTIME_DIR/astrs` |
14//! | `ASTRS_ZERO_COPY_THRESHOLD` | the send path (§6.2) | 4096 |
15//! | `ASTRS_TYPE_CHECK` | typed handles (§9.2) | `warn` |
16//!
17//! # Examples
18//!
19//! ```
20//! use astrs_node_api::env::TypeCheckMode;
21//!
22//! assert_eq!("warn".parse(), Ok(TypeCheckMode::Warn));
23//! assert!(TypeCheckMode::Error.is_fatal());
24//! assert!(!TypeCheckMode::default().is_fatal(), "0.1.0 defaults to warn");
25//! ```
26
27use std::path::PathBuf;
28use std::str::FromStr;
29
30use astrs_wire::{DEFAULT_ZERO_COPY_THRESHOLD, ENV_NODE_CONFIG, ENV_RUN_PARENT_PID};
31
32use crate::error::{NodeError, Result};
33
34/// The environment variable overriding the daemon's loopback node port.
35pub const ENV_DAEMON_PORT: &str = "ASTRS_DAEMON_PORT";
36
37/// The environment variable overriding the runtime directory.
38pub const ENV_RUNTIME_DIR: &str = "ASTRS_RUNTIME_DIR";
39
40/// The environment variable overriding the zero-copy threshold.
41pub const ENV_ZERO_COPY_THRESHOLD: &str = "ASTRS_ZERO_COPY_THRESHOLD";
42
43/// The environment variable selecting the runtime type-check mode (§9.2).
44pub const ENV_TYPE_CHECK: &str = "ASTRS_TYPE_CHECK";
45
46/// The freedesktop variable the default runtime directory is derived from.
47pub const ENV_XDG_RUNTIME_DIR: &str = "XDG_RUNTIME_DIR";
48
49/// The daemon's loopback node port (§24.2).
50pub const DEFAULT_DAEMON_PORT: u16 = 7408;
51
52/// The runtime directory leaf appended to `$XDG_RUNTIME_DIR`.
53pub const RUNTIME_DIR_LEAF: &str = "astrs";
54
55/// The daemon's Unix-domain socket name inside the runtime directory (§4.2).
56pub const DAEMON_SOCKET_NAME: &str = "daemon.sock";
57
58/// The shared-memory broker socket name inside the runtime directory (§6.2).
59pub const SHM_BROKER_SOCKET_NAME: &str = "shm.sock";
60
61/// Every environment variable this crate reads, in documentation order.
62///
63/// # Examples
64///
65/// ```
66/// use astrs_node_api::env;
67///
68/// assert!(env::READ_VARIABLES.contains(&"ASTRS_TYPE_CHECK"));
69/// assert_eq!(env::READ_VARIABLES.len(), 7);
70/// ```
71pub const READ_VARIABLES: &[&str] = &[
72    ENV_NODE_CONFIG,
73    ENV_RUN_PARENT_PID,
74    ENV_DAEMON_PORT,
75    ENV_RUNTIME_DIR,
76    ENV_ZERO_COPY_THRESHOLD,
77    ENV_TYPE_CHECK,
78    ENV_XDG_RUNTIME_DIR,
79];
80
81/// How strictly a typed handle checks a port's declared URN (§9.2).
82///
83/// The default is [`TypeCheckMode::Warn`] in 0.1.0: a type system nobody can
84/// switch on is useless, and one that breaks every existing graph on upgrade
85/// is worse. `warn` makes drift visible without making it fatal; `error` is
86/// what a validated deployment sets.
87#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
88#[non_exhaustive]
89pub enum TypeCheckMode {
90    /// Do not check declared types at all.
91    Off,
92    /// Log a warning on a mismatch and continue (the 0.1.0 default).
93    #[default]
94    Warn,
95    /// Refuse the handle with [`NodeError::TypeMismatch`].
96    Error,
97}
98
99impl TypeCheckMode {
100    /// Every mode, in increasing strictness.
101    pub const ALL: &'static [Self] = &[Self::Off, Self::Warn, Self::Error];
102
103    /// The lower-case name used by `ASTRS_TYPE_CHECK` and by metrics labels.
104    #[must_use]
105    pub const fn as_str(self) -> &'static str {
106        match self {
107            Self::Off => "off",
108            Self::Warn => "warn",
109            Self::Error => "error",
110        }
111    }
112
113    /// Whether a mismatch aborts the call.
114    #[must_use]
115    pub const fn is_fatal(self) -> bool {
116        matches!(self, Self::Error)
117    }
118
119    /// Whether a mismatch is examined at all.
120    #[must_use]
121    pub const fn is_enabled(self) -> bool {
122        !matches!(self, Self::Off)
123    }
124
125    /// Reads the mode from `ASTRS_TYPE_CHECK`, defaulting to
126    /// [`TypeCheckMode::Warn`].
127    ///
128    /// # Errors
129    ///
130    /// [`NodeError::BadEnv`] when the variable names something else.
131    pub fn from_env() -> Result<Self> {
132        match std::env::var(ENV_TYPE_CHECK) {
133            Ok(value) => value.parse().map_err(|_| NodeError::BadEnv {
134                name: ENV_TYPE_CHECK,
135                value,
136                reason: "expected one of: off, warn, error".to_owned(),
137            }),
138            Err(_) => Ok(Self::default()),
139        }
140    }
141}
142
143impl FromStr for TypeCheckMode {
144    type Err = ();
145
146    fn from_str(text: &str) -> core::result::Result<Self, Self::Err> {
147        match text.trim().to_ascii_lowercase().as_str() {
148            "off" | "none" | "0" | "false" => Ok(Self::Off),
149            "warn" | "warning" => Ok(Self::Warn),
150            "error" | "strict" | "fatal" => Ok(Self::Error),
151            _ => Err(()),
152        }
153    }
154}
155
156impl core::fmt::Display for TypeCheckMode {
157    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
158        f.write_str(self.as_str())
159    }
160}
161
162/// Reads `ASTRS_RUN_PARENT_PID`, when it is set (§4.2).
163///
164/// # Errors
165///
166/// [`NodeError::BadEnv`] when it is set to something that is not a process id.
167///
168/// # Examples
169///
170/// ```
171/// // Unset in an ordinary test process, so no guard is requested.
172/// assert!(astrs_node_api::env::parent_pid().is_ok());
173/// ```
174pub fn parent_pid() -> Result<Option<u32>> {
175    parse_optional_env(ENV_RUN_PARENT_PID, "a process id")
176}
177
178/// Reads `ASTRS_DAEMON_PORT`, defaulting to [`DEFAULT_DAEMON_PORT`].
179///
180/// # Errors
181///
182/// [`NodeError::BadEnv`] when it is not a port number.
183pub fn daemon_port() -> Result<u16> {
184    Ok(parse_optional_env(ENV_DAEMON_PORT, "a TCP port")?.unwrap_or(DEFAULT_DAEMON_PORT))
185}
186
187/// Reads `ASTRS_ZERO_COPY_THRESHOLD`, defaulting to the §24.2 4 KiB.
188///
189/// # Errors
190///
191/// [`NodeError::BadEnv`] when it is not a byte count.
192pub fn zero_copy_threshold() -> Result<u64> {
193    Ok(parse_optional_env(ENV_ZERO_COPY_THRESHOLD, "a byte count")?
194        .unwrap_or(DEFAULT_ZERO_COPY_THRESHOLD))
195}
196
197/// The runtime directory for this process (§24.2).
198///
199/// `ASTRS_RUNTIME_DIR` wins; otherwise `$XDG_RUNTIME_DIR/astrs`; otherwise the
200/// system temporary directory with the same leaf, which is what makes a node
201/// runnable on a desktop macOS session where `XDG_RUNTIME_DIR` is unset.
202///
203/// # Examples
204///
205/// ```
206/// let dir = astrs_node_api::env::runtime_dir();
207/// assert!(dir.is_absolute() || dir.components().count() > 0);
208/// ```
209#[must_use]
210pub fn runtime_dir() -> PathBuf {
211    if let Ok(dir) = std::env::var(ENV_RUNTIME_DIR)
212        && !dir.is_empty()
213    {
214        return PathBuf::from(dir);
215    }
216    if let Ok(dir) = std::env::var(ENV_XDG_RUNTIME_DIR)
217        && !dir.is_empty()
218    {
219        return PathBuf::from(dir).join(RUNTIME_DIR_LEAF);
220    }
221    std::env::temp_dir().join(RUNTIME_DIR_LEAF)
222}
223
224/// The daemon's Unix-domain socket path under [`runtime_dir`].
225#[must_use]
226pub fn daemon_socket_path() -> PathBuf {
227    runtime_dir().join(DAEMON_SOCKET_NAME)
228}
229
230/// The shared-memory broker socket path under [`runtime_dir`].
231#[must_use]
232pub fn shm_broker_path() -> PathBuf {
233    runtime_dir().join(SHM_BROKER_SOCKET_NAME)
234}
235
236/// Parses an optional environment variable, treating an empty value as unset.
237///
238/// # Errors
239///
240/// [`NodeError::BadEnv`] when the value is present but unparseable.
241fn parse_optional_env<T: FromStr>(name: &'static str, expected: &str) -> Result<Option<T>> {
242    let Ok(value) = std::env::var(name) else {
243        return Ok(None);
244    };
245    let trimmed = value.trim();
246    if trimmed.is_empty() {
247        return Ok(None);
248    }
249    trimmed.parse().map(Some).map_err(|_| NodeError::BadEnv {
250        name,
251        value: value.clone(),
252        reason: format!("expected {expected}"),
253    })
254}
255
256#[cfg(test)]
257mod tests {
258    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
259
260    use super::*;
261
262    #[test]
263    fn type_check_modes_parse_every_spelling() {
264        assert_eq!("off".parse(), Ok(TypeCheckMode::Off));
265        assert_eq!("NONE".parse(), Ok(TypeCheckMode::Off));
266        assert_eq!("0".parse(), Ok(TypeCheckMode::Off));
267        assert_eq!("false".parse(), Ok(TypeCheckMode::Off));
268        assert_eq!("  warn  ".parse(), Ok(TypeCheckMode::Warn));
269        assert_eq!("Warning".parse(), Ok(TypeCheckMode::Warn));
270        assert_eq!("ERROR".parse(), Ok(TypeCheckMode::Error));
271        assert_eq!("strict".parse(), Ok(TypeCheckMode::Error));
272        assert_eq!("fatal".parse(), Ok(TypeCheckMode::Error));
273        assert_eq!("loud".parse::<TypeCheckMode>(), Err(()));
274    }
275
276    #[test]
277    fn type_check_modes_classify_themselves() {
278        assert!(!TypeCheckMode::Off.is_enabled());
279        assert!(!TypeCheckMode::Off.is_fatal());
280        assert!(TypeCheckMode::Warn.is_enabled());
281        assert!(!TypeCheckMode::Warn.is_fatal());
282        assert!(TypeCheckMode::Error.is_enabled());
283        assert!(TypeCheckMode::Error.is_fatal());
284        assert_eq!(TypeCheckMode::default(), TypeCheckMode::Warn);
285        for mode in TypeCheckMode::ALL {
286            assert_eq!(mode.to_string(), mode.as_str());
287            assert_eq!(mode.as_str().parse(), Ok(*mode));
288        }
289        assert_eq!(TypeCheckMode::ALL.len(), 3);
290    }
291
292    #[test]
293    fn the_variable_table_is_complete_and_unique() {
294        let mut names = READ_VARIABLES.to_vec();
295        let total = names.len();
296        names.sort_unstable();
297        names.dedup();
298        assert_eq!(names.len(), total);
299        for name in READ_VARIABLES {
300            assert!(
301                name.starts_with("ASTRS_") || name.starts_with("XDG_"),
302                "{name}"
303            );
304        }
305    }
306
307    #[test]
308    fn the_runtime_directory_always_resolves() {
309        // The process environment is shared with parallel tests, so this
310        // asserts only the property that holds for every possible setting.
311        let dir = runtime_dir();
312        assert!(!dir.as_os_str().is_empty());
313        assert!(daemon_socket_path().starts_with(&dir));
314        assert!(shm_broker_path().starts_with(&dir));
315        assert!(
316            daemon_socket_path()
317                .file_name()
318                .is_some_and(|name| name == DAEMON_SOCKET_NAME)
319        );
320        assert!(
321            shm_broker_path()
322                .file_name()
323                .is_some_and(|name| name == SHM_BROKER_SOCKET_NAME)
324        );
325    }
326
327    #[test]
328    fn optional_variables_default_when_unset_or_blank() {
329        // `parse_optional_env` is exercised directly rather than through the
330        // process environment, which parallel tests share.
331        assert_eq!(
332            parse_optional_env::<u16>("ASTRS_SURELY_UNSET_VARIABLE", "a port").unwrap(),
333            None
334        );
335    }
336
337    #[test]
338    fn the_documented_defaults_match_the_appendix() {
339        assert_eq!(DEFAULT_DAEMON_PORT, 7408);
340        assert_eq!(DEFAULT_ZERO_COPY_THRESHOLD, 4096);
341        assert_eq!(RUNTIME_DIR_LEAF, "astrs");
342        assert_eq!(ENV_TYPE_CHECK, "ASTRS_TYPE_CHECK");
343        assert_eq!(ENV_ZERO_COPY_THRESHOLD, "ASTRS_ZERO_COPY_THRESHOLD");
344        assert_eq!(ENV_DAEMON_PORT, "ASTRS_DAEMON_PORT");
345        assert_eq!(ENV_RUNTIME_DIR, "ASTRS_RUNTIME_DIR");
346    }
347
348    #[test]
349    fn readers_report_a_default_when_the_variable_is_absent() {
350        // These read the real environment; in a test process none of the
351        // AstRS variables are set, so every reader must produce its default
352        // rather than an error.
353        if std::env::var(ENV_DAEMON_PORT).is_err() {
354            assert_eq!(daemon_port().unwrap(), DEFAULT_DAEMON_PORT);
355        }
356        if std::env::var(ENV_ZERO_COPY_THRESHOLD).is_err() {
357            assert_eq!(zero_copy_threshold().unwrap(), DEFAULT_ZERO_COPY_THRESHOLD);
358        }
359        if std::env::var(ENV_RUN_PARENT_PID).is_err() {
360            assert_eq!(parent_pid().unwrap(), None);
361        }
362        if std::env::var(ENV_TYPE_CHECK).is_err() {
363            assert_eq!(TypeCheckMode::from_env().unwrap(), TypeCheckMode::Warn);
364        }
365    }
366}