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    /// Template context handed to `mise x` for a `run` command left unrendered, kept
133    /// so a restart rebuilt from this record can pass it again.
134    #[serde(skip_serializing_if = "Option::is_none", default)]
135    pub deferred_template_context: Option<String>,
136    /// The mise binary the daemon's project set with `general.mise_bin`, kept
137    /// so a retry or a cron run wraps the command with the same mise. `None`
138    /// leaves it to the supervisor's own settings and search.
139    ///
140    /// # Schema compatibility note
141    /// Omitted when `None`, and read as `None` when missing, so state files
142    /// from older binaries load unchanged. An older binary reading a newer
143    /// file ignores the key and falls back to its own `mise_bin` lookup.
144    #[serde(skip_serializing_if = "Option::is_none", default)]
145    pub mise_bin: Option<PathBuf>,
146    /// Unix user to run this daemon as.
147    #[serde(skip_serializing_if = "Option::is_none", default)]
148    pub user: Option<String>,
149    /// Memory limit for the daemon process (e.g. "50MB", "1GiB")
150    #[serde(skip_serializing_if = "Option::is_none", default)]
151    pub memory_limit: Option<MemoryLimit>,
152    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores)
153    #[serde(skip_serializing_if = "Option::is_none", default)]
154    pub cpu_limit: Option<CpuLimit>,
155    /// Unix signal to send for graceful shutdown (default: SIGTERM)
156    #[serde(skip_serializing_if = "Option::is_none", default)]
157    pub stop_signal: Option<StopConfig>,
158    /// Archive hook command invoked before retention prunes this daemon's logs.
159    #[serde(skip_serializing_if = "Option::is_none", default)]
160    pub archive_hook: Option<String>,
161    /// Log format for this daemon.
162    #[serde(skip_serializing_if = "Option::is_none", default)]
163    pub log_format: Option<String>,
164    /// Allocate a pseudo-terminal for the daemon process.
165    #[serde(skip_serializing_if = "Option::is_none", default)]
166    pub pty: Option<bool>,
167    /// True for daemons auto-registered from config by the cron watcher,
168    /// not yet started. Treated as "available" by list/status/stats.
169    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
170    pub config_registered: bool,
171    /// Run-to-completion task rather than a long-running service. Readiness is
172    /// a zero exit code, and the terminal state is `completed` instead of
173    /// `stopped`. See `DaemonStatus::Completed`.
174    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
175    pub oneshot: bool,
176    /// Set when the proxy started this run and it may be stopped for
177    /// inactivity: how long, in milliseconds, it may go without proxy
178    /// activity. `None` for a daemon started any other way, or claimed since
179    /// by an explicit start.
180    #[serde(default)]
181    pub proxy_idle_timeout_ms: Option<u64>,
182    /// When the cron watcher last actually started this daemon.
183    ///
184    /// Distinct from `last_cron_triggered`, which advances on every scheduled
185    /// tick the watcher observes -- including the anchoring tick that
186    /// `immediate = false` uses to skip the first window, and ticks where the
187    /// `retrigger` policy declines to run. Only this field means "it ran",
188    /// which is what `last_exit_success` describes the outcome of.
189    #[serde(skip_serializing_if = "Option::is_none", default)]
190    pub last_cron_run: Option<chrono::DateTime<chrono::Local>>,
191    /// Start `cmd` directly, without a shell. See `RunOptions::no_shell`.
192    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
193    pub no_shell: bool,
194    /// Registered from config by the cron watcher and only ever started by
195    /// its schedule since, so each scheduled run is built from the current
196    /// config, templates rendered, rather than from what was stored at
197    /// registration. Cleared once a client starts the daemon: a run it asked
198    /// for carries its own options, which the schedule then keeps.
199    ///
200    /// Appended after `no_shell` for the positional IPC encoding.
201    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
202    pub scheduled_from_config: bool,
203    /// The ready port as the start gave it. `ready_port` holds the port the
204    /// run actually checked, moved along with a port bump, so it cannot tell
205    /// a ready port that was bumped from one given as the bumped number. A
206    /// restart of an ad-hoc daemon starts from this one and bumps it afresh.
207    ///
208    /// Appended after `scheduled_from_config` for the positional IPC encoding.
209    #[serde(skip_serializing_if = "Option::is_none", default)]
210    pub configured_ready_port: Option<ReadyPort>,
211    /// What the daemon last reported over the Program Status Protocol
212    /// (OSC 7501). Dropped when a new run starts, and `working`/`blocked`
213    /// reports are dropped when the process exits (as are `idle` ones).
214    ///
215    /// Appended after `configured_ready_port` for the positional IPC encoding.
216    #[serde(skip_serializing_if = "Option::is_none", default)]
217    pub program_status: Option<crate::program_status::ProgramStatus>,
218}
219
220#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Default)]
221pub struct RunOptions {
222    pub id: DaemonId,
223    pub cmd: Vec<String>,
224    /// Original shell command string (from config `run`), passed verbatim to the shell.
225    /// Falls back to joining `cmd` when None (e.g. ad-hoc `pitchfork run -- cmd args`).
226    #[serde(skip_serializing_if = "Option::is_none", default)]
227    pub run: Option<String>,
228    pub force: bool,
229    pub shell_pid: Option<u32>,
230    pub dir: Dir,
231    pub autostop: bool,
232    pub cron_schedule: Option<String>,
233    pub cron_retrigger: Option<CronRetrigger>,
234    pub cron_immediate: Option<bool>,
235    pub retry: Retry,
236    pub retry_count: u32,
237    pub ready_delay: Option<u64>,
238    pub ready_output: Option<ReadyOutput>,
239    pub ready_http: Option<ReadyHttp>,
240    pub ready_port: Option<ReadyPort>,
241    pub ready_cmd: Option<ReadyCmd>,
242    pub health_cmd: Option<HealthCmd>,
243    pub health_http: Option<HealthHttp>,
244    pub health_port: Option<HealthPort>,
245    pub port: Option<PortConfig>,
246    pub wait_ready: bool,
247    #[serde(skip_serializing_if = "Vec::is_empty", default)]
248    pub depends: Vec<DaemonId>,
249    #[serde(skip_serializing_if = "Option::is_none", default)]
250    pub env: Option<IndexMap<String, String>>,
251    /// Template context for a `run` command left unrendered for `mise x`, which
252    /// is started with it in `PITCHFORK_TEMPLATE_CONTEXT`. Kept apart from `env`
253    /// so a variable of that name the user configured stays theirs.
254    #[serde(skip_serializing_if = "Option::is_none", default)]
255    pub deferred_template_context: Option<String>,
256    #[serde(skip_serializing_if = "Vec::is_empty", default)]
257    pub watch: Vec<String>,
258    #[serde(default)]
259    pub watch_mode: WatchMode,
260    #[serde(skip_serializing_if = "Option::is_none", default)]
261    pub watch_base_dir: Option<PathBuf>,
262    /// Whether to use mise for this daemon (None = inherit global general.mise setting).
263    ///
264    /// # Schema compatibility note
265    /// See `Daemon::mise` for downgrade implications when this field is `None`.
266    #[serde(skip_serializing_if = "Option::is_none", default)]
267    pub mise: Option<bool>,
268    /// The mise binary to wrap the command with, from the daemon's project
269    /// settings (`general.mise_bin`). Resolved by the client, because the
270    /// supervisor is long-lived and may have been started from a different
271    /// directory. `None` falls back to the supervisor's `resolve_mise_bin`.
272    #[serde(skip_serializing_if = "Option::is_none", default)]
273    pub mise_bin: Option<PathBuf>,
274    /// Optional stable slug alias for this daemon.
275    #[serde(skip_serializing_if = "Option::is_none", default)]
276    pub slug: Option<String>,
277    /// Whether to proxy this daemon (None = inherit global proxy.enable setting).
278    #[serde(skip_serializing_if = "Option::is_none", default)]
279    pub proxy: Option<bool>,
280    /// Unix user to run this daemon as.
281    #[serde(skip_serializing_if = "Option::is_none", default)]
282    pub user: Option<String>,
283    /// Memory limit for the daemon process (e.g. "50MB", "1GiB")
284    #[serde(skip_serializing_if = "Option::is_none", default)]
285    pub memory_limit: Option<MemoryLimit>,
286    /// CPU usage limit as a percentage (e.g. 80 for 80%, 200 for 2 cores)
287    #[serde(skip_serializing_if = "Option::is_none", default)]
288    pub cpu_limit: Option<CpuLimit>,
289    /// Unix signal to send for graceful shutdown (default: SIGTERM)
290    #[serde(skip_serializing_if = "Option::is_none", default)]
291    pub stop_signal: Option<StopConfig>,
292    /// Archive hook command invoked before retention prunes this daemon's logs.
293    #[serde(skip_serializing_if = "Option::is_none", default)]
294    pub archive_hook: Option<String>,
295    /// Log format for this daemon: `json`, `logfmt`, `auto`, or `text`.
296    #[serde(skip_serializing_if = "Option::is_none", default)]
297    pub log_format: Option<String>,
298    /// Hook triggered when the daemon produces matching output
299    #[serde(skip_serializing_if = "Option::is_none", default)]
300    pub on_output_hook: Option<crate::pitchfork_toml::OnOutputHook>,
301    /// Allocate a pseudo-terminal for the daemon process.
302    #[serde(skip_serializing_if = "Option::is_none", default)]
303    pub pty: Option<bool>,
304    /// This start describes the daemon in full, so the configuration fields
305    /// it leaves unset are cleared from the saved record instead of kept. Set
306    /// by every start except a restart of an ad-hoc daemon, which carries only
307    /// part of its record.
308    ///
309    /// False by default so that a request from an older client, which does
310    /// not send it, keeps merging into the record as it always did.
311    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
312    pub replaces_saved_record: bool,
313    /// Run-to-completion task rather than a long-running service.
314    #[serde(default)]
315    pub oneshot: bool,
316    /// How long to wait for a oneshot to finish, already resolved from the
317    /// project's `supervisor.oneshot_timeout`.
318    ///
319    /// Resolved by the client and carried on the request because the
320    /// supervisor is long-lived and may have started in another directory, so
321    /// its own `settings()` would not see the project's value. `None` leaves
322    /// the supervisor to fall back to whatever it can resolve.
323    #[serde(skip_serializing_if = "Option::is_none", default)]
324    pub oneshot_wait: Option<OneshotWait>,
325    /// This start came from entering a directory rather than from a person
326    /// asking for it, so a completed `oneshot` is left alone. Decided by the
327    /// supervisor because only it holds authoritative state: the state file
328    /// lags it by up to the flush interval, which is exactly the window a
329    /// second directory entry lands in.
330    #[serde(default)]
331    pub on_directory_enter: bool,
332    /// The proxy is starting this daemon, and it may be stopped after this
333    /// many milliseconds without proxy activity. `None` for every other start,
334    /// which is what makes such a start explicit. Carried over by restarts
335    /// (retry, file watch), which continue the same ownership.
336    #[serde(default)]
337    pub proxy_idle_timeout_ms: Option<u64>,
338    /// The cron watcher is starting this run, so a successful spawn is what
339    /// `Daemon::last_cron_run` records.
340    ///
341    /// Set only by the watcher's own call. A retry, file-watch or manual
342    /// restart of a scheduled daemon carries the daemon's `cron_schedule` but
343    /// not this, because the schedule did not ask for it.
344    #[serde(default)]
345    pub cron_started: bool,
346    /// Start `cmd` directly, without a shell: the config's `run` was an
347    /// array. `run` is `None` then, since there is no command line.
348    #[serde(default)]
349    pub no_shell: bool,
350    /// This start's ready checks are the daemon's only ones: those it leaves
351    /// unset are cleared from the record instead of kept. Set by an ad-hoc
352    /// restart given readiness flags, which replace how it was waited for.
353    ///
354    /// Appended after `no_shell` for the positional IPC encoding.
355    #[serde(default)]
356    pub replaces_ready_checks: bool,
357    /// Set by the supervisor on a start a client asked for over IPC; never
358    /// sent. See `Daemon::scheduled_from_config`.
359    #[serde(skip)]
360    pub requested_by_client: bool,
361}
362
363impl Daemon {
364    /// Whether this record was made by `pitchfork run` rather than from
365    /// config. Every start from config records `watch_base_dir`, the
366    /// directory of the project that defined it; a config daemon recorded
367    /// before that directory was stored still has the cron schedule it was
368    /// started with, which `pitchfork run` never gives a daemon.
369    pub fn is_adhoc(&self) -> bool {
370        self.watch_base_dir.is_none() && self.cron_schedule.is_none()
371    }
372
373    /// The next time the cron watcher will consider this daemon due, or
374    /// `None` when it has no schedule or the schedule does not parse.
375    ///
376    /// Anchored exactly the way `check_cron_schedules` anchors itself, so the
377    /// answer is what the watcher will actually do rather than an independent
378    /// reading of the schedule. That includes the case where the supervisor
379    /// was down across a window: the anchor is still the old tick, so the
380    /// result is a time in the past -- the overdue run the watcher takes on
381    /// its next check.
382    pub fn next_cron_run(
383        &self,
384        now: chrono::DateTime<chrono::Local>,
385    ) -> Option<chrono::DateTime<chrono::Local>> {
386        use std::str::FromStr;
387        let schedule = cron::Schedule::from_str(self.cron_schedule.as_ref()?).ok()?;
388        let anchor = match self.last_cron_triggered {
389            Some(t) => t,
390            // Mirrors the watcher's first-sighting branch: `immediate` looks
391            // back ten seconds, the default anchors to now.
392            None if self.cron_immediate.unwrap_or(false) => now - chrono::Duration::seconds(10),
393            None => now,
394        };
395        schedule.after(&anchor).next()
396    }
397
398    /// Build RunOptions from persisted daemon state.
399    ///
400    /// Carries over all configuration fields from the daemon state.
401    /// Callers can override specific fields on the returned value.
402    pub async fn to_run_options(&self, cmd: Vec<String>) -> RunOptions {
403        // Re-read on_output_hook from fresh config so restarts (retry, watch,
404        // cron) always pick up the current hook configuration.
405        // Read it from the daemon's project directory, which need not be in
406        // the supervisor's cwd ancestry (e.g. daemons started via slugs), nor
407        // contain the daemon's working directory when `dir` points elsewhere.
408        // Reading config walks the filesystem, so it runs on a blocking worker.
409        let id = self.id.clone();
410        let project_dir = self.watch_base_dir.clone().or_else(|| self.dir.clone());
411        let on_output_hook = tokio::task::spawn_blocking(move || {
412            project_dir
413                .as_deref()
414                .and_then(|dir| crate::pitchfork_toml::PitchforkToml::all_merged_from(dir).ok())
415                .or_else(|| {
416                    crate::pitchfork_toml::PitchforkToml::all_merged_all_namespaces_blocking().ok()
417                })
418                .and_then(|pt| {
419                    pt.daemons
420                        .get(&id)
421                        .and_then(|d| d.hooks.as_ref())
422                        .and_then(|h| h.on_output.clone())
423                })
424        })
425        .await
426        .ok()
427        .flatten();
428
429        RunOptions {
430            id: self.id.clone(),
431            cmd,
432            run: self.run.clone(),
433            force: false,
434            shell_pid: self.shell_pid,
435            dir: Dir(self.dir.clone().unwrap_or_else(|| crate::env::CWD.clone())),
436            autostop: self.autostop,
437            oneshot: self.oneshot,
438            // Re-resolved by the client on the paths that have a project to
439            // resolve it from; a supervisor-internal restart keeps None and
440            // falls back.
441            oneshot_wait: None,
442            on_directory_enter: false,
443            // A restart continues whatever ownership the run it replaces had.
444            proxy_idle_timeout_ms: self.proxy_idle_timeout_ms,
445            // A restart of a scheduled daemon is not the schedule starting a
446            // run; only the cron watcher's own call sets this.
447            cron_started: false,
448            no_shell: self.no_shell,
449            // Built from the whole record, whose ready checks it carries.
450            replaces_ready_checks: false,
451            // Set by the IPC handler for a client's own request.
452            requested_by_client: false,
453            cron_schedule: self.cron_schedule.clone(),
454            cron_retrigger: self.cron_retrigger,
455            cron_immediate: self.cron_immediate,
456            retry: self.retry,
457            retry_count: self.retry_count,
458            ready_delay: self.ready_delay,
459            ready_output: self.ready_output.clone(),
460            ready_http: self.ready_http.clone(),
461            ready_port: self.ready_port.clone(),
462            ready_cmd: self.ready_cmd.clone(),
463            health_cmd: self.health_cmd.clone(),
464            health_http: self.health_http.clone(),
465            health_port: self.health_port.clone(),
466            port: self.port.clone(),
467            wait_ready: false,
468            depends: self.depends.clone(),
469            env: self.env.clone(),
470            watch: self.watch.clone(),
471            watch_mode: self.watch_mode,
472            watch_base_dir: self.watch_base_dir.clone(),
473            mise: self.mise,
474            deferred_template_context: self.deferred_template_context.clone(),
475            mise_bin: self.mise_bin.clone(),
476            slug: self.slug.clone(),
477            proxy: self.proxy,
478            user: self.user.clone(),
479            memory_limit: self.memory_limit,
480            cpu_limit: self.cpu_limit,
481            stop_signal: self.stop_signal,
482            archive_hook: self.archive_hook.clone(),
483            log_format: self.log_format.clone(),
484            on_output_hook,
485            pty: self.pty,
486            // Built from the whole record, so it describes the daemon in full.
487            replaces_saved_record: true,
488        }
489    }
490}
491
492impl Display for Daemon {
493    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494        write!(f, "{}", self.id.qualified())
495    }
496}
497
498#[cfg(test)]
499mod tests {
500    use super::*;
501    use chrono::TimeZone;
502
503    fn at(h: u32, m: u32, sec: u32) -> chrono::DateTime<chrono::Local> {
504        chrono::Local
505            .with_ymd_and_hms(2026, 9, 21, h, m, sec)
506            .unwrap()
507    }
508
509    /// Daily at 03:00, the schedule from the report that asked for this.
510    fn daily_3am(last_triggered: Option<chrono::DateTime<chrono::Local>>) -> Daemon {
511        Daemon {
512            cron_schedule: Some("0 0 3 * * *".to_string()),
513            last_cron_triggered: last_triggered,
514            ..Daemon::default()
515        }
516    }
517
518    #[tokio::test]
519    async fn a_restart_from_the_saved_record_keeps_the_deferred_template_context() {
520        let daemon = Daemon {
521            deferred_template_context: Some("{\"name\":\"api\"}".to_string()),
522            ..Daemon::default()
523        };
524        let opts = daemon.to_run_options(vec!["echo".to_string()]).await;
525        assert_eq!(
526            opts.deferred_template_context.as_deref(),
527            Some("{\"name\":\"api\"}")
528        );
529    }
530
531    #[test]
532    fn next_cron_run_is_none_without_a_schedule() {
533        assert!(Daemon::default().next_cron_run(at(7, 0, 0)).is_none());
534    }
535
536    /// The watcher warns and skips an expression it cannot parse; there is no
537    /// next run to report for one.
538    #[test]
539    fn next_cron_run_is_none_for_an_invalid_schedule() {
540        let d = Daemon {
541            cron_schedule: Some("not a cron expression".to_string()),
542            ..Daemon::default()
543        };
544        assert!(d.next_cron_run(at(7, 0, 0)).is_none());
545    }
546
547    #[test]
548    fn next_cron_run_follows_the_last_tick() {
549        let d = daily_3am(Some(at(3, 0, 4)));
550        assert_eq!(
551            d.next_cron_run(at(7, 0, 0)),
552            Some(
553                chrono::Local
554                    .with_ymd_and_hms(2026, 9, 22, 3, 0, 0)
555                    .unwrap()
556            )
557        );
558    }
559
560    /// A supervisor that was down across 03:00 has a stale anchor, so the next
561    /// run is in the past: the window it still owes, which is what the watcher
562    /// will take on its next check.
563    #[test]
564    fn next_cron_run_reports_a_missed_window_as_past() {
565        let d = daily_3am(Some(
566            chrono::Local
567                .with_ymd_and_hms(2026, 9, 20, 3, 0, 0)
568                .unwrap(),
569        ));
570        let next = d.next_cron_run(at(7, 0, 0)).unwrap();
571        assert_eq!(next, at(3, 0, 0));
572        assert!(next < at(7, 0, 0));
573    }
574
575    /// Never triggered, `immediate = false`: the watcher will anchor to now
576    /// and skip the current window, so the answer is the next one.
577    #[test]
578    fn next_cron_run_skips_the_current_window_without_immediate() {
579        let d = daily_3am(None);
580        assert_eq!(
581            d.next_cron_run(at(2, 59, 0)),
582            Some(at(3, 0, 0)),
583            "a window still ahead of now is reported as-is"
584        );
585        assert_eq!(
586            d.next_cron_run(at(3, 0, 30)),
587            Some(
588                chrono::Local
589                    .with_ymd_and_hms(2026, 9, 22, 3, 0, 0)
590                    .unwrap()
591            ),
592            "a window that just passed is not claimed: immediate=false skips it"
593        );
594    }
595
596    /// `immediate = true` keeps the watcher's ten-second look-back, so a
597    /// window that just passed is still due.
598    #[test]
599    fn next_cron_run_honors_the_immediate_lookback() {
600        let d = Daemon {
601            cron_immediate: Some(true),
602            ..daily_3am(None)
603        };
604        assert_eq!(d.next_cron_run(at(3, 0, 5)), Some(at(3, 0, 0)));
605    }
606
607    #[test]
608    fn test_valid_daemon_ids() {
609        // Short IDs
610        assert!(is_valid_daemon_id("myapp"));
611        assert!(is_valid_daemon_id("my-app"));
612        assert!(is_valid_daemon_id("my_app"));
613        assert!(is_valid_daemon_id("my.app"));
614        assert!(is_valid_daemon_id("MyApp123"));
615
616        // Qualified IDs (namespace/short_id)
617        assert!(is_valid_daemon_id("project/api"));
618        assert!(is_valid_daemon_id("global/web"));
619        assert!(is_valid_daemon_id("my-project/my-app"));
620    }
621
622    #[test]
623    fn test_invalid_daemon_ids() {
624        // Empty
625        assert!(!is_valid_daemon_id(""));
626
627        // Multiple slashes (invalid qualified format)
628        assert!(!is_valid_daemon_id("a/b/c"));
629        assert!(!is_valid_daemon_id("../etc/passwd"));
630
631        // Invalid qualified format (empty parts)
632        assert!(!is_valid_daemon_id("/api"));
633        assert!(!is_valid_daemon_id("project/"));
634
635        // Backslashes
636        assert!(!is_valid_daemon_id("foo\\bar"));
637
638        // Parent directory reference
639        assert!(!is_valid_daemon_id(".."));
640        assert!(!is_valid_daemon_id("foo..bar"));
641
642        // Double dash (reserved for path encoding)
643        assert!(!is_valid_daemon_id("my--app"));
644        assert!(!is_valid_daemon_id("project--api"));
645        assert!(!is_valid_daemon_id("--app"));
646        assert!(!is_valid_daemon_id("app--"));
647
648        // Spaces
649        assert!(!is_valid_daemon_id("my app"));
650        assert!(!is_valid_daemon_id(" myapp"));
651        assert!(!is_valid_daemon_id("myapp "));
652
653        // Current directory
654        assert!(!is_valid_daemon_id("."));
655
656        // Control characters
657        assert!(!is_valid_daemon_id("my\x00app"));
658        assert!(!is_valid_daemon_id("my\napp"));
659        assert!(!is_valid_daemon_id("my\tapp"));
660
661        // Non-ASCII
662        assert!(!is_valid_daemon_id("myäpp"));
663        assert!(!is_valid_daemon_id("приложение"));
664
665        // Unsupported punctuation under DaemonId rules
666        assert!(!is_valid_daemon_id("app@host"));
667        assert!(!is_valid_daemon_id("app:8080"));
668    }
669}