Skip to main content

pitchfork_cli/
state_file.rs

1use crate::daemon::Daemon;
2use crate::daemon_id::DaemonId;
3use crate::error::FileError;
4use crate::{Result, env};
5use once_cell::sync::Lazy;
6use std::collections::{BTreeMap, BTreeSet};
7use std::fmt::Debug;
8use std::path::{Path, PathBuf};
9use std::sync::Mutex;
10use std::sync::atomic::{AtomicBool, Ordering};
11
12#[derive(Debug, serde::Serialize, serde::Deserialize)]
13pub struct StateFile {
14    #[serde(default)]
15    pub daemons: BTreeMap<DaemonId, Daemon>,
16    #[serde(default)]
17    pub disabled: BTreeSet<DaemonId>,
18    #[serde(default)]
19    pub shell_dirs: BTreeMap<String, PathBuf>,
20    /// Project sessions keyed by host PID (as string, matching `shell_dirs`)
21    /// and then by canonical directory. `#[serde(default)]` keeps older
22    /// state files (that predate project sessions) parseable.
23    #[serde(default)]
24    pub project_sessions: BTreeMap<String, BTreeMap<PathBuf, ProjectSession>>,
25    #[serde(skip)]
26    pub(crate) path: PathBuf,
27    #[serde(skip)]
28    pub(crate) dirty: AtomicBool,
29    /// Snapshot of the last written TOML content. Used by `write()` to skip
30    /// redundant disk I/O when the serialized state hasn't changed.
31    /// Guarded by the file lock in practice; `Mutex` is used only to satisfy
32    /// `Sync` since `write` takes `&self`.
33    #[serde(skip)]
34    pub(crate) last_content: Mutex<Option<String>>,
35}
36
37/// What [`StateFile::restore_daemon_in_file`] found in the file on disk.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub(crate) enum DiskRecord {
40    /// The file already had the entry.
41    Present,
42    /// The entry was missing and has been put back.
43    Restored,
44    /// The file could not be parsed and was left untouched.
45    Unparseable,
46}
47
48/// A project session entry. The owning host PID and tracked directory live in
49/// the nested map key, so the value only needs the liveness title snapshot
50/// used to mitigate PID reuse.
51#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Default)]
52pub struct ProjectSession {
53    #[serde(skip_serializing_if = "Option::is_none", default)]
54    pub liveness_title: Option<String>,
55}
56
57impl StateFile {
58    pub fn new(path: PathBuf) -> Self {
59        Self {
60            daemons: Default::default(),
61            disabled: Default::default(),
62            shell_dirs: Default::default(),
63            project_sessions: Default::default(),
64            path,
65            dirty: AtomicBool::new(false),
66            last_content: Mutex::new(None),
67        }
68    }
69
70    pub fn get() -> &'static Self {
71        static STATE_FILE: Lazy<StateFile> = Lazy::new(|| {
72            let path = &*env::PITCHFORK_STATE_FILE;
73            StateFile::read(path).unwrap_or_else(|e| {
74                error!(
75                    "failed to read state file {}: {}. Falling back to in-memory empty state",
76                    path.display(),
77                    e
78                );
79                StateFile::new(path.to_path_buf())
80            })
81        });
82        &STATE_FILE
83    }
84
85    pub fn read<P: AsRef<Path>>(path: P) -> Result<Self> {
86        let path = path.as_ref();
87        if !path.exists() {
88            return Ok(Self::new(path.to_path_buf()));
89        }
90        let canonical_path = normalized_lock_path(path);
91        let _lock = xx::fslock::get(&canonical_path, false)?;
92        let raw = xx::file::read_to_string(path).unwrap_or_else(|e| {
93            warn!("Error reading state file {path:?}: {e}");
94            String::new()
95        });
96
97        // Try to parse directly (new format with qualified IDs)
98        match toml::from_str::<Self>(&raw) {
99            Ok(mut state_file) => {
100                state_file.path = path.to_path_buf();
101                state_file.dirty = AtomicBool::new(false);
102                for (id, daemon) in state_file.daemons.iter_mut() {
103                    daemon.id = id.clone();
104                }
105                // Seed last_content with the raw TOML so the first write() can
106                // skip disk I/O when the state hasn't actually changed.
107                state_file.last_content = Mutex::new(Some(raw));
108                Ok(state_file)
109            }
110            Err(parse_err) => {
111                if Self::looks_like_old_format(&raw) {
112                    // Silent migration: attempt to rewrite bare keys as legacy/<name>
113                    debug!(
114                        "State file at {} appears to be in old format, attempting silent migration",
115                        path.display()
116                    );
117                    match Self::migrate_old_format(&raw) {
118                        Ok(migrated) => {
119                            let mut state_file = migrated;
120                            state_file.path = path.to_path_buf();
121                            // Persist migrated state while we still hold the lock
122                            if let Err(e) = state_file.write_unlocked() {
123                                warn!("State file migration write failed: {e}");
124                            }
125                            debug!("State file migrated successfully");
126                            return Ok(state_file);
127                        }
128                        Err(e) => {
129                            error!(
130                                "State file migration failed: {e}. \
131                                 Raw content preserved at {}. Starting with empty state.",
132                                path.display()
133                            );
134                            return Err(miette::miette!(
135                                "Failed to migrate state file {}: {e}",
136                                path.display()
137                            ));
138                        }
139                    }
140                }
141                // New-format parse failure: do NOT silently discard state.
142                Err(miette::miette!(
143                    "Failed to parse state file {}: {parse_err}",
144                    path.display()
145                ))
146            }
147        }
148    }
149
150    /// Returns true if the TOML looks like the old state file format, i.e. the
151    /// `daemons` table has at least one key that is missing the `namespace/`
152    /// prefix.  Detection is done by parsing as a generic `toml::Value` so it
153    /// works regardless of how the table headers are written.
154    fn looks_like_old_format(raw: &str) -> bool {
155        use toml::Value;
156        let Ok(Value::Table(doc)) = toml::from_str::<Value>(raw) else {
157            return false;
158        };
159        let Some(Value::Table(daemons)) = doc.get("daemons") else {
160            return false;
161        };
162        // Old format: at least one daemon key has no '/'
163        !daemons.is_empty() && daemons.keys().any(|k| !k.contains('/'))
164    }
165
166    /// Parse old-format state TOML (bare daemon names) and return a new-format
167    /// `StateFile` with daemon IDs qualified under the `"legacy"` namespace.
168    fn migrate_old_format(raw: &str) -> Result<Self> {
169        use toml::Value;
170
171        const LEGACY_NAMESPACE: &str = "legacy";
172
173        // Parse as generic TOML value
174        let mut doc: toml::map::Map<String, Value> = toml::from_str(raw)
175            .map_err(|e| miette::miette!("failed to parse old state file: {e}"))?;
176
177        // Re-key [daemons] entries: "name" -> "legacy/name"
178        if let Some(Value::Table(daemons)) = doc.get_mut("daemons") {
179            let old_keys: Vec<String> = daemons.keys().cloned().collect();
180            for key in old_keys {
181                if !key.contains('/')
182                    && let Some(val) = daemons.remove(&key)
183                {
184                    let mut new_key = format!("{LEGACY_NAMESPACE}/{key}");
185                    // Preserve data on collision by assigning a unique migrated key.
186                    if daemons.contains_key(&new_key) {
187                        let base = format!("{key}-legacy");
188                        let mut candidate = format!("{LEGACY_NAMESPACE}/{base}");
189                        let mut n: u32 = 2;
190                        while daemons.contains_key(&candidate) {
191                            candidate = format!("{LEGACY_NAMESPACE}/{base}-{n}");
192                            n += 1;
193                        }
194                        warn!(
195                            "Legacy daemon key '{}' collides with '{}'; migrating as '{}'",
196                            key,
197                            format_args!("{LEGACY_NAMESPACE}/{key}"),
198                            candidate
199                        );
200                        new_key = candidate;
201                    }
202                    // Update the inner `id` field too
203                    let val = if let Value::Table(mut tbl) = val {
204                        tbl.insert("id".to_string(), Value::String(new_key.clone()));
205                        Value::Table(tbl)
206                    } else {
207                        val
208                    };
209                    daemons.insert(new_key, val);
210                }
211            }
212        }
213
214        // Re-key [disabled] set entries the same way
215        if let Some(Value::Array(disabled)) = doc.get_mut("disabled") {
216            for entry in disabled.iter_mut() {
217                if let Value::String(s) = entry
218                    && !s.contains('/')
219                {
220                    *s = format!("{LEGACY_NAMESPACE}/{s}");
221                }
222            }
223        }
224
225        let new_raw =
226            toml::to_string(&Value::Table(doc)).map_err(|e| FileError::SerializeError {
227                path: PathBuf::new(),
228                source: e,
229            })?;
230
231        let mut state_file: Self = toml::from_str(&new_raw)
232            .map_err(|e| miette::miette!("failed to parse migrated state file: {e}"))?;
233        // Sync inner daemon id fields
234        for (id, daemon) in state_file.daemons.iter_mut() {
235            daemon.id = id.clone();
236        }
237        Ok(state_file)
238    }
239
240    /// Mark the state file as dirty so the background flush task will
241    /// persist it on the next tick.
242    fn mark_dirty(&self) {
243        self.dirty.store(true, Ordering::Relaxed);
244    }
245
246    /// Check whether the state file needs to be flushed.
247    pub fn is_dirty(&self) -> bool {
248        self.dirty.load(Ordering::Relaxed)
249    }
250
251    /// Insert or replace a daemon entry and mark the state dirty.
252    pub fn insert_daemon(&mut self, id: &DaemonId, daemon: Daemon) {
253        self.daemons.insert(id.clone(), daemon);
254        self.mark_dirty();
255    }
256
257    /// Set a daemon's status, marking the state dirty. Returns whether the
258    /// daemon exists.
259    pub fn set_status(
260        &mut self,
261        id: &DaemonId,
262        status: crate::daemon_status::DaemonStatus,
263    ) -> bool {
264        let Some(daemon) = self.daemons.get_mut(id) else {
265            return false;
266        };
267        daemon.status = status;
268        self.mark_dirty();
269        true
270    }
271
272    /// Clear a daemon's idle-shutdown ownership, marking the state dirty if it
273    /// had any. Returns true if it did.
274    pub fn clear_proxy_idle_timeout(&mut self, id: &DaemonId) -> bool {
275        let cleared = self
276            .daemons
277            .get_mut(id)
278            .is_some_and(|d| d.proxy_idle_timeout_ms.take().is_some());
279        if cleared {
280            self.mark_dirty();
281        }
282        cleared
283    }
284
285    /// Remove a daemon entry and mark the state dirty if the daemon existed.
286    pub fn remove_daemon(&mut self, id: &DaemonId) {
287        if self.daemons.remove(id).is_some() {
288            self.mark_dirty();
289        }
290    }
291
292    /// Disable a daemon (add to disabled set) and mark the state dirty.
293    /// Returns true if the daemon was not already disabled.
294    pub fn disable_daemon(&mut self, id: &DaemonId) -> bool {
295        let inserted = self.disabled.insert(id.clone());
296        if inserted {
297            self.mark_dirty();
298        }
299        inserted
300    }
301
302    /// Enable a daemon (remove from disabled set) and mark the state dirty.
303    /// Returns true if the daemon was previously disabled.
304    pub fn enable_daemon(&mut self, id: &DaemonId) -> bool {
305        let removed = self.disabled.remove(id);
306        if removed {
307            self.mark_dirty();
308        }
309        removed
310    }
311
312    /// Set the active port for a daemon and mark the state dirty.
313    /// Returns true if the daemon was found and updated.
314    pub fn set_active_port(&mut self, id: &DaemonId, port: u16) -> bool {
315        if let Some(d) = self.daemons.get_mut(id) {
316            d.active_port = Some(port);
317            self.mark_dirty();
318            true
319        } else {
320            false
321        }
322    }
323
324    /// Apply a program status update. Marks the state dirty only on change.
325    pub fn apply_program_status(
326        &mut self,
327        id: &DaemonId,
328        update: crate::program_status::StatusUpdate,
329    ) {
330        use crate::program_status::StatusUpdate;
331        let Some(d) = self.daemons.get_mut(id) else {
332            return;
333        };
334        let new = match update {
335            StatusUpdate::Set(status) => Some(status),
336            StatusUpdate::Clear => None,
337        };
338        if d.program_status != new {
339            d.program_status = new;
340            self.mark_dirty();
341        }
342    }
343
344    /// Drop a `working`/`blocked` program status once the process is gone.
345    pub fn drop_live_program_status(&mut self, id: &DaemonId) {
346        if let Some(d) = self.daemons.get_mut(id)
347            && d.program_status
348                .as_ref()
349                .is_some_and(|s| s.state.ends_with_process())
350        {
351            d.program_status = None;
352            self.mark_dirty();
353        }
354    }
355
356    /// Clear the active port for a daemon and mark the state dirty.
357    /// Returns true if the daemon was found and updated.
358    pub fn clear_active_port(&mut self, id: &DaemonId) -> bool {
359        if let Some(d) = self.daemons.get_mut(id) {
360            d.active_port = None;
361            self.mark_dirty();
362            true
363        } else {
364            false
365        }
366    }
367
368    /// Update the last cron trigger time for a daemon and mark the state dirty.
369    /// Returns true if the daemon was found and updated.
370    pub fn set_last_cron_triggered(
371        &mut self,
372        id: &DaemonId,
373        time: chrono::DateTime<chrono::Local>,
374    ) -> bool {
375        if let Some(d) = self.daemons.get_mut(id) {
376            d.last_cron_triggered = Some(time);
377            self.mark_dirty();
378            true
379        } else {
380            false
381        }
382    }
383
384    /// Record that the cron watcher actually started a daemon, and mark the
385    /// state dirty. Returns true if the daemon was found and updated.
386    ///
387    /// Separate from `set_last_cron_triggered` because a tick and a run are
388    /// not the same event: see `Daemon::last_cron_run`.
389    pub fn set_last_cron_run(
390        &mut self,
391        id: &DaemonId,
392        time: chrono::DateTime<chrono::Local>,
393    ) -> bool {
394        if let Some(d) = self.daemons.get_mut(id) {
395            d.last_cron_run = Some(time);
396            self.mark_dirty();
397            true
398        } else {
399            false
400        }
401    }
402
403    /// Set a shell working directory and mark the state dirty.
404    pub fn set_shell_dir(&mut self, shell_pid: u32, dir: PathBuf) {
405        self.shell_dirs.insert(shell_pid.to_string(), dir);
406        self.mark_dirty();
407    }
408
409    /// Remove a shell working directory and mark the state dirty.
410    /// Returns true if the entry existed.
411    #[cfg(unix)]
412    pub fn remove_shell_dir(&mut self, shell_pid: u32) -> bool {
413        let removed = self.shell_dirs.remove(&shell_pid.to_string()).is_some();
414        if removed {
415            self.mark_dirty();
416        }
417        removed
418    }
419
420    /// Insert or replace a project session for the given host PID and directory
421    /// and mark the state dirty. Returns the previous session, if any.
422    pub fn set_project_session(
423        &mut self,
424        pid: u32,
425        dir: PathBuf,
426        session: ProjectSession,
427    ) -> Option<ProjectSession> {
428        let inner = self.project_sessions.entry(pid.to_string()).or_default();
429        let old = inner.insert(dir, session);
430        self.mark_dirty();
431        old
432    }
433
434    /// Remove a project session for the given host PID and directory and mark
435    /// the state dirty if it existed. Returns the removed session, if any.
436    /// Empty per-PID subtables are pruned so the persisted TOML stays tidy.
437    pub fn remove_project_session(&mut self, pid: u32, dir: &Path) -> Option<ProjectSession> {
438        let pid_str = pid.to_string();
439        if let std::collections::btree_map::Entry::Occupied(mut entry) =
440            self.project_sessions.entry(pid_str)
441        {
442            let removed = entry.get_mut().remove(dir);
443            if removed.is_some() {
444                if entry.get().is_empty() {
445                    entry.remove();
446                }
447                self.mark_dirty();
448            }
449            removed
450        } else {
451            None
452        }
453    }
454
455    /// Look up a project session for the given host PID and directory.
456    #[cfg(any(unix, test))]
457    pub fn get_project_session(&self, pid: u32, dir: &Path) -> Option<&ProjectSession> {
458        self.project_sessions
459            .get(&pid.to_string())
460            .and_then(|inner| inner.get(dir))
461    }
462
463    /// Flat iterator over all project sessions yielding `(pid_str, dir, session)`
464    /// for every entry. Used by the supervisor refresh loop to evaluate liveness.
465    /// Every directory a tracked shell or project session is in.
466    pub fn active_directories(&self) -> Vec<PathBuf> {
467        let mut dirs: std::collections::HashSet<PathBuf> =
468            self.shell_dirs.values().cloned().collect();
469        for (_, dir, _) in self.iter_project_sessions() {
470            dirs.insert(dir.clone());
471        }
472        dirs.into_iter().collect()
473    }
474
475    pub fn iter_project_sessions(&self) -> Vec<(&str, &PathBuf, &ProjectSession)> {
476        let mut out: Vec<(&str, &PathBuf, &ProjectSession)> = Vec::new();
477        for (pid_str, inner) in &self.project_sessions {
478            for (dir, session) in inner {
479                out.push((pid_str.as_str(), dir, session));
480            }
481        }
482        out
483    }
484
485    /// Retain only daemons matching the predicate and mark the state dirty
486    /// if any were removed.
487    pub fn retain_daemons<F>(&mut self, mut f: F)
488    where
489        F: FnMut(&DaemonId, &Daemon) -> bool,
490    {
491        let before = self.daemons.len();
492        self.daemons.retain(|id, daemon| f(id, daemon));
493        if self.daemons.len() != before {
494            self.mark_dirty();
495        }
496    }
497
498    /// Synchronous force-write. Clears the dirty flag. If the serialized
499    /// content matches the last written content, the disk write is skipped to
500    /// avoid unnecessary I/O. Used during shutdown and migration where async
501    /// flushing is not available.
502    pub fn write(&self) -> Result<()> {
503        let canonical_path = normalized_lock_path(&self.path);
504        let _lock = xx::fslock::get(&canonical_path, false)?;
505        let raw = toml::to_string(self).map_err(|e| FileError::SerializeError {
506            path: self.path.clone(),
507            source: e,
508        })?;
509        if self
510            .last_content
511            .lock()
512            .unwrap()
513            .as_ref()
514            .is_some_and(|last| last == &raw)
515        {
516            // No real change — just clear the dirty flag
517            self.dirty.store(false, Ordering::Relaxed);
518            return Ok(());
519        }
520        Self::write_raw(&self.path, &raw)?;
521        *self.last_content.lock().unwrap() = Some(raw);
522        self.dirty.store(false, Ordering::Relaxed);
523        Ok(())
524    }
525
526    /// Put `daemon`'s entry back into the state file at `path` if the file no
527    /// longer has it (with the same PID), leaving the rest of the file as it
528    /// is now. The check and the write happen under one lock, so a concurrent
529    /// writer's update is not lost. Blocking; run it off the async workers.
530    pub(crate) fn restore_daemon_in_file(path: &Path, daemon: &Daemon) -> Result<DiskRecord> {
531        let canonical_path = normalized_lock_path(path);
532        let _lock = xx::fslock::get(&canonical_path, false)?;
533        // A missing file (deleted since) just gets the entry back; any other
534        // read failure must not be mistaken for an empty file, which would
535        // replace the existing records.
536        let raw = match std::fs::read_to_string(path) {
537            Ok(raw) => raw,
538            Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
539            Err(source) => {
540                return Err(FileError::ReadError {
541                    path: path.to_path_buf(),
542                    source,
543                }
544                .into());
545            }
546        };
547        let Ok(mut on_disk) = toml::from_str::<Self>(&raw) else {
548            return Ok(DiskRecord::Unparseable);
549        };
550        if on_disk.daemons.get(&daemon.id).and_then(|d| d.pid) == daemon.pid {
551            return Ok(DiskRecord::Present);
552        }
553        on_disk.daemons.insert(daemon.id.clone(), daemon.clone());
554        let raw = toml::to_string(&on_disk).map_err(|e| FileError::SerializeError {
555            path: path.to_path_buf(),
556            source: e,
557        })?;
558        Self::write_raw(path, &raw)?;
559        Ok(DiskRecord::Restored)
560    }
561
562    /// Apply `f` to the state in the file at `path` and write it back if `f`
563    /// reports a change, reading and writing under one lock so a concurrent
564    /// writer's update is not lost. A missing file is left missing. Blocking.
565    pub(crate) fn update_in_file<T>(
566        path: &Path,
567        f: impl FnOnce(&mut Self) -> (bool, T),
568    ) -> Result<T> {
569        let canonical_path = normalized_lock_path(path);
570        let _lock = xx::fslock::get(&canonical_path, false)?;
571        let raw = match std::fs::read_to_string(path) {
572            Ok(raw) => raw,
573            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
574                let (_, out) = f(&mut Self::new(path.to_path_buf()));
575                return Ok(out);
576            }
577            Err(source) => {
578                return Err(FileError::ReadError {
579                    path: path.to_path_buf(),
580                    source,
581                }
582                .into());
583            }
584        };
585        let mut sf: Self = toml::from_str(&raw)
586            .map_err(|e| miette::miette!("failed to parse state file {}: {e}", path.display()))?;
587        sf.path = path.to_path_buf();
588        for (id, daemon) in sf.daemons.iter_mut() {
589            daemon.id = id.clone();
590        }
591        let (changed, out) = f(&mut sf);
592        if changed {
593            let raw = toml::to_string(&sf).map_err(|e| FileError::SerializeError {
594                path: path.to_path_buf(),
595                source: e,
596            })?;
597            Self::write_raw(path, &raw)?;
598        }
599        Ok(out)
600    }
601
602    /// Forget what this instance last wrote, because the file has changed
603    /// since: the next write must not be skipped as unchanged.
604    pub(crate) fn forget_written_snapshot(&self) {
605        *self.last_content.lock().unwrap() = None;
606    }
607
608    /// Rewrite the file with this state on the next flush.
609    pub(crate) fn force_next_write(&self) {
610        self.forget_written_snapshot();
611        self.mark_dirty();
612    }
613
614    /// Write the state file without acquiring the lock.
615    /// Used internally when the lock is already held (e.g., during migration in read()).
616    fn write_unlocked(&self) -> Result<()> {
617        let raw = toml::to_string(self).map_err(|e| FileError::SerializeError {
618            path: self.path.clone(),
619            source: e,
620        })?;
621        Self::write_raw(&self.path, &raw)?;
622        *self.last_content.lock().unwrap() = Some(raw);
623        self.dirty.store(false, Ordering::Relaxed);
624        Ok(())
625    }
626
627    /// Perform the actual file I/O (temp file + atomic rename).
628    /// **The caller MUST hold the file lock** (via `xx::fslock::get`) before
629    /// calling this function; otherwise concurrent writes may corrupt the file.
630    pub(crate) fn write_raw(path: &Path, raw: &str) -> Result<()> {
631        if let Some(parent) = path.parent() {
632            std::fs::create_dir_all(parent).map_err(|e| FileError::WriteError {
633                path: parent.to_path_buf(),
634                details: Some(format!("failed to create state file directory: {e}")),
635            })?;
636        }
637        let temp_path = path.with_extension("toml.tmp");
638        xx::file::write(&temp_path, raw).map_err(|e| FileError::WriteError {
639            path: temp_path.clone(),
640            details: Some(e.to_string()),
641        })?;
642        std::fs::rename(&temp_path, path).map_err(|e| FileError::WriteError {
643            path: path.to_path_buf(),
644            details: Some(format!("failed to rename temp file: {e}")),
645        })?;
646        Ok(())
647    }
648}
649
650fn normalized_lock_path(path: &Path) -> PathBuf {
651    if let Ok(canonical) = path.canonicalize() {
652        return canonical;
653    }
654
655    if let Some(parent) = path.parent()
656        && let Ok(canonical_parent) = parent.canonicalize()
657        && let Some(file_name) = path.file_name()
658    {
659        return canonical_parent.join(file_name);
660    }
661
662    path.to_path_buf()
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668    use crate::daemon_status::DaemonStatus;
669
670    #[test]
671    fn program_status_survives_exit_only_when_finished() {
672        use crate::program_status::{ProgramState, ProgramStatus, StatusUpdate};
673        let mut state = StateFile::new(PathBuf::from("/tmp/test.toml"));
674        let id = DaemonId::new("project", "job");
675        state.daemons.insert(
676            id.clone(),
677            Daemon {
678                id: id.clone(),
679                ..Daemon::default()
680            },
681        );
682        let set = |state| {
683            StatusUpdate::Set(ProgramStatus {
684                state,
685                progress: None,
686                msg: Some("step".into()),
687            })
688        };
689
690        state.apply_program_status(&id, set(ProgramState::Working));
691        state.drop_live_program_status(&id);
692        assert!(state.daemons[&id].program_status.is_none());
693
694        state.apply_program_status(&id, set(ProgramState::Done));
695        state.drop_live_program_status(&id);
696        assert_eq!(
697            state.daemons[&id].program_status.as_ref().map(|s| s.state),
698            Some(ProgramState::Done)
699        );
700
701        state.apply_program_status(&id, StatusUpdate::Clear);
702        assert!(state.daemons[&id].program_status.is_none());
703    }
704
705    #[test]
706    fn test_state_file_toml_roundtrip_stopped() {
707        let mut state = StateFile::new(PathBuf::from("/tmp/test.toml"));
708        let daemon_id = DaemonId::new("project", "test");
709        state.daemons.insert(
710            daemon_id.clone(),
711            Daemon {
712                id: daemon_id,
713                status: DaemonStatus::Stopped,
714                last_exit_success: Some(true),
715                user: Some("postgres".to_string()),
716                ..Daemon::default()
717            },
718        );
719
720        let toml_str = toml::to_string(&state).unwrap();
721        println!("Serialized TOML:\n{toml_str}");
722
723        let parsed: StateFile = toml::from_str(&toml_str).expect("Failed to parse TOML");
724        println!("Parsed: {parsed:?}");
725
726        assert!(
727            parsed
728                .daemons
729                .contains_key(&DaemonId::new("project", "test"))
730        );
731        let daemon = parsed
732            .daemons
733            .get(&DaemonId::new("project", "test"))
734            .unwrap();
735        assert_eq!(daemon.user.as_deref(), Some("postgres"));
736    }
737
738    #[test]
739    fn test_looks_like_old_format_bare_names() {
740        let old = r#"
741[daemons.api]
742id = "api"
743autostop = false
744retry = 0
745retry_count = 0
746status = "stopped"
747"#;
748        assert!(StateFile::looks_like_old_format(old));
749    }
750
751    #[test]
752    fn test_looks_like_old_format_new_format() {
753        let new = r#"
754    disabled = []
755
756    [daemons."legacy/api"]
757    id = "legacy/api"
758autostop = false
759retry = 0
760retry_count = 0
761status = "stopped"
762"#;
763        assert!(!StateFile::looks_like_old_format(new));
764    }
765
766    #[test]
767    fn test_looks_like_old_format_empty() {
768        assert!(!StateFile::looks_like_old_format(""));
769        assert!(!StateFile::looks_like_old_format("[shell_dirs]"));
770    }
771
772    #[test]
773    fn test_migrate_old_format_basic() {
774        let old = r#"
775[daemons.api]
776id = "api"
777autostop = false
778retry = 0
779retry_count = 0
780status = "stopped"
781
782[daemons.worker]
783id = "worker"
784autostop = false
785retry = 0
786retry_count = 0
787status = "stopped"
788last_exit_success = true
789"#;
790        let migrated = StateFile::migrate_old_format(old).expect("migration should succeed");
791        assert!(
792            migrated
793                .daemons
794                .contains_key(&DaemonId::new("legacy", "api")),
795            "api should be migrated to legacy/api"
796        );
797        assert!(
798            migrated
799                .daemons
800                .contains_key(&DaemonId::new("legacy", "worker")),
801            "worker should be migrated to legacy/worker"
802        );
803        assert_eq!(migrated.daemons.len(), 2);
804    }
805
806    #[test]
807    fn test_migrate_old_format_preserves_disabled() {
808        let old = r#"
809disabled = ["api", "worker"]
810
811[daemons.api]
812id = "api"
813autostop = false
814retry = 0
815retry_count = 0
816status = "stopped"
817"#;
818        let migrated = StateFile::migrate_old_format(old).expect("migration should succeed");
819        assert!(
820            migrated.disabled.contains(&DaemonId::new("legacy", "api")),
821            "disabled 'api' should become 'legacy/api'"
822        );
823        assert!(
824            migrated
825                .disabled
826                .contains(&DaemonId::new("legacy", "worker")),
827            "disabled 'worker' should become 'legacy/worker'"
828        );
829    }
830
831    #[test]
832    fn test_migrate_old_format_already_qualified_unchanged() {
833        // If somehow a key already has a namespace, it should not be double-prefixed
834        let mixed = r#"
835[daemons.bare]
836id = "bare"
837autostop = false
838retry = 0
839retry_count = 0
840status = "stopped"
841"#;
842        let migrated = StateFile::migrate_old_format(mixed).expect("migration should succeed");
843        // "bare" -> "legacy/bare", not "legacy/legacy/bare"
844        assert!(
845            migrated
846                .daemons
847                .contains_key(&DaemonId::new("legacy", "bare")),
848            "bare key should become legacy/bare"
849        );
850        // Should not have double-prefixed entry
851        assert_eq!(migrated.daemons.len(), 1);
852    }
853
854    #[test]
855    fn test_migrate_old_format_does_not_overwrite_existing_qualified_entry() {
856        let mixed = r#"
857[daemons.api]
858id = "api"
859cmd = ["echo", "old"]
860autostop = false
861retry = 0
862retry_count = 0
863status = "stopped"
864
865[daemons."legacy/api"]
866id = "legacy/api"
867cmd = ["echo", "new"]
868autostop = false
869retry = 0
870retry_count = 0
871status = "stopped"
872"#;
873
874        let migrated = StateFile::migrate_old_format(mixed).expect("migration should succeed");
875        let key = DaemonId::new("legacy", "api");
876        let daemon = migrated.daemons.get(&key).expect("legacy/api should exist");
877
878        let cmd = daemon.cmd.as_ref().expect("cmd should exist");
879        assert_eq!(cmd, &vec!["echo".to_string(), "new".to_string()]);
880
881        // Colliding bare key should be preserved under a unique migrated key.
882        let preserved = DaemonId::new("legacy", "api-legacy");
883        let preserved_daemon = migrated
884            .daemons
885            .get(&preserved)
886            .expect("colliding bare key should be preserved as legacy/api-legacy");
887        let preserved_cmd = preserved_daemon
888            .cmd
889            .as_ref()
890            .expect("preserved cmd should exist");
891        assert_eq!(preserved_cmd, &vec!["echo".to_string(), "old".to_string()]);
892        assert_eq!(migrated.daemons.len(), 2);
893    }
894
895    #[test]
896    fn test_project_sessions_nested_map_roundtrip() {
897        let mut state = StateFile::new(PathBuf::from("/tmp/test.toml"));
898        state.set_project_session(
899            1234,
900            PathBuf::from("/projects/a"),
901            ProjectSession {
902                liveness_title: Some("sleep".to_string()),
903            },
904        );
905        state.set_project_session(
906            1234,
907            PathBuf::from("/projects/b"),
908            ProjectSession {
909                liveness_title: None,
910            },
911        );
912        state.set_project_session(
913            5678,
914            PathBuf::from("/projects/a"),
915            ProjectSession {
916                liveness_title: Some("code".to_string()),
917            },
918        );
919
920        let toml_str = toml::to_string(&state).unwrap();
921        let parsed: StateFile = toml::from_str(&toml_str).expect("roundtrip parse");
922
923        // All three sessions survive.
924        assert_eq!(parsed.iter_project_sessions().len(), 3);
925        assert!(
926            parsed
927                .get_project_session(1234, &PathBuf::from("/projects/a"))
928                .is_some()
929        );
930        assert!(
931            parsed
932                .get_project_session(1234, &PathBuf::from("/projects/b"))
933                .is_some()
934        );
935        assert!(
936            parsed
937                .get_project_session(5678, &PathBuf::from("/projects/a"))
938                .is_some()
939        );
940
941        // Removal prunes the per-PID subtable when it becomes empty.
942        let mut state = parsed;
943        state.remove_project_session(5678, &PathBuf::from("/projects/a"));
944        assert!(
945            state
946                .get_project_session(5678, &PathBuf::from("/projects/a"))
947                .is_none()
948        );
949        assert!(!state.project_sessions.contains_key("5678"));
950        assert_eq!(state.iter_project_sessions().len(), 2);
951    }
952}