use std::path::PathBuf;
use crate::connector::{ServiceConnector, ServiceInfo};
use super::helpers::detect_service;
pub struct SearchConnector {
home_dir: Option<PathBuf>,
}
impl SearchConnector {
pub fn new() -> Self {
Self { home_dir: None }
}
#[cfg(test)]
pub fn with_home(home_dir: PathBuf) -> Self {
Self {
home_dir: Some(home_dir),
}
}
fn addr_file_path(&self) -> PathBuf {
let home = self
.home_dir
.clone()
.or_else(dirs::home_dir)
.unwrap_or_else(|| PathBuf::from("/tmp"));
home.join(".trusty-search").join("http_addr")
}
}
impl Default for SearchConnector {
fn default() -> Self {
Self::new()
}
}
impl ServiceConnector for SearchConnector {
fn id(&self) -> &'static str {
"trusty-search"
}
fn display_name(&self) -> &'static str {
"Trusty Search"
}
fn detect(&self) -> ServiceInfo {
detect_service(
self.id(),
self.display_name(),
"trusty-search",
self.addr_file_path(),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::connector::ServiceStatus;
use std::fs;
use tempfile::TempDir;
fn make_home_with_addr(rel_path: &str, content: &str) -> TempDir {
let tmp = TempDir::new().expect("tempdir");
let path = tmp.path().join(rel_path);
fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
fs::write(&path, content).expect("write addr file");
tmp
}
#[test]
fn test_search_connector_with_stale_addr_file() {
let tmp = make_home_with_addr(".trusty-search/http_addr", "127.0.0.1:14998");
let connector = SearchConnector::with_home(tmp.path().to_path_buf());
let info = connector.detect();
assert!(
info.status == ServiceStatus::Absent || info.status == ServiceStatus::Available,
"expected Absent or Available, got {:?}",
info.status
);
assert_eq!(info.id, "trusty-search");
assert_eq!(info.display_name, "Trusty Search");
}
#[test]
fn test_search_connector_no_addr_file() {
let tmp = TempDir::new().expect("tempdir");
let connector = SearchConnector::with_home(tmp.path().to_path_buf());
let info = connector.detect();
assert!(
info.status == ServiceStatus::Absent || info.status == ServiceStatus::Available,
"expected Absent or Available, got {:?}",
info.status
);
assert!(info.url.is_none());
}
}