1use super::Supervisor;
6use crate::Result;
7use crate::daemon::Daemon;
8use crate::daemon::RunOptions;
9use crate::daemon_id::DaemonId;
10use crate::daemon_status::DaemonStatus;
11use crate::pitchfork_toml::CpuLimit;
12use crate::pitchfork_toml::CronRetrigger;
13use crate::pitchfork_toml::HealthCmd;
14use crate::pitchfork_toml::HealthHttp;
15use crate::pitchfork_toml::HealthPort;
16use crate::pitchfork_toml::MemoryLimit;
17use crate::pitchfork_toml::PitchforkToml;
18use crate::pitchfork_toml::PortConfig;
19use crate::pitchfork_toml::ReadyCmd;
20use crate::pitchfork_toml::ReadyHttp;
21use crate::pitchfork_toml::ReadyOutput;
22use crate::pitchfork_toml::ReadyPort;
23use crate::pitchfork_toml::Retry;
24use crate::pitchfork_toml::StopConfig;
25use crate::pitchfork_toml::WatchMode;
26use crate::procs::PROCS;
27use crate::state_file::DiskRecord;
28use indexmap::IndexMap;
29use std::collections::HashMap;
30use std::path::PathBuf;
31
32fn should_clean_daemon(
33 id: &DaemonId,
34 daemon: &Daemon,
35 namespaces: &[String],
36 daemons: &[DaemonId],
37) -> bool {
38 let namespace_matches =
39 namespaces.is_empty() || namespaces.iter().any(|ns| ns == id.namespace());
40 let daemon_matches = daemons.is_empty() || daemons.contains(id);
41 daemon.pid.is_none() && namespace_matches && daemon_matches
42}
43
44fn prune_candidate(
45 id: &DaemonId,
46 daemon: &Daemon,
47 namespaces: &[String],
48 daemons: &[DaemonId],
49) -> Option<(DaemonId, PathBuf)> {
50 should_clean_daemon(id, daemon, namespaces, daemons)
51 .then(|| daemon.dir.clone())
52 .flatten()
53 .map(|dir| (id.clone(), dir))
54}
55
56#[derive(Debug, Default)]
60pub(crate) struct UpsertDaemonOpts {
61 pub id: DaemonId,
62 pub pid: Option<u32>,
63 pub status: DaemonStatus,
64 pub shell_pid: Option<u32>,
65 pub dir: Option<PathBuf>,
66 pub cmd: Option<Vec<String>>,
67 pub run: Option<String>,
68 pub no_shell: Option<bool>,
71 pub scheduled_from_config: Option<bool>,
74 pub autostop: Option<bool>,
78 pub oneshot: Option<bool>,
82 pub cron_schedule: Option<Option<String>>,
87 pub cron_retrigger: Option<CronRetrigger>,
88 pub cron_immediate: Option<bool>,
89 pub last_exit_success: Option<bool>,
90 pub retry: Option<Retry>,
91 pub retry_count: Option<u32>,
92 pub ready_delay: Option<u64>,
93 pub ready_output: Option<ReadyOutput>,
94 pub ready_http: Option<ReadyHttp>,
95 pub ready_port: Option<ReadyPort>,
96 pub configured_ready_port: Option<ReadyPort>,
98 pub ready_cmd: Option<ReadyCmd>,
99 pub replaces_ready_checks: bool,
102 pub health_cmd: Option<HealthCmd>,
103 pub health_http: Option<HealthHttp>,
104 pub health_port: Option<HealthPort>,
105 pub port: Option<PortConfig>,
107 pub resolved_port: Option<Vec<u16>>,
111 pub active_port: Option<u16>,
113 pub slug: Option<String>,
115 pub proxy: Option<bool>,
117 pub depends: Option<Vec<DaemonId>>,
118 pub env: Option<IndexMap<String, String>>,
119 pub watch: Option<Vec<String>>,
120 pub watch_mode: Option<WatchMode>,
121 pub watch_base_dir: Option<Option<PathBuf>>,
126 pub mise: Option<bool>,
127 pub deferred_template_context: Option<Option<String>>,
130 pub mise_bin: Option<Option<PathBuf>>,
134 pub user: Option<String>,
136 pub memory_limit: Option<MemoryLimit>,
138 pub cpu_limit: Option<CpuLimit>,
140 pub stop_signal: Option<StopConfig>,
142 pub archive_hook: Option<String>,
144 pub log_format: Option<String>,
146 pub pty: Option<bool>,
148 pub config_registered: bool,
150 pub replaces_config: bool,
155 pub proxy_idle_timeout_ms: Option<Option<u64>>,
159}
160
161#[derive(Debug)]
173pub(crate) struct UpsertDaemonOptsBuilder {
174 pub opts: UpsertDaemonOpts,
175}
176
177impl UpsertDaemonOpts {
178 pub fn builder(id: DaemonId) -> UpsertDaemonOptsBuilder {
180 UpsertDaemonOptsBuilder {
181 opts: UpsertDaemonOpts {
182 id,
183 ..Default::default()
184 },
185 }
186 }
187
188 pub(crate) fn from_run_options(
192 opts: &RunOptions,
193 status: DaemonStatus,
194 ) -> UpsertDaemonOptsBuilder {
195 UpsertDaemonOpts::builder(opts.id.clone()).set(|o| {
196 o.replaces_config = opts.replaces_saved_record;
197 o.status = status;
198 o.shell_pid = opts.shell_pid;
199 o.dir = Some(opts.dir.0.clone());
200 o.cmd = Some(opts.cmd.clone());
201 o.run = opts.run.clone();
202 o.no_shell = Some(opts.no_shell);
203 o.scheduled_from_config = opts.requested_by_client.then_some(false);
206 o.autostop = Some(opts.autostop);
207 o.oneshot = Some(opts.oneshot);
208 o.cron_schedule = Some(opts.cron_schedule.clone());
209 o.cron_retrigger = opts.cron_retrigger;
210 o.cron_immediate = opts.cron_immediate;
211 o.retry = Some(opts.retry);
212 o.retry_count = Some(opts.retry_count);
213 o.ready_delay = opts.ready_delay;
214 o.ready_output = opts.ready_output.clone();
215 o.ready_http = opts.ready_http.clone();
216 o.ready_port = opts.ready_port.clone();
217 o.configured_ready_port = opts.ready_port.clone();
218 o.ready_cmd = opts.ready_cmd.clone();
219 o.replaces_ready_checks = opts.replaces_ready_checks;
220 o.health_cmd = opts.health_cmd.clone();
221 o.health_http = opts.health_http.clone();
222 o.health_port = opts.health_port.clone();
223 o.port = opts.port.clone();
224 o.depends = Some(opts.depends.clone());
225 o.env = opts.env.clone();
226 o.watch = Some(opts.watch.clone());
227 o.watch_mode = Some(opts.watch_mode);
228 o.watch_base_dir = Some(opts.watch_base_dir.clone());
229 o.mise = opts.mise;
230 o.deferred_template_context = Some(opts.deferred_template_context.clone());
231 o.mise_bin = Some(opts.mise_bin.clone());
232 o.user = opts.user.clone();
233 o.memory_limit = opts.memory_limit;
234 o.cpu_limit = opts.cpu_limit;
235 o.stop_signal = opts.stop_signal;
236 o.pty = opts.pty;
237 o.archive_hook = opts.archive_hook.clone();
238 o.log_format = opts.log_format.clone();
239 o.proxy_idle_timeout_ms = Some(opts.proxy_idle_timeout_ms);
240 })
241 }
242}
243
244impl UpsertDaemonOptsBuilder {
245 pub fn set<F: FnOnce(&mut UpsertDaemonOpts)>(mut self, f: F) -> Self {
247 f(&mut self.opts);
248 self
249 }
250
251 pub fn build(self) -> UpsertDaemonOpts {
253 self.opts
254 }
255}
256
257impl Supervisor {
258 pub(crate) async fn restore_own_record(&self) {
268 if self
269 .shutting_down
270 .load(std::sync::atomic::Ordering::Acquire)
271 {
272 return;
273 }
274 let pitchfork_id = DaemonId::pitchfork();
275 let state = self.state_file.lock().await;
276 if self
280 .shutting_down
281 .load(std::sync::atomic::Ordering::Acquire)
282 {
283 return;
284 }
285 let Some(own) = state
286 .daemons
287 .get(&pitchfork_id)
288 .filter(|d| d.pid.is_some())
289 .cloned()
290 else {
291 return;
292 };
293 let own_pid = own.pid.unwrap_or_default();
294 let path = state.path.clone();
295 let result = tokio::task::spawn_blocking(move || {
298 crate::state_file::StateFile::restore_daemon_in_file(&path, &own)
299 })
300 .await;
301 match result {
302 Ok(Ok(DiskRecord::Present)) => {}
303 Ok(Ok(DiskRecord::Restored)) => {
304 if state.is_dirty() {
307 debug!("recorded this supervisor in the state file ahead of the next flush");
308 } else {
309 warn!(
310 "state file {} no longer recorded this supervisor (pid {own_pid}); restored it",
311 state.path.display()
312 );
313 }
314 state.forget_written_snapshot();
317 }
318 Ok(Ok(DiskRecord::Unparseable)) => {
319 warn!(
320 "state file {} cannot be parsed; rewriting it from the supervisor's state",
321 state.path.display()
322 );
323 state.force_next_write();
324 }
325 Ok(Err(e)) => warn!("failed to restore the supervisor record in the state file: {e}"),
326 Err(e) => warn!("failed to restore the supervisor record in the state file: {e}"),
327 }
328 }
329
330 pub(crate) async fn run_options_from_config(
337 &self,
338 id: &DaemonId,
339 config: &crate::pitchfork_toml::PitchforkTomlDaemon,
340 pt: &PitchforkToml,
341 ) -> Result<RunOptions> {
342 let resolved_daemons: std::collections::HashMap<DaemonId, Vec<u16>> = {
343 let state = self.state_file.lock().await;
344 state
345 .daemons
346 .iter()
347 .filter(|(_, d)| !d.resolved_port.is_empty())
348 .map(|(id, d)| (id.clone(), d.resolved_port.clone()))
349 .collect()
350 };
351 let id = id.clone();
355 let mut config = config.clone();
356 let pt = pt.clone();
357 tokio::task::spawn_blocking(move || {
358 crate::ipc::batch::render_daemon_config_with(&id, &mut config, &pt, &resolved_daemons)?;
359 let cmd = config
360 .run
361 .argv()
362 .map_err(|e| miette::miette!("failed to parse command for daemon {id}: {e}"))?;
363 let mut opts = config.to_run_options(&id, cmd);
364 let (mise, mise_bin) = crate::ipc::batch::project_mise_options(&config);
368 opts.mise = Some(mise);
369 opts.mise_bin = mise_bin;
370 if crate::ipc::batch::should_inject_default_ready_delay(&opts) {
373 let project_dir =
374 crate::ipc::batch::resolve_config_base_dir(config.path.as_deref());
375 let (settings, _) = crate::settings::Settings::resolve_from_dir(&project_dir);
376 opts.ready_delay = Some(
377 settings
378 .general_ready_delay_secs()
379 .map_err(|e| miette::miette!("{e}"))?,
380 );
381 }
382 Ok(opts)
383 })
384 .await
385 .map_err(|e| miette::miette!("rendering daemon config panicked: {e}"))?
386 }
387
388 pub(crate) async fn upsert_daemon(&self, opts: UpsertDaemonOpts) -> Result<Daemon> {
390 info!(
391 "upserting daemon: {} pid: {} status: {}",
392 opts.id,
393 opts.pid.unwrap_or(0),
394 opts.status
395 );
396 let mut state_file = self.state_file.lock().await;
397 let existing = state_file.daemons.get(&opts.id);
398 let configured = existing.filter(|_| !opts.replaces_config);
401 let ready_base = configured.filter(|_| !opts.replaces_ready_checks);
404 let daemon = Daemon {
405 id: opts.id.clone(),
406 title: opts.pid.and_then(|pid| {
412 PROCS.title(pid).or_else(|| {
413 existing
414 .filter(|d| d.pid == Some(pid))
415 .and_then(|d| d.title.clone())
416 })
417 }),
418 start_time: opts.pid.and_then(|pid| {
419 PROCS.start_time(pid).or_else(|| {
420 existing
421 .filter(|d| d.pid == Some(pid))
422 .and_then(|d| d.start_time)
423 })
424 }),
425 boot_time: opts.pid.map(|_| PROCS.boot_time()),
429 pid: opts.pid,
430 status: opts.status,
431 shell_pid: opts.shell_pid,
432 autostop: opts
433 .autostop
434 .unwrap_or_else(|| existing.is_some_and(|d| d.autostop)),
435 oneshot: opts
440 .oneshot
441 .unwrap_or_else(|| existing.is_some_and(|d| d.oneshot)),
442 dir: opts.dir.or(configured.and_then(|d| d.dir.clone())),
443 cmd: opts.cmd.or(configured.and_then(|d| d.cmd.clone())),
444 run: if opts.no_shell == Some(true) {
447 None
448 } else {
449 opts.run.or(configured.and_then(|d| d.run.clone()))
450 },
451 no_shell: opts
452 .no_shell
453 .unwrap_or_else(|| existing.is_some_and(|d| d.no_shell)),
454 scheduled_from_config: opts
455 .scheduled_from_config
456 .unwrap_or_else(|| existing.is_some_and(|d| d.scheduled_from_config)),
457 cron_schedule: opts
458 .cron_schedule
459 .unwrap_or_else(|| configured.and_then(|d| d.cron_schedule.clone())),
460 cron_retrigger: opts
461 .cron_retrigger
462 .or(configured.and_then(|d| d.cron_retrigger)),
463 cron_immediate: opts
464 .cron_immediate
465 .or(configured.and_then(|d| d.cron_immediate)),
466 last_cron_triggered: existing.and_then(|d| d.last_cron_triggered),
467 last_cron_run: existing.and_then(|d| d.last_cron_run),
468 last_exit_success: opts
469 .last_exit_success
470 .or(existing.and_then(|d| d.last_exit_success)),
471 retry: opts
472 .retry
473 .unwrap_or_else(|| existing.map(|d| d.retry).unwrap_or_default()),
474 retry_count: opts
475 .retry_count
476 .unwrap_or(existing.map(|d| d.retry_count).unwrap_or(0)),
477 ready_delay: opts.ready_delay.or(ready_base.and_then(|d| d.ready_delay)),
478 ready_output: opts
479 .ready_output
480 .or(ready_base.and_then(|d| d.ready_output.clone())),
481 ready_http: opts
482 .ready_http
483 .or(ready_base.and_then(|d| d.ready_http.clone())),
484 ready_port: opts
485 .ready_port
486 .or(ready_base.and_then(|d| d.ready_port.clone())),
487 configured_ready_port: opts
488 .configured_ready_port
489 .or(ready_base.and_then(|d| d.configured_ready_port.clone())),
490 ready_cmd: opts
491 .ready_cmd
492 .or(ready_base.and_then(|d| d.ready_cmd.clone())),
493 health_cmd: opts
494 .health_cmd
495 .or(configured.and_then(|d| d.health_cmd.clone())),
496 health_http: opts
497 .health_http
498 .or(configured.and_then(|d| d.health_http.clone())),
499 health_port: opts
500 .health_port
501 .or(configured.and_then(|d| d.health_port.clone())),
502 port: opts
503 .port
504 .or_else(|| configured.and_then(|d| d.port.clone())),
505 resolved_port: match opts.resolved_port {
506 Some(ports) => ports,
507 None => existing
508 .map(|d| d.resolved_port.clone())
509 .unwrap_or_default(),
510 },
511 depends: opts
512 .depends
513 .unwrap_or_else(|| existing.map(|d| d.depends.clone()).unwrap_or_default()),
514 env: opts.env.or(configured.and_then(|d| d.env.clone())),
515 watch: opts
516 .watch
517 .unwrap_or_else(|| existing.map(|d| d.watch.clone()).unwrap_or_default()),
518 watch_mode: opts
519 .watch_mode
520 .unwrap_or_else(|| existing.map(|d| d.watch_mode).unwrap_or_default()),
521 watch_base_dir: opts
522 .watch_base_dir
523 .unwrap_or_else(|| configured.and_then(|d| d.watch_base_dir.clone())),
524 mise: opts.mise.or(configured.and_then(|d| d.mise)),
525 deferred_template_context: opts
526 .deferred_template_context
527 .unwrap_or_else(|| existing.and_then(|d| d.deferred_template_context.clone())),
528 mise_bin: opts
529 .mise_bin
530 .unwrap_or_else(|| configured.and_then(|d| d.mise_bin.clone())),
531 user: opts.user.or(configured.and_then(|d| d.user.clone())),
532 proxy: opts.proxy.or(existing.and_then(|d| d.proxy)),
533 active_port: opts.active_port,
539 slug: opts.slug.or(existing.and_then(|d| d.slug.clone())),
540 memory_limit: opts
541 .memory_limit
542 .or(configured.and_then(|d| d.memory_limit)),
543 cpu_limit: opts.cpu_limit.or(configured.and_then(|d| d.cpu_limit)),
544 stop_signal: opts.stop_signal.or(configured.and_then(|d| d.stop_signal)),
545 archive_hook: opts
546 .archive_hook
547 .or(configured.and_then(|d| d.archive_hook.clone())),
548 log_format: opts
549 .log_format
550 .or(configured.and_then(|d| d.log_format.clone())),
551 pty: opts.pty.or(configured.and_then(|d| d.pty)),
552 config_registered: opts.config_registered,
553 proxy_idle_timeout_ms: opts
554 .proxy_idle_timeout_ms
555 .unwrap_or_else(|| existing.and_then(|d| d.proxy_idle_timeout_ms)),
556 };
557 state_file.insert_daemon(&opts.id, daemon.clone());
558 Ok(daemon)
559 }
560
561 pub async fn enable(&self, id: &DaemonId) -> Result<bool> {
563 info!("enabling daemon: {id}");
564 let config = PitchforkToml::all_merged_all_namespaces().await?;
565 let mut state_file = self.state_file.lock().await;
566 let exists = state_file.daemons.contains_key(id) || config.daemons.contains_key(id);
567 if !exists {
568 return Err(miette::miette!("daemon '{}' not found", id));
569 }
570 let result = state_file.enable_daemon(id);
571 Ok(result)
572 }
573
574 pub async fn disable(&self, id: &DaemonId) -> Result<bool> {
576 info!("disabling daemon: {id}");
577 let config = PitchforkToml::all_merged_all_namespaces().await?;
578 let not_found = || miette::miette!("daemon '{}' not found", id);
579 if !config.daemons.contains_key(id)
582 && !self.state_file.lock().await.daemons.contains_key(id)
583 {
584 return Err(not_found());
585 }
586 let lock = self.stop_lock(id).await;
589 let _guard = lock.lock().await;
590 let mut state_file = self.state_file.lock().await;
591 let exists = state_file.daemons.contains_key(id) || config.daemons.contains_key(id);
592 if !exists {
593 return Err(not_found());
594 }
595 let result = state_file.disable_daemon(id);
596 self.cancel_retrying(id);
599 Ok(result)
600 }
601
602 pub(crate) async fn get_daemon(&self, id: &DaemonId) -> Option<Daemon> {
604 self.state_file.lock().await.daemons.get(id).cloned()
605 }
606
607 pub(crate) async fn active_daemons(&self) -> Vec<Daemon> {
609 let pitchfork_id = DaemonId::pitchfork();
610 self.state_file
611 .lock()
612 .await
613 .daemons
614 .values()
615 .filter(|d| d.pid.is_some() && d.id != pitchfork_id)
616 .cloned()
617 .collect()
618 }
619
620 pub(crate) async fn remove_daemon(&self, id: &DaemonId) -> Result<()> {
622 let mut state_file = self.state_file.lock().await;
623 state_file.remove_daemon(id);
624 Ok(())
625 }
626
627 pub(crate) async fn set_shell_dir(&self, shell_pid: u32, dir: PathBuf) -> Result<()> {
629 let mut state_file = self.state_file.lock().await;
630 state_file.set_shell_dir(shell_pid, dir);
631 Ok(())
632 }
633
634 pub(crate) async fn get_shell_dir(&self, shell_pid: u32) -> Option<PathBuf> {
636 self.state_file
637 .lock()
638 .await
639 .shell_dirs
640 .get(&shell_pid.to_string())
641 .cloned()
642 }
643
644 #[cfg(unix)]
646 pub(crate) async fn remove_shell_pid(&self, shell_pid: u32) -> Result<()> {
647 let mut state_file = self.state_file.lock().await;
648 state_file.remove_shell_dir(shell_pid);
649 Ok(())
650 }
651
652 pub(crate) async fn get_dirs_with_shell_pids(&self) -> HashMap<PathBuf, Vec<u32>> {
654 self.state_file.lock().await.shell_dirs.iter().fold(
655 HashMap::new(),
656 |mut acc, (pid, dir)| {
657 if let Ok(pid) = pid.parse() {
658 acc.entry(dir.clone()).or_default().push(pid);
659 }
660 acc
661 },
662 )
663 }
664
665 pub(crate) async fn get_notifications(&self) -> Vec<(log::LevelFilter, String)> {
667 self.pending_notifications.lock().await.drain(..).collect()
668 }
669
670 pub(crate) async fn clean(&self) -> Result<()> {
672 self.clean_filtered(&[], &[], false).await?;
673 Ok(())
674 }
675
676 pub(crate) async fn clean_filtered(
678 &self,
679 namespaces: &[String],
680 daemons: &[DaemonId],
681 prune: bool,
682 ) -> Result<u64> {
683 if prune {
684 let candidates: Vec<(DaemonId, PathBuf)> = {
685 let state_file = self.state_file.lock().await;
686 state_file
687 .daemons
688 .iter()
689 .filter_map(|(id, daemon)| prune_candidate(id, daemon, namespaces, daemons))
690 .collect()
691 };
692
693 let mut missing = HashMap::new();
694 for (id, dir) in candidates {
695 match tokio::fs::try_exists(&dir).await {
696 Ok(false) => {
697 missing.insert(id, dir);
698 }
699 Ok(true) => {}
700 Err(e) => warn!("cannot check {} to prune {id}: {e}", dir.display()),
702 }
703 }
704
705 let mut removed = 0;
706 let mut state_file = self.state_file.lock().await;
707 state_file.retain_daemons(|id, daemon| {
708 let remove = should_clean_daemon(id, daemon, namespaces, daemons)
709 && missing
710 .get(id)
711 .is_some_and(|missing_dir| daemon.dir.as_ref() == Some(missing_dir));
712 removed += u64::from(remove);
713 !remove
714 });
715 return Ok(removed);
716 }
717
718 let mut removed = 0;
719 let mut state_file = self.state_file.lock().await;
720 state_file.retain_daemons(|id, daemon| {
721 let remove = should_clean_daemon(id, daemon, namespaces, daemons);
722 removed += u64::from(remove);
723 !remove
724 });
725 Ok(removed)
726 }
727
728 pub(crate) async fn get_active_directories(&self) -> Vec<PathBuf> {
732 self.state_file.lock().await.active_directories()
733 }
734
735 pub(crate) async fn get_liveness_sessions(&self) -> Vec<(u32, PathBuf, Option<String>)> {
739 self.state_file
740 .lock()
741 .await
742 .iter_project_sessions()
743 .into_iter()
744 .filter_map(|(pid_str, dir, session)| {
745 pid_str
746 .parse()
747 .ok()
748 .map(|pid| (pid, dir.clone(), session.liveness_title.clone()))
749 })
750 .collect()
751 }
752
753 pub(crate) async fn get_project_sessions_info(&self) -> Vec<crate::ipc::ProjectSessionInfo> {
757 let sessions: Vec<(u32, PathBuf, Option<String>)> = self
758 .state_file
759 .lock()
760 .await
761 .iter_project_sessions()
762 .into_iter()
763 .filter_map(|(pid_str, dir, session)| {
764 pid_str
765 .parse()
766 .ok()
767 .map(|pid| (pid, dir.clone(), session.liveness_title.clone()))
768 })
769 .collect();
770 let pids: Vec<u32> = sessions.iter().map(|(pid, _, _)| *pid).collect();
771 if !pids.is_empty() {
772 PROCS.refresh_pids(&pids);
773 }
774 sessions
775 .into_iter()
776 .map(
777 |(pid, directory, liveness_title)| crate::ipc::ProjectSessionInfo {
778 pid,
779 directory,
780 liveness_title,
781 alive: PROCS.is_running(pid),
782 current_title: PROCS.title(pid),
783 },
784 )
785 .collect()
786 }
787
788 pub(crate) async fn enter_project_session(
792 &self,
793 pid: u32,
794 dir: PathBuf,
795 ) -> Result<Option<crate::state_file::ProjectSession>> {
796 if pid == 0 {
797 return Err(miette::miette!("invalid host PID 0"));
798 }
799 if pid > i32::MAX as u32 {
800 return Err(miette::miette!("host PID {pid} exceeds i32::MAX"));
801 }
802 PROCS.refresh_pids(&[pid]);
803 let liveness_title = PROCS.title(pid);
804 #[cfg(unix)]
810 if !PROCS.is_running(pid) {
811 return Err(miette::miette!("host PID {pid} is not running"));
812 }
813 let mut state_file = self.state_file.lock().await;
814 let previous = state_file.set_project_session(
815 pid,
816 dir,
817 crate::state_file::ProjectSession { liveness_title },
818 );
819 Ok(previous)
820 }
821
822 pub(crate) async fn leave_project_session(
826 &self,
827 pid: u32,
828 dir: &std::path::Path,
829 ) -> Result<Option<PathBuf>> {
830 let mut state_file = self.state_file.lock().await;
831 if state_file.remove_project_session(pid, dir).is_some() {
832 Ok(Some(dir.to_path_buf()))
833 } else {
834 Ok(None)
835 }
836 }
837}
838
839#[cfg(test)]
840mod tests {
841 use super::*;
842
843 fn daemon(id: &DaemonId, pid: Option<u32>, dir: Option<PathBuf>) -> Daemon {
844 Daemon {
845 id: id.clone(),
846 pid,
847 dir,
848 ..Daemon::default()
849 }
850 }
851
852 #[test]
853 fn clean_filters_intersect_and_preserve_running_daemons() {
854 let api = DaemonId::new("project-a", "api");
855 let worker = DaemonId::new("project-a", "worker");
856 let namespaces = vec!["project-a".to_string()];
857 let daemons = vec![api.clone()];
858
859 assert!(should_clean_daemon(
860 &api,
861 &daemon(&api, None, None),
862 &namespaces,
863 &daemons,
864 ));
865 assert!(!should_clean_daemon(
866 &worker,
867 &daemon(&worker, None, None),
868 &namespaces,
869 &daemons,
870 ));
871 assert!(!should_clean_daemon(
872 &api,
873 &daemon(&api, Some(42), None),
874 &namespaces,
875 &daemons,
876 ));
877 }
878
879 #[test]
880 fn prune_candidates_require_a_recorded_directory() {
881 let id = DaemonId::new("project-a", "api");
882 assert!(prune_candidate(&id, &daemon(&id, None, None), &[], &[]).is_none());
883 assert_eq!(
884 prune_candidate(
885 &id,
886 &daemon(&id, None, Some(PathBuf::from("missing"))),
887 &[],
888 &[]
889 ),
890 Some((id, PathBuf::from("missing")))
891 );
892 }
893}