Skip to main content

pitchfork_cli/
daemon.rs

1use crate::config_types::OneshotWait;
2use crate::daemon_id::DaemonId;
3use crate::daemon_status::DaemonStatus;
4use crate::pitchfork_toml::{
5    CpuLimit, CronRetrigger, Dir, HealthCmd, HealthHttp, HealthPort, MemoryLimit, PortConfig,
6    ReadyCmd, ReadyHttp, ReadyOutput, ReadyPort, Retry, StopConfig, WatchMode,
7};
8use indexmap::IndexMap;
9use std::fmt::Display;
10use std::path::PathBuf;
11
12/// Validates a daemon ID to ensure it's safe for use in file paths and IPC.
13///
14/// A valid daemon ID:
15/// - Is not empty
16/// - Does not contain backslashes (`\`)
17/// - Does not contain parent directory references (`..`)
18/// - Does not contain spaces
19/// - Does not contain `--` (reserved for path encoding of `/`)
20/// - Is not `.` (current directory)
21/// - Contains only printable ASCII characters
22/// - If qualified (contains `/`), has exactly one `/` separating namespace and short ID
23///
24/// Format: `[namespace/]short_id`
25/// - Qualified: `project/api`, `global/web`
26/// - Short: `api`, `web`
27///
28/// This validation prevents path traversal attacks when daemon IDs are used
29/// to construct log file paths or other filesystem operations.
30pub fn is_valid_daemon_id(id: &str) -> bool {
31    if id.contains('/') {
32        DaemonId::parse(id).is_ok()
33    } else {
34        DaemonId::try_new("global", id).is_ok()
35    }
36}
37
38#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
39pub struct Daemon {
40    pub id: DaemonId,
41    pub title: Option<String>,
42    pub pid: Option<u32>,
43    /// High-resolution kernel start token recorded at spawn. Together with
44    /// `pid` this identifies the process across a supervisor crash: a recycled
45    /// PID has a different token, so orphan cleanup can tell a genuine orphan
46    /// from an unrelated process.
47    #[serde(skip_serializing_if = "Option::is_none", default)]
48    pub start_time: Option<u64>,
49    /// System boot time (seconds since epoch) recorded at spawn. Lets orphan
50    /// reconciliation tell a daemon that died under a crashed supervisor
51    /// during this boot from one whose process died with the machine, which
52    /// need different terminal states. Unlike `start_time` this is a
53    /// wall-clock value comparable across processes and platforms.
54    #[serde(skip_serializing_if = "Option::is_none", default)]
55    pub boot_time: Option<u64>,
56    pub shell_pid: Option<u32>,
57    pub status: DaemonStatus,
58    pub dir: Option<PathBuf>,
59    #[serde(skip_serializing_if = "Option::is_none", default)]
60    pub cmd: Option<Vec<String>>,
61    /// Original shell command string, persisted for retry/watch restarts.
62    #[serde(skip_serializing_if = "Option::is_none", default)]
63    pub run: Option<String>,
64    pub autostop: bool,
65    #[serde(skip_serializing_if = "Option::is_none", default)]
66    pub cron_schedule: Option<String>,
67    #[serde(skip_serializing_if = "Option::is_none", default)]
68    pub cron_retrigger: Option<CronRetrigger>,
69    #[serde(skip_serializing_if = "Option::is_none", default)]
70    pub cron_immediate: Option<bool>,
71    #[serde(skip_serializing_if = "Option::is_none", default)]
72    pub last_cron_triggered: Option<chrono::DateTime<chrono::Local>>,
73    #[serde(skip_serializing_if = "Option::is_none", default)]
74    pub last_exit_success: Option<bool>,
75    #[serde(default)]
76    pub retry: Retry,
77    #[serde(default)]
78    pub retry_count: u32,
79    #[serde(skip_serializing_if = "Option::is_none", default)]
80    pub ready_delay: Option<u64>,
81    #[serde(skip_serializing_if = "Option::is_none", default)]
82    pub ready_output: Option<ReadyOutput>,
83    #[serde(skip_serializing_if = "Option::is_none", default)]
84    pub ready_http: Option<ReadyHttp>,
85    #[serde(skip_serializing_if = "Option::is_none", default)]
86    pub ready_port: Option<ReadyPort>,
87    #[serde(skip_serializing_if = "Option::is_none", default)]
88    pub ready_cmd: Option<ReadyCmd>,
89    #[serde(skip_serializing_if = "Option::is_none", default)]
90    pub health_cmd: Option<HealthCmd>,
91    #[serde(skip_serializing_if = "Option::is_none", default)]
92    pub health_http: Option<HealthHttp>,
93    #[serde(skip_serializing_if = "Option::is_none", default)]
94    pub health_port: Option<HealthPort>,
95    /// Port configuration (expected ports and auto-bump settings)
96    #[serde(skip_serializing_if = "Option::is_none", default)]
97    pub port: Option<PortConfig>,
98    /// Resolved ports actually used after auto-bump (may differ from expected)
99    #[serde(skip_serializing_if = "Vec::is_empty", default)]
100    pub resolved_port: Vec<u16>,
101    /// The first port the process is actually listening on (detected at runtime via listeners crate).
102    /// This is the source of truth for the reverse proxy. Cleared when the daemon stops.
103    #[serde(skip_serializing_if = "Option::is_none", default)]
104    pub active_port: Option<u16>,
105    /// Optional stable slug alias for this daemon (used in proxy URLs and CLI commands).
106    #[serde(skip_serializing_if = "Option::is_none", default)]
107    pub slug: Option<String>,
108    /// Whether to proxy this daemon (None = inherit global proxy.enable setting).
109    #[serde(skip_serializing_if = "Option::is_none", default)]
110    pub proxy: Option<bool>,
111    #[serde(skip_serializing_if = "Vec::is_empty", default)]
112    pub depends: Vec<DaemonId>,
113    #[serde(skip_serializing_if = "Option::is_none", default)]
114    pub env: Option<IndexMap<String, String>>,
115    #[serde(skip_serializing_if = "Vec::is_empty", default)]
116    pub watch: Vec<String>,
117    #[serde(default)]
118    pub watch_mode: WatchMode,
119    #[serde(skip_serializing_if = "Option::is_none", default)]
120    pub watch_base_dir: Option<PathBuf>,
121    /// Whether to use mise for this daemon (None = inherit global general.mise setting).
122    ///
123    /// # Schema compatibility note
124    /// This field changed from `bool` to `Option<bool>` with `skip_serializing_if = "Option::is_none"`.
125    /// - **Upgrade (old → new):** safe — old files contain `mise = true/false`, which deserialize
126    ///   correctly as `Some(true)` / `Some(false)`.
127    /// - **Downgrade (new → old):** if `mise` is `None` (inherit global), the key is omitted from
128    ///   the state file. An old binary reads the missing key as `false`, ignoring `general.mise = true`.
129    ///   Any daemon that relied on the global setting would silently stop using mise after a downgrade.
130    #[serde(skip_serializing_if = "Option::is_none", default)]
131    pub mise: Option<bool>,
132    /// Unix user to run this daemon as.
133    #[serde(skip_serializing_if = "Option::is_none", default)]
134    pub user: Option<String>,
135    /// Memory limit for the daemon process (e.g. "50MB", "1GiB")
136    #[serde(skip_serializing_if = "Option::is_none", default)]
137    pub memory_limit: Option<MemoryLimit>,
138    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores)
139    #[serde(skip_serializing_if = "Option::is_none", default)]
140    pub cpu_limit: Option<CpuLimit>,
141    /// Unix signal to send for graceful shutdown (default: SIGTERM)
142    #[serde(skip_serializing_if = "Option::is_none", default)]
143    pub stop_signal: Option<StopConfig>,
144    /// Archive hook command invoked before retention prunes this daemon's logs.
145    #[serde(skip_serializing_if = "Option::is_none", default)]
146    pub archive_hook: Option<String>,
147    /// Log format for this daemon.
148    #[serde(skip_serializing_if = "Option::is_none", default)]
149    pub log_format: Option<String>,
150    /// Allocate a pseudo-terminal for the daemon process.
151    #[serde(skip_serializing_if = "Option::is_none", default)]
152    pub pty: Option<bool>,
153    /// True for daemons auto-registered from config by the cron watcher,
154    /// not yet started. Treated as "available" by list/status/stats.
155    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
156    pub config_registered: bool,
157    /// Run-to-completion task rather than a long-running service. Readiness is
158    /// a zero exit code, and the terminal state is `completed` instead of
159    /// `stopped`. See `DaemonStatus::Completed`.
160    ///
161    /// Appended rather than grouped with `status`: IPC encodes this struct
162    /// positionally, so a field inserted in the middle shifts every field
163    /// after it for a peer that does not have it.
164    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
165    pub oneshot: bool,
166    /// Set when the proxy started this run and it may be stopped for
167    /// inactivity: how long, in milliseconds, it may go without proxy
168    /// activity. `None` for a daemon started any other way, or claimed since
169    /// by an explicit start.
170    ///
171    /// Appended last for the positional IPC encoding, like `oneshot`.
172    #[serde(default)]
173    pub proxy_idle_timeout_ms: Option<u64>,
174}
175
176#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Default)]
177pub struct RunOptions {
178    pub id: DaemonId,
179    pub cmd: Vec<String>,
180    /// Original shell command string (from config `run`), passed verbatim to the shell.
181    /// Falls back to joining `cmd` when None (e.g. ad-hoc `pitchfork run -- cmd args`).
182    #[serde(skip_serializing_if = "Option::is_none", default)]
183    pub run: Option<String>,
184    pub force: bool,
185    pub shell_pid: Option<u32>,
186    pub dir: Dir,
187    pub autostop: bool,
188    pub cron_schedule: Option<String>,
189    pub cron_retrigger: Option<CronRetrigger>,
190    pub cron_immediate: Option<bool>,
191    pub retry: Retry,
192    pub retry_count: u32,
193    pub ready_delay: Option<u64>,
194    pub ready_output: Option<ReadyOutput>,
195    pub ready_http: Option<ReadyHttp>,
196    pub ready_port: Option<ReadyPort>,
197    pub ready_cmd: Option<ReadyCmd>,
198    pub health_cmd: Option<HealthCmd>,
199    pub health_http: Option<HealthHttp>,
200    pub health_port: Option<HealthPort>,
201    pub port: Option<PortConfig>,
202    pub wait_ready: bool,
203    #[serde(skip_serializing_if = "Vec::is_empty", default)]
204    pub depends: Vec<DaemonId>,
205    #[serde(skip_serializing_if = "Option::is_none", default)]
206    pub env: Option<IndexMap<String, String>>,
207    #[serde(skip_serializing_if = "Vec::is_empty", default)]
208    pub watch: Vec<String>,
209    #[serde(default)]
210    pub watch_mode: WatchMode,
211    #[serde(skip_serializing_if = "Option::is_none", default)]
212    pub watch_base_dir: Option<PathBuf>,
213    /// Whether to use mise for this daemon (None = inherit global general.mise setting).
214    ///
215    /// # Schema compatibility note
216    /// See `Daemon::mise` for downgrade implications when this field is `None`.
217    #[serde(skip_serializing_if = "Option::is_none", default)]
218    pub mise: Option<bool>,
219    /// Optional stable slug alias for this daemon.
220    #[serde(skip_serializing_if = "Option::is_none", default)]
221    pub slug: Option<String>,
222    /// Whether to proxy this daemon (None = inherit global proxy.enable setting).
223    #[serde(skip_serializing_if = "Option::is_none", default)]
224    pub proxy: Option<bool>,
225    /// Unix user to run this daemon as.
226    #[serde(skip_serializing_if = "Option::is_none", default)]
227    pub user: Option<String>,
228    /// Memory limit for the daemon process (e.g. "50MB", "1GiB")
229    #[serde(skip_serializing_if = "Option::is_none", default)]
230    pub memory_limit: Option<MemoryLimit>,
231    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores)
232    #[serde(skip_serializing_if = "Option::is_none", default)]
233    pub cpu_limit: Option<CpuLimit>,
234    /// Unix signal to send for graceful shutdown (default: SIGTERM)
235    #[serde(skip_serializing_if = "Option::is_none", default)]
236    pub stop_signal: Option<StopConfig>,
237    /// Archive hook command invoked before retention prunes this daemon's logs.
238    #[serde(skip_serializing_if = "Option::is_none", default)]
239    pub archive_hook: Option<String>,
240    /// Log format for this daemon: `json`, `logfmt`, `auto`, or `text`.
241    #[serde(skip_serializing_if = "Option::is_none", default)]
242    pub log_format: Option<String>,
243    /// Hook triggered when the daemon produces matching output
244    #[serde(skip_serializing_if = "Option::is_none", default)]
245    pub on_output_hook: Option<crate::pitchfork_toml::OnOutputHook>,
246    /// Allocate a pseudo-terminal for the daemon process.
247    #[serde(skip_serializing_if = "Option::is_none", default)]
248    pub pty: Option<bool>,
249    /// Run-to-completion task rather than a long-running service.
250    ///
251    /// Appended rather than grouped with `autostop`: IPC encodes this struct
252    /// positionally, so a field inserted in the middle shifts every field
253    /// after it for a CLI or supervisor that does not have it, and a version
254    /// mismatch is only warned about, not refused.
255    #[serde(default)]
256    pub oneshot: bool,
257    /// How long to wait for a oneshot to finish, already resolved from the
258    /// project's `supervisor.oneshot_timeout`.
259    ///
260    /// Resolved by the client and carried on the request because the
261    /// supervisor is long-lived and may have started in another directory, so
262    /// its own `settings()` would not see the project's value. `None` leaves
263    /// the supervisor to fall back to whatever it can resolve.
264    #[serde(skip_serializing_if = "Option::is_none", default)]
265    pub oneshot_wait: Option<OneshotWait>,
266    /// This start came from entering a directory rather than from a person
267    /// asking for it, so a completed `oneshot` is left alone. Decided by the
268    /// supervisor because only it holds authoritative state: the state file
269    /// lags it by up to the flush interval, which is exactly the window a
270    /// second directory entry lands in.
271    #[serde(default)]
272    pub on_directory_enter: bool,
273    /// The proxy is starting this daemon, and it may be stopped after this
274    /// many milliseconds without proxy activity. `None` for every other start,
275    /// which is what makes such a start explicit. Carried over by restarts
276    /// (retry, file watch), which continue the same ownership.
277    ///
278    /// Appended last for the positional IPC encoding.
279    #[serde(default)]
280    pub proxy_idle_timeout_ms: Option<u64>,
281}
282
283impl Daemon {
284    /// Build RunOptions from persisted daemon state.
285    ///
286    /// Carries over all configuration fields from the daemon state.
287    /// Callers can override specific fields on the returned value.
288    pub fn to_run_options(&self, cmd: Vec<String>) -> RunOptions {
289        // Re-read on_output_hook from fresh config so restarts (retry, watch,
290        // cron) always pick up the current hook configuration.
291        // Use daemon.dir if available to handle daemons started via slugs
292        // whose project directory is not in the supervisor's cwd ancestry.
293        let on_output_hook = self
294            .dir
295            .as_deref()
296            .and_then(|dir| crate::pitchfork_toml::PitchforkToml::all_merged_from(dir).ok())
297            .or_else(|| crate::pitchfork_toml::PitchforkToml::all_merged_all_namespaces().ok())
298            .and_then(|pt| {
299                pt.daemons
300                    .get(&self.id)
301                    .and_then(|d| d.hooks.as_ref())
302                    .and_then(|h| h.on_output.clone())
303            });
304
305        RunOptions {
306            id: self.id.clone(),
307            cmd,
308            run: self.run.clone(),
309            force: false,
310            shell_pid: self.shell_pid,
311            dir: Dir(self.dir.clone().unwrap_or_else(|| crate::env::CWD.clone())),
312            autostop: self.autostop,
313            oneshot: self.oneshot,
314            // Re-resolved by the client on the paths that have a project to
315            // resolve it from; a supervisor-internal restart keeps None and
316            // falls back.
317            oneshot_wait: None,
318            on_directory_enter: false,
319            // A restart continues whatever ownership the run it replaces had.
320            proxy_idle_timeout_ms: self.proxy_idle_timeout_ms,
321            cron_schedule: self.cron_schedule.clone(),
322            cron_retrigger: self.cron_retrigger,
323            cron_immediate: self.cron_immediate,
324            retry: self.retry,
325            retry_count: self.retry_count,
326            ready_delay: self.ready_delay,
327            ready_output: self.ready_output.clone(),
328            ready_http: self.ready_http.clone(),
329            ready_port: self.ready_port.clone(),
330            ready_cmd: self.ready_cmd.clone(),
331            health_cmd: self.health_cmd.clone(),
332            health_http: self.health_http.clone(),
333            health_port: self.health_port.clone(),
334            port: self.port.clone(),
335            wait_ready: false,
336            depends: self.depends.clone(),
337            env: self.env.clone(),
338            watch: self.watch.clone(),
339            watch_mode: self.watch_mode,
340            watch_base_dir: self.watch_base_dir.clone(),
341            mise: self.mise,
342            slug: self.slug.clone(),
343            proxy: self.proxy,
344            user: self.user.clone(),
345            memory_limit: self.memory_limit,
346            cpu_limit: self.cpu_limit,
347            stop_signal: self.stop_signal,
348            archive_hook: self.archive_hook.clone(),
349            log_format: self.log_format.clone(),
350            on_output_hook,
351            pty: self.pty,
352        }
353    }
354}
355
356impl Display for Daemon {
357    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358        write!(f, "{}", self.id.qualified())
359    }
360}
361
362#[cfg(test)]
363mod tests {
364    use super::*;
365
366    #[test]
367    fn test_valid_daemon_ids() {
368        // Short IDs
369        assert!(is_valid_daemon_id("myapp"));
370        assert!(is_valid_daemon_id("my-app"));
371        assert!(is_valid_daemon_id("my_app"));
372        assert!(is_valid_daemon_id("my.app"));
373        assert!(is_valid_daemon_id("MyApp123"));
374
375        // Qualified IDs (namespace/short_id)
376        assert!(is_valid_daemon_id("project/api"));
377        assert!(is_valid_daemon_id("global/web"));
378        assert!(is_valid_daemon_id("my-project/my-app"));
379    }
380
381    #[test]
382    fn test_invalid_daemon_ids() {
383        // Empty
384        assert!(!is_valid_daemon_id(""));
385
386        // Multiple slashes (invalid qualified format)
387        assert!(!is_valid_daemon_id("a/b/c"));
388        assert!(!is_valid_daemon_id("../etc/passwd"));
389
390        // Invalid qualified format (empty parts)
391        assert!(!is_valid_daemon_id("/api"));
392        assert!(!is_valid_daemon_id("project/"));
393
394        // Backslashes
395        assert!(!is_valid_daemon_id("foo\\bar"));
396
397        // Parent directory reference
398        assert!(!is_valid_daemon_id(".."));
399        assert!(!is_valid_daemon_id("foo..bar"));
400
401        // Double dash (reserved for path encoding)
402        assert!(!is_valid_daemon_id("my--app"));
403        assert!(!is_valid_daemon_id("project--api"));
404        assert!(!is_valid_daemon_id("--app"));
405        assert!(!is_valid_daemon_id("app--"));
406
407        // Spaces
408        assert!(!is_valid_daemon_id("my app"));
409        assert!(!is_valid_daemon_id(" myapp"));
410        assert!(!is_valid_daemon_id("myapp "));
411
412        // Current directory
413        assert!(!is_valid_daemon_id("."));
414
415        // Control characters
416        assert!(!is_valid_daemon_id("my\x00app"));
417        assert!(!is_valid_daemon_id("my\napp"));
418        assert!(!is_valid_daemon_id("my\tapp"));
419
420        // Non-ASCII
421        assert!(!is_valid_daemon_id("myäpp"));
422        assert!(!is_valid_daemon_id("приложение"));
423
424        // Unsupported punctuation under DaemonId rules
425        assert!(!is_valid_daemon_id("app@host"));
426        assert!(!is_valid_daemon_id("app:8080"));
427    }
428}