Skip to main content

running_process/cleanup/
instances.rs

1#[cfg(unix)]
2use std::path::PathBuf;
3
4/// One broker instance discovered from the local pipe namespace.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct BrokerInstance {
7    /// Filesystem path or named pipe string.
8    pub path: String,
9}
10
11/// Enumerate broker v1 instances visible to the current user.
12pub fn list() -> Vec<BrokerInstance> {
13    #[cfg(unix)]
14    {
15        unix_instance_dirs()
16            .into_iter()
17            .flat_map(|dir| {
18                std::fs::read_dir(dir)
19                    .into_iter()
20                    .flat_map(|rd| rd.flatten())
21                    .filter_map(|entry| {
22                        let path = entry.path();
23                        let name = path.file_name()?.to_string_lossy();
24                        if name.starts_with("rpb-v1-") && name.ends_with(".sock") {
25                            Some(BrokerInstance {
26                                path: path.to_string_lossy().into_owned(),
27                            })
28                        } else {
29                            None
30                        }
31                    })
32                    .collect::<Vec<_>>()
33            })
34            .collect()
35    }
36    #[cfg(windows)]
37    {
38        // Windows named-pipe namespace enumeration lands with the
39        // broker binary in Phase 4. Phase 2 keeps the command stable
40        // and returns an empty list when no broker is required.
41        Vec::new()
42    }
43}
44
45/// Render `running-process-cleanup instances --json`.
46pub fn render_json(instances: &[BrokerInstance]) -> String {
47    let body = instances
48        .iter()
49        .map(|instance| {
50            format!(
51                "{{\"path\":\"{}\"}}",
52                crate::cleanup::json_escape(&instance.path)
53            )
54        })
55        .collect::<Vec<_>>()
56        .join(",");
57    format!("{{\"schema_version\":1,\"instances\":[{body}]}}")
58}
59
60#[cfg(unix)]
61fn unix_instance_dirs() -> Vec<PathBuf> {
62    let mut dirs = Vec::new();
63    if let Some(runtime) = std::env::var_os("XDG_RUNTIME_DIR") {
64        dirs.push(
65            PathBuf::from(runtime)
66                .join("running-process")
67                .join("broker"),
68        );
69    }
70    dirs.push(std::env::temp_dir());
71    dirs
72}