Skip to main content

cortexkit_bus_testkit/
daemon.rs

1use crate::{process::Process, BusServer, Module, RigError};
2use sha2::{Digest, Sha256};
3use std::{
4    path::{Path, PathBuf},
5    process::{Command, Stdio},
6    time::{Duration, Instant},
7};
8use subc_control::{ClientControlRequest, ClientControlResponse};
9use subc_protocol::{Flags, Frame, FrameType, Priority};
10use subc_transport::{authenticate_client, connection_file, read_frame, write_frame};
11use tokio::{io::AsyncWriteExt, net::TcpStream, task::JoinHandle};
12
13pub struct DaemonOptions {
14    pub modules: Vec<Module>,
15    /// A 32-character lowercase hex id. None suppresses the fixture file.
16    /// The daemon version under test may itself mint an id when none exists.
17    pub machine_id: Option<String>,
18    pub startup_timeout: Duration,
19}
20
21impl Default for DaemonOptions {
22    fn default() -> Self {
23        Self {
24            modules: vec![],
25            machine_id: Some(new_machine_id()),
26            startup_timeout: Duration::from_secs(30),
27        }
28    }
29}
30
31pub fn new_machine_id() -> String {
32    let key = nkeys::KeyPair::new_user();
33    crate::signer::hex(&Sha256::digest(key.public_key().as_bytes())[..16])
34}
35
36/// Write the identity in the data home the binary daemon uses, not the caller's.
37pub fn write_machine_id(data_home: &Path, machine_id: &str) -> Result<PathBuf, RigError> {
38    if machine_id.len() != 32
39        || !machine_id
40            .bytes()
41            .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
42    {
43        return Err(RigError::Invalid(
44            "machine id must be 32 lowercase hex characters".into(),
45        ));
46    }
47    let path = data_home.join("cortexkit/machine-id");
48    std::fs::create_dir_all(path.parent().unwrap())?;
49    std::fs::write(&path, format!("{machine_id}\n"))?;
50    Ok(path)
51}
52
53/// A binary daemon and a throwaway, in-client-process claustrum signer.
54/// The broker must outlive this value. No operator vault or installed daemon is used.
55pub struct PrivateDaemon {
56    child: Option<Process>,
57    signer: Option<JoinHandle<Result<(), subc_client_rs::SubcModuleError>>>,
58    root: tempfile::TempDir,
59    pub connection_file: PathBuf,
60    pub config_file: PathBuf,
61    pub data_home: PathBuf,
62    pub runtime_dir: PathBuf,
63    pub config_home: PathBuf,
64    log: PathBuf,
65}
66
67impl PrivateDaemon {
68    pub async fn start(bus: &BusServer, options: DaemonOptions) -> Result<Self, RigError> {
69        // Resolve every required binary before creating state or starting a child.
70        let subc = crate::ck_subc_binary()?;
71        let ck_bus = crate::binaries::ck_bus_source()?;
72        let root = tempfile::tempdir()?;
73        let data_home = root.path().join("data");
74        let runtime_dir = root.path().join("run");
75        let config_home = root.path().join("config");
76        for dir in [&data_home, &runtime_dir, &config_home.join("cortexkit")] {
77            std::fs::create_dir_all(dir)?;
78        }
79        if let Some(machine_id) = &options.machine_id {
80            write_machine_id(&data_home, machine_id)?;
81        }
82        let config_file = config_home.join("cortexkit/subc.jsonc");
83        std::fs::write(
84            &config_file,
85            crate::subc_config(&ck_bus, &bus.ckbus_env(), &options.modules)?,
86        )?;
87        let connection_file = runtime_dir.join("subc-connection.json");
88        let log = root.path().join("daemon.log");
89        let output = std::fs::File::create(&log)?;
90        // Set homes on the child, never the test process. The daemon's orphan sweep
91        // must not inspect or signal processes recorded in the operator's data home.
92        let child = Process(
93            Command::new(subc)
94                .env("XDG_DATA_HOME", &data_home)
95                .env("XDG_RUNTIME_DIR", &runtime_dir)
96                .env("XDG_CONFIG_HOME", &config_home)
97                .env("SUBC_CGROUP_PLACEMENT", "disabled")
98                .env("SUBC_PORT", "0")
99                .stdin(Stdio::null())
100                .stdout(output.try_clone()?)
101                .stderr(output)
102                .spawn()?,
103        );
104        let mut daemon = Self {
105            child: Some(child),
106            signer: None,
107            root,
108            connection_file,
109            config_file,
110            data_home,
111            runtime_dir,
112            config_home,
113            log,
114        };
115        let deadline = Instant::now() + options.startup_timeout;
116        daemon.wait_connection(deadline).await?;
117        let signer = bus.trust.signer.clone();
118        let connection = daemon.connection_file.clone();
119        daemon.signer = Some(tokio::spawn(async move {
120            subc_client_rs::serve_with(&connection, signer.manifest(), signer).await
121        }));
122        loop {
123            daemon.check_child()?;
124            let response = tokio::time::timeout_at(
125                tokio::time::Instant::from_std(deadline),
126                daemon.control(ClientControlRequest::CatalogList {
127                    module_id: Some("ckbus".into()),
128                }),
129            )
130            .await;
131            if let Ok(Ok(ClientControlResponse::CatalogList { modules, .. })) = response {
132                if modules.iter().any(|module| module.module_id == "ckbus") {
133                    return Ok(daemon);
134                }
135            }
136            if Instant::now() >= deadline {
137                return Err(daemon.timeout("ckbus catalog registration"));
138            }
139            tokio::time::sleep(Duration::from_millis(50)).await;
140        }
141    }
142
143    async fn wait_connection(&mut self, deadline: Instant) -> Result<(), RigError> {
144        loop {
145            self.check_child()?;
146            if connection_file::read(&self.connection_file).is_ok() {
147                return Ok(());
148            }
149            if Instant::now() >= deadline {
150                return Err(self.timeout("private connection file"));
151            }
152            tokio::time::sleep(Duration::from_millis(50)).await;
153        }
154    }
155    fn check_child(&mut self) -> Result<(), RigError> {
156        if let Some(status) = self.child.as_mut().unwrap().0.try_wait()? {
157            return Err(RigError::Invalid(format!(
158                "ck-subc exited {status}: {}",
159                self.log_text()
160            )));
161        }
162        Ok(())
163    }
164    fn timeout(&self, waiting_for: &str) -> RigError {
165        RigError::Timeout {
166            waiting_for: waiting_for.into(),
167            details: format!(
168                "expected {}; {}",
169                self.connection_file.display(),
170                self.log_text()
171            ),
172        }
173    }
174    pub fn root(&self) -> &Path {
175        self.root.path()
176    }
177    pub fn pid(&self) -> u32 {
178        self.child.as_ref().unwrap().0.id()
179    }
180    pub fn log_text(&self) -> String {
181        let mut text = std::fs::read_to_string(&self.log).unwrap_or_default();
182        let mut directories = vec![self.data_home.join("cortexkit/run/logs")];
183        while let Some(directory) = directories.pop() {
184            let Ok(entries) = std::fs::read_dir(directory) else {
185                continue;
186            };
187            for entry in entries.filter_map(Result::ok) {
188                if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
189                    directories.push(entry.path());
190                } else {
191                    text.push_str(&format!(
192                        "\n{}:\n{}",
193                        entry.path().display(),
194                        std::fs::read_to_string(entry.path()).unwrap_or_default()
195                    ));
196                }
197            }
198        }
199        text
200    }
201
202    pub async fn control(
203        &self,
204        request: ClientControlRequest,
205    ) -> Result<ClientControlResponse, RigError> {
206        tokio::time::timeout(
207            Duration::from_secs(3),
208            control(&self.connection_file, request),
209        )
210        .await
211        .map_err(|_| self.timeout("daemon control response"))?
212    }
213}
214
215impl Drop for PrivateDaemon {
216    fn drop(&mut self) {
217        drop(self.child.take());
218        if let Some(signer) = self.signer.take() {
219            signer.abort();
220        }
221    }
222}
223
224async fn control(
225    path: &Path,
226    request: ClientControlRequest,
227) -> Result<ClientControlResponse, RigError> {
228    let connection =
229        connection_file::read(path).map_err(|error| RigError::Invalid(error.to_string()))?;
230    let endpoint = connection
231        .endpoints
232        .first()
233        .ok_or_else(|| RigError::Invalid("no daemon endpoint".into()))?;
234    let mut stream = TcpStream::connect((endpoint.host.as_str(), endpoint.port)).await?;
235    authenticate_client(&mut stream, &connection, Duration::from_secs(2))
236        .await
237        .map_err(|error| RigError::Invalid(error.to_string()))?;
238    let frame = Frame::build(
239        FrameType::Request,
240        Flags::new(false, Priority::Passive, false),
241        0,
242        0,
243        1,
244        serde_json::to_vec(&request).map_err(|error| RigError::Invalid(error.to_string()))?,
245    )
246    .map_err(|error| RigError::Invalid(error.to_string()))?;
247    write_frame(&mut stream, &frame)
248        .await
249        .map_err(|error| RigError::Invalid(error.to_string()))?;
250    stream.flush().await?;
251    let response = read_frame(&mut stream)
252        .await
253        .map_err(|error| RigError::Invalid(error.to_string()))?
254        .ok_or_else(|| RigError::Invalid("daemon closed control connection".into()))?;
255    if response.header.ty != FrameType::Response {
256        return Err(RigError::Invalid(format!(
257            "control refused: {}",
258            String::from_utf8_lossy(&response.body)
259        )));
260    }
261    serde_json::from_slice(&response.body).map_err(|error| RigError::Invalid(error.to_string()))
262}