Skip to main content

stackless_core/
cli_binary.rs

1//! Resolve the stackless CLI binary used to spawn the operator daemon.
2//!
3//! Third-party SDK consumers must not be spawned as the daemon: only the
4//! installed CLI understands `daemon run`. Resolution is pure-testable via
5//! [`resolve_cli_from`] because edition 2024 + `unsafe_code = "forbid"`
6//! blocks in-process `set_var`.
7
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, Ordering};
10
11#[derive(Debug, thiserror::Error)]
12pub enum ResolveError {
13    #[error("cannot resolve stackless executable: {detail}")]
14    Spawn { detail: String },
15    #[error("stackless CLI binary not found: {detail}")]
16    BinaryNotFound { detail: String },
17}
18
19static CLI_PROCESS: AtomicBool = AtomicBool::new(false);
20
21/// Mark this process as the stackless CLI entrypoint (`stackless::cli::run`).
22///
23/// Spawning the operator daemon (and registering launchd / running the reaper)
24/// is only valid from a process that has called this.
25pub fn mark_cli_process() {
26    CLI_PROCESS.store(true, Ordering::SeqCst);
27}
28
29/// Whether [`mark_cli_process`] has been called in this process.
30pub fn is_cli_process() -> bool {
31    CLI_PROCESS.load(Ordering::SeqCst)
32}
33
34/// How the daemon executable was resolved.
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum ResolveSource {
37    /// Absolute path from `STACKLESS_BIN`.
38    EnvOverride,
39    /// This process is the CLI (`mark_cli_process`) — use `current_exe`.
40    SelfAsCli,
41    /// `stackless` found on `PATH`.
42    Path,
43    /// Found under a well-known install directory.
44    WellKnown,
45    /// Caller injected an explicit path (`ensure_with`).
46    Explicit,
47}
48
49/// Whether a version mismatch should drain and respawn the daemon.
50///
51/// Only the CLI upgrading itself replaces a running daemon. SDK consumers
52/// that resolved a CLI via PATH/env must never kill a healthy daemon and
53/// must never respawn in a version-mismatch thrash loop.
54pub fn should_replace_daemon(
55    daemon_version: &str,
56    own_version: &str,
57    source: ResolveSource,
58) -> bool {
59    source == ResolveSource::SelfAsCli && daemon_version != own_version
60}
61
62const STACKLESS_BIN_ENV: &str = "STACKLESS_BIN";
63
64/// Resolve the CLI binary from the real process environment.
65pub fn resolve_cli() -> Result<(PathBuf, ResolveSource), ResolveError> {
66    let override_bin = std::env::var_os(STACKLESS_BIN_ENV).map(PathBuf::from);
67    let self_exe = std::env::current_exe().map_err(|err| ResolveError::Spawn {
68        detail: format!("cannot resolve current executable: {err}"),
69    })?;
70    let path_dirs: Vec<PathBuf> = std::env::var_os("PATH")
71        .map(|p| std::env::split_paths(&p).collect())
72        .unwrap_or_default();
73    let home = std::env::var_os("HOME").map(PathBuf::from);
74    resolve_cli_from(
75        override_bin.as_deref(),
76        &self_exe,
77        is_cli_process(),
78        &path_dirs,
79        home.as_deref(),
80    )
81}
82
83/// Pure resolver for tests and [`resolve_cli`].
84pub fn resolve_cli_from(
85    override_bin: Option<&Path>,
86    self_exe: &Path,
87    is_cli: bool,
88    path_dirs: &[PathBuf],
89    home: Option<&Path>,
90) -> Result<(PathBuf, ResolveSource), ResolveError> {
91    if let Some(path) = override_bin {
92        if is_executable(path) {
93            return Ok((path.to_path_buf(), ResolveSource::EnvOverride));
94        }
95        return Err(ResolveError::BinaryNotFound {
96            detail: format!(
97                "{STACKLESS_BIN_ENV}={path} is set but is not an executable file",
98                path = path.display()
99            ),
100        });
101    }
102
103    if is_cli && is_executable(self_exe) {
104        return Ok((self_exe.to_path_buf(), ResolveSource::SelfAsCli));
105    }
106
107    for dir in path_dirs {
108        let candidate = dir.join("stackless");
109        if is_executable(&candidate) {
110            return Ok((candidate, ResolveSource::Path));
111        }
112    }
113
114    for dir in well_known_dirs(home) {
115        let candidate = dir.join("stackless");
116        if is_executable(&candidate) {
117            return Ok((candidate, ResolveSource::WellKnown));
118        }
119    }
120
121    Err(ResolveError::BinaryNotFound {
122        detail: format!(
123            "Client::system() needs the stackless CLI to run the operator daemon. \
124             Install it (https://github.com/snowmead/stackless#install), ensure \
125             `stackless` is on PATH, or set {STACKLESS_BIN_ENV}. \
126             For hermetic tests use Client::builder().paths(...) / TestContext \
127             (feature test-support)."
128        ),
129    })
130}
131
132fn well_known_dirs(home: Option<&Path>) -> Vec<PathBuf> {
133    let mut dirs = Vec::new();
134    if let Some(home) = home {
135        dirs.push(home.join(".cargo").join("bin"));
136    }
137    dirs.push(PathBuf::from("/usr/local/bin"));
138    dirs.push(PathBuf::from("/opt/homebrew/bin"));
139    dirs
140}
141
142fn is_executable(path: &Path) -> bool {
143    use std::os::unix::fs::PermissionsExt;
144    let Ok(meta) = std::fs::metadata(path) else {
145        return false;
146    };
147    meta.is_file() && meta.permissions().mode() & 0o111 != 0
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153    use std::os::unix::fs::PermissionsExt;
154
155    fn touch_exe(dir: &Path, name: &str) -> PathBuf {
156        let path = dir.join(name);
157        std::fs::write(&path, b"#!/bin/sh\n").unwrap();
158        let mut perms = std::fs::metadata(&path).unwrap().permissions();
159        perms.set_mode(0o755);
160        std::fs::set_permissions(&path, perms).unwrap();
161        path
162    }
163
164    #[test]
165    fn override_wins_when_executable() {
166        let dir = tempfile::tempdir().unwrap();
167        let bin = touch_exe(dir.path(), "custom-stackless");
168        let (resolved, source) =
169            resolve_cli_from(Some(&bin), &dir.path().join("consumer"), false, &[], None).unwrap();
170        assert_eq!(resolved, bin);
171        assert_eq!(source, ResolveSource::EnvOverride);
172    }
173
174    #[test]
175    fn bad_override_is_hard_error() {
176        let dir = tempfile::tempdir().unwrap();
177        let missing = dir.path().join("missing");
178        let err =
179            resolve_cli_from(Some(&missing), &dir.path().join("x"), false, &[], None).unwrap_err();
180        assert!(matches!(err, ResolveError::BinaryNotFound { .. }));
181        assert!(err.to_string().contains(STACKLESS_BIN_ENV));
182    }
183
184    #[test]
185    fn cli_marker_uses_self() {
186        let dir = tempfile::tempdir().unwrap();
187        let self_exe = touch_exe(dir.path(), "stackless");
188        let (resolved, source) = resolve_cli_from(None, &self_exe, true, &[], None).unwrap();
189        assert_eq!(resolved, self_exe);
190        assert_eq!(source, ResolveSource::SelfAsCli);
191    }
192
193    #[test]
194    fn unmarked_self_never_returned_even_if_named_stackless() {
195        let dir = tempfile::tempdir().unwrap();
196        let self_exe = touch_exe(dir.path(), "stackless");
197        let path_dir = tempfile::tempdir().unwrap();
198        let on_path = touch_exe(path_dir.path(), "stackless");
199        let (resolved, source) = resolve_cli_from(
200            None,
201            &self_exe,
202            false,
203            &[path_dir.path().to_path_buf()],
204            None,
205        )
206        .unwrap();
207        assert_eq!(resolved, on_path);
208        assert_eq!(source, ResolveSource::Path);
209        assert_ne!(resolved, self_exe);
210    }
211
212    #[test]
213    fn unmarked_with_nothing_errors() {
214        let dir = tempfile::tempdir().unwrap();
215        let self_exe = touch_exe(dir.path(), "jinttai-e2e");
216        let err = resolve_cli_from(None, &self_exe, false, &[], None).unwrap_err();
217        assert!(matches!(err, ResolveError::BinaryNotFound { .. }));
218        assert!(!err.to_string().contains("jinttai-e2e daemon run"));
219    }
220
221    #[test]
222    fn well_known_cargo_bin() {
223        let home = tempfile::tempdir().unwrap();
224        let cargo_bin = home.path().join(".cargo").join("bin");
225        std::fs::create_dir_all(&cargo_bin).unwrap();
226        let bin = touch_exe(&cargo_bin, "stackless");
227        let self_exe = home.path().join("consumer");
228        let (resolved, source) =
229            resolve_cli_from(None, &self_exe, false, &[], Some(home.path())).unwrap();
230        assert_eq!(resolved, bin);
231        assert_eq!(source, ResolveSource::WellKnown);
232    }
233
234    #[test]
235    fn should_replace_only_self_as_cli() {
236        assert!(should_replace_daemon(
237            "0.1.4",
238            "0.1.5",
239            ResolveSource::SelfAsCli
240        ));
241        assert!(!should_replace_daemon(
242            "0.1.4",
243            "0.1.5",
244            ResolveSource::Path
245        ));
246        assert!(!should_replace_daemon(
247            "0.1.4",
248            "0.1.5",
249            ResolveSource::EnvOverride
250        ));
251        assert!(!should_replace_daemon(
252            "0.1.4",
253            "0.1.5",
254            ResolveSource::WellKnown
255        ));
256        assert!(!should_replace_daemon(
257            "0.1.4",
258            "0.1.5",
259            ResolveSource::Explicit
260        ));
261        assert!(!should_replace_daemon(
262            "0.1.5",
263            "0.1.5",
264            ResolveSource::SelfAsCli
265        ));
266    }
267}