zero_headless/paths.rs
1//! Filesystem path helpers for the daemon and its clients.
2//!
3//! Both the daemon and the CLI-side dialer need to agree on
4//! *where* the socket and state file live; isolating the logic
5//! here means a future move (e.g. `/var/run/zero/<operator>.sock`
6//! on Linux) is a single-file change instead of a grep-and-replace.
7//!
8//! The defaults land under [`zero_config::runtime_paths`]. We
9//! intentionally *do not* put the socket under `XDG_RUNTIME_DIR`
10//! on Linux, because that directory is lost across login sessions
11//! and the daemon's whole purpose is surviving the operator's
12//! terminal.
13
14use std::path::{Path, PathBuf};
15
16/// Socket file name under the operator directory.
17pub const SOCKET_FILE_NAME: &str = "sock";
18
19/// State-file path relative to the operator directory.
20/// `state/headless.json` keeps daemon persistence under the same
21/// operator partition as session state and wraps.
22pub const STATE_SUBDIR: &str = "state";
23pub const STATE_FILE_NAME: &str = "headless.json";
24
25/// Default Unix socket path:
26/// `<zero_dir>/operators/<operator-slug>/sock`. Falls back to
27/// `<tmpdir>/zero-sock` when config paths are unavailable.
28#[must_use]
29pub fn default_socket_path() -> PathBuf {
30 zero_config::runtime_paths().map_or_else(
31 |_| std::env::temp_dir().join("zero-sock"),
32 |paths| paths.headless_socket_path,
33 )
34}
35
36/// Default state-file path:
37/// `<zero_dir>/operators/<operator-slug>/state/headless.json`.
38#[must_use]
39pub fn default_state_path() -> PathBuf {
40 zero_config::runtime_paths().map_or_else(
41 |_| std::env::temp_dir().join("zero-headless.json"),
42 |paths| paths.headless_state_path,
43 )
44}
45
46/// Socket path rooted at an arbitrary base — used by tests to
47/// point both the daemon and its dialer at a temp dir.
48#[must_use]
49pub fn socket_in(base: &Path) -> PathBuf {
50 base.join(SOCKET_FILE_NAME)
51}
52
53/// State-file path rooted at an arbitrary base. Mirrors the
54/// production layout so tests exercise the same
55/// `state/headless.json` resolution as prod.
56#[must_use]
57pub fn state_in(base: &Path) -> PathBuf {
58 base.join(STATE_SUBDIR).join(STATE_FILE_NAME)
59}
60
61#[cfg(test)]
62mod tests {
63 use super::*;
64
65 #[test]
66 fn socket_and_state_share_base() {
67 let base = std::path::Path::new("/tmp/zero-test");
68 assert_eq!(socket_in(base), PathBuf::from("/tmp/zero-test/sock"));
69 assert_eq!(
70 state_in(base),
71 PathBuf::from("/tmp/zero-test/state/headless.json"),
72 );
73 }
74
75 #[test]
76 fn defaults_are_absolute_or_fallback() {
77 // Either the HOME-rooted default resolved or the tmpdir
78 // fallback fired — both yield absolute paths. An empty
79 // / relative result would be a regression.
80 let s = default_socket_path();
81 assert!(s.is_absolute(), "socket path not absolute: {s:?}");
82 let p = default_state_path();
83 assert!(p.is_absolute(), "state path not absolute: {p:?}");
84 }
85}