use std::path::{Path, PathBuf};
use std::time::Duration;
use tokio::sync::oneshot;
use crate::AppState;
pub struct TestDaemon {
socket: PathBuf,
state: AppState,
stop: Option<oneshot::Sender<()>>,
}
impl TestDaemon {
pub async fn start() -> Self {
Self::start_with(new_test_state()).await
}
pub async fn start_with(state: AppState) -> Self {
let tmp = tempfile::tempdir().expect("tempdir for the test socket");
let socket = tmp.path().join("sockets").join("trusty-memory.sock");
std::mem::forget(tmp);
let (stop, shutdown) = oneshot::channel::<()>();
let serve_socket = socket.clone();
let serve_state = state.clone();
tokio::spawn(async move {
let _ = crate::transport::uds::serve_with_shutdown(serve_state, &serve_socket, async {
let _ = shutdown.await;
})
.await;
});
for _ in 0..200 {
if trusty_common::uds::socket_is_serving(&socket, Duration::from_millis(200)).await {
break;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
Self {
socket,
state,
stop: Some(stop),
}
}
pub fn socket(&self) -> &Path {
&self.socket
}
pub fn state(&self) -> &AppState {
&self.state
}
}
impl Drop for TestDaemon {
fn drop(&mut self) {
if let Some(stop) = self.stop.take() {
let _ = stop.send(());
}
}
}
pub fn new_test_state() -> AppState {
trusty_common::memory_core::retrieval::seed_shared_embedder_with_mock();
let tmp = tempfile::tempdir().expect("tempdir for the test data root");
let root = tmp.path().to_path_buf();
std::mem::forget(tmp);
unsafe {
std::env::set_var("TRUSTY_SKIP_PALACE_ENFORCEMENT", "1");
}
let state = AppState::new(root);
state.set_ready();
state
}