use crate::gateway_cli::SERVICE_NAME;
use eclipse_core::config::{self, Config, EnvFn, Where};
use eclipse_core::cron;
use std::net::{TcpStream, ToSocketAddrs};
use std::path::PathBuf;
use std::time::Duration;
const PORT_TIMEOUT: Duration = Duration::from_millis(400);
pub struct Platform {
pub name: &'static str,
pub transport: &'static str,
pub state: &'static str,
pub carried: u64,
}
pub const PLATFORMS: &[Platform] = &[];
pub trait Host {
fn show(&self) -> Option<String>;
fn uptime_secs(&self) -> Option<f64>;
fn answers(&self, host: &str, port: u16) -> bool;
}
pub struct System;
impl Host for System {
fn show(&self) -> Option<String> {
let out = std::process::Command::new("systemctl")
.args([
"--user",
"show",
SERVICE_NAME,
"--no-pager",
"--property=ActiveState",
"--property=ActiveEnterTimestampMonotonic",
"--property=ExecMainPID",
])
.output()
.ok()?;
Some(String::from_utf8_lossy(&out.stdout).into_owned())
}
fn uptime_secs(&self) -> Option<f64> {
let text = std::fs::read_to_string("/proc/uptime").ok()?;
text.split_whitespace().next()?.parse().ok()
}
fn answers(&self, host: &str, port: u16) -> bool {
connect(host, port, PORT_TIMEOUT)
}
}
fn connect(host: &str, port: u16, budget: Duration) -> bool {
let Ok(mut found) = (host, port).to_socket_addrs() else {
return false;
};
match found.next() {
Some(addr) => TcpStream::connect_timeout(&addr, budget).is_ok(),
None => false,
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct Shown {
pub state: String,
pub pid: Option<u32>,
pub entered_us: Option<u64>,
}
pub fn parse_show(text: &str) -> Shown {
let mut shown = Shown::default();
for line in text.lines() {
let Some((key, value)) = line.split_once('=') else {
continue;
};
let value = value.trim();
match key.trim() {
"ActiveState" => shown.state = value.to_string(),
"ActiveEnterTimestampMonotonic" => {
shown.entered_us = value.parse::<u64>().ok().filter(|us| *us > 0)
}
"ExecMainPID" => shown.pid = value.parse::<u32>().ok().filter(|pid| *pid > 0),
_ => {}
}
}
shown
}
pub fn unit_env(text: &str) -> (Option<String>, Option<PathBuf>) {
let (mut profile, mut config) = (None, None);
for line in text.lines() {
let Some(rest) = line.trim().strip_prefix("Environment=") else {
continue;
};
let word = rest.trim().trim_matches('"');
let Some((key, value)) = word.split_once('=') else {
continue;
};
match key {
"ECLIPSE_PROFILE" if !value.is_empty() => profile = Some(value.to_string()),
"ECLIPSE_CONFIG" if !value.is_empty() => config = Some(PathBuf::from(value)),
_ => {}
}
}
(profile, config)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Unit {
Active {
age: Option<Duration>,
pid: Option<u32>,
},
Inactive(String),
NotInstalled(PathBuf),
Unknown(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Endpoint {
pub host: String,
pub port: u16,
pub answers: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Newest {
pub job: String,
pub outcome: String,
pub at_ms: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Jobs {
pub total: usize,
pub enabled: usize,
pub newest: Option<Newest>,
pub trouble: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Serves {
pub profile: Option<String>,
pub config: Option<PathBuf>,
pub reads: Option<PathBuf>,
pub unit: Option<PathBuf>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Snapshot {
pub unit: Unit,
pub endpoint: Option<Endpoint>,
pub endpoint_trouble: Option<String>,
pub jobs: Jobs,
pub serves: Serves,
}
pub fn probe(host: &dyn Host, env: EnvFn, here: Option<&Where>) -> Snapshot {
let unit_path = env("HOME")
.filter(|home| !home.is_empty())
.map(|home| crate::gateway_cli::unit_path(std::path::Path::new(&home)));
let text = unit_path
.as_ref()
.and_then(|path| std::fs::read_to_string(path).ok());
let installed = unit_path.clone().filter(|_| text.is_some());
let (unit_profile, config) = text.as_deref().map(unit_env).unwrap_or((None, None));
let profile = match installed {
Some(_) => unit_profile,
None => unit_profile.or_else(|| here.and_then(|place| place.profile.clone())),
};
let reads = config
.clone()
.or_else(|| {
installed
.is_none()
.then(|| here.and_then(|place| place.config.clone()))
.flatten()
})
.or_else(|| config::config_path(env))
.filter(|path| path.exists());
let serves = Serves {
profile,
config,
reads,
unit: installed,
};
let shown = host.show();
let unit = match (shown.as_deref().map(parse_show), &unit_path) {
(Some(shown), _) if shown.state == "active" => Unit::Active {
age: shown
.entered_us
.zip(host.uptime_secs())
.and_then(|(entered_us, uptime)| {
let seconds = uptime - entered_us as f64 / 1_000_000.0;
(seconds >= 0.0).then(|| Duration::from_secs(seconds as u64))
}),
pid: shown.pid,
},
(_, Some(path)) if !path.exists() => Unit::NotInstalled(path.clone()),
(Some(shown), _) => Unit::Inactive(shown.state),
(None, _) => Unit::Unknown(
"systemctl did not answer — systemd may not be running for this user".to_string(),
),
};
let (endpoint, endpoint_trouble) = match &serves.reads {
None => (
None,
Some("no config file to read the port from".to_string()),
),
Some(path) => match Config::load_with_profile(Some(path), serves.profile.as_deref(), env) {
Ok(cfg) => {
let (host_name, port) = (cfg.web.host.clone(), cfg.web.port);
let answers = host.answers(&host_name, port);
(
Some(Endpoint {
host: host_name,
port,
answers,
}),
None,
)
}
Err(why) => (None, Some(format!("{}: {why}", path.display()))),
},
};
Snapshot {
unit,
endpoint,
endpoint_trouble,
jobs: jobs(env),
serves,
}
}
fn jobs(env: EnvFn) -> Jobs {
let Some(root) = config::home_root(env) else {
return Jobs {
total: 0,
enabled: 0,
newest: None,
trouble: Some("HOME is not set, so there is no cron root".to_string()),
};
};
match cron::views(&root, eclipse_core::session::now_ms() as i64) {
Ok(views) => {
let newest = views
.iter()
.filter_map(|view| view.last_started_ms.map(|at| (at, view)))
.max_by_key(|(at, _)| *at)
.map(|(at, view)| Newest {
job: view.name.clone(),
outcome: match (&view.last_outcome, view.last_finished_ms) {
(_, Some(finished)) if finished >= at => view
.last_outcome
.clone()
.unwrap_or_else(|| "no outcome recorded".to_string()),
_ => "running".to_string(),
},
at_ms: at,
});
Jobs {
total: views.len(),
enabled: views.iter().filter(|view| view.enabled).count(),
newest,
trouble: None,
}
}
Err(why) => Jobs {
total: 0,
enabled: 0,
newest: None,
trouble: Some(why.to_string()),
},
}
}
pub fn text(snapshot: &Snapshot, here: Option<&Where>) -> String {
let mut out = String::new();
out.push_str(&headline(&snapshot.unit));
out.push('\n');
out.push_str(&format!(" up for {}\n", age_word(&snapshot.unit)));
if let Unit::Active { pid: Some(pid), .. } = &snapshot.unit {
out.push_str(&format!(" pid {pid}\n"));
}
match (&snapshot.endpoint, &snapshot.endpoint_trouble) {
(Some(endpoint), _) => {
let verdict = match (endpoint.answers, &snapshot.unit) {
(true, Unit::Active { .. }) => "answers".to_string(),
(true, _) => "answers (the unit is not active)".to_string(),
(false, _) => "down".to_string(),
};
out.push_str(&format!(
" port {}:{} — {verdict}\n",
endpoint.host, endpoint.port
))
}
(None, Some(why)) => out.push_str(&format!(" port unknown — {why}\n")),
(None, None) => out.push_str(" port unknown\n"),
}
out.push_str(&format!(" jobs {}\n", jobs_line(&snapshot.jobs)));
out.push_str(&format!(
" serves {}\n",
serves_line(&snapshot.serves, here)
));
out.push_str(&format!(" fix {}\n", fix_line(&snapshot.unit)));
out
}
pub fn platforms(snapshot: &Snapshot, here: Option<&Where>) -> String {
let mut out = text(snapshot, here);
out.push('\n');
if PLATFORMS.is_empty() {
out.push_str("platforms: none configured\n");
out.push_str(
" the gateway carries the dashboard API and the scheduler; no messaging front end is \
attached to it\n",
);
out.push_str(
" a platform would be one row here: name · transport · state · requests carried\n",
);
return out;
}
out.push_str("platforms:\n");
for platform in PLATFORMS {
out.push_str(&format!(
" {} · {} · {} · {} requests carried\n",
platform.name, platform.transport, platform.state, platform.carried
));
}
out
}
fn headline(unit: &Unit) -> String {
match unit {
Unit::Active { .. } => "gateway: up".to_string(),
Unit::Inactive(word) => format!("gateway: down ({word})"),
Unit::NotInstalled(path) => format!("gateway: not installed — {}", path.display()),
Unit::Unknown(why) => format!("gateway: unknown — {why}"),
}
}
fn age_word(unit: &Unit) -> String {
match unit {
Unit::Active {
age: Some(age),
pid: _,
} => span(*age),
Unit::Active { age: None, .. } => "unknown".to_string(),
Unit::Inactive(_) | Unit::NotInstalled(_) => "down".to_string(),
Unit::Unknown(_) => "unknown".to_string(),
}
}
fn span(age: Duration) -> String {
let secs = age.as_secs();
let (days, hours, minutes) = (secs / 86_400, (secs % 86_400) / 3_600, (secs % 3_600) / 60);
if days > 0 {
format!("{days} d {hours} h")
} else if hours > 0 {
format!("{hours} h {minutes} m")
} else if minutes > 0 {
format!("{minutes} m")
} else {
format!("{secs} s")
}
}
fn jobs_line(jobs: &Jobs) -> String {
if let Some(why) = &jobs.trouble {
return format!("could not be read — {why}");
}
if jobs.total == 0 {
return "none scheduled — `eclipse cron add` writes the first".to_string();
}
let mut out = format!("{} scheduled, {} enabled", jobs.total, jobs.enabled);
match &jobs.newest {
Some(newest) => out.push_str(&format!(
" · newest run {}: {}, {}",
newest.job,
newest.outcome,
cron::iso_local(newest.at_ms)
)),
None => out.push_str(" · nothing has run yet"),
}
out
}
fn serves_line(serves: &Serves, here: Option<&Where>) -> String {
let reads = match &serves.reads {
Some(path) => path.display().to_string(),
None => return "nothing to read: no unit file and no config".to_string(),
};
let profile = serves.profile.as_deref().unwrap_or("default");
let name = if serves.profile.is_some() {
format!("profile {profile}")
} else {
"the default profile".to_string()
};
if serves.unit.is_none() {
return format!(
"{name}, reading {reads} — no unit was read: this is what this session would serve"
);
}
let Some(place) = here else {
return format!("{name}, reading {reads} — this session read no config file to compare");
};
let mine = place.profile.as_deref();
let my_config = place.config.as_deref();
let my_reads = my_config.map(|path| path.display().to_string());
let same_profile = profile == mine.unwrap_or("default");
let same_config = my_reads.as_deref() == Some(reads.as_str());
let this_file = match &my_reads {
Some(path) if *path != reads => format!(", reading {path}"),
Some(_) => String::new(),
None => ", reading no config file".to_string(),
};
let tail = match (same_profile, same_config) {
(true, true) => "this session's own".to_string(),
(true, false) => format!(
"same profile, another config file (this session reads {})",
my_reads.as_deref().unwrap_or("the default one")
),
(false, _) => format!(
"not this session's (this one is {}{this_file})",
mine.unwrap_or("default")
),
};
format!("{name}, reading {reads} — {tail}")
}
fn fix_line(unit: &Unit) -> String {
match unit {
Unit::Active { .. } => {
"read-only — `eclipse gateway start|stop|restart` are the verbs that change it"
.to_string()
}
Unit::Inactive(_) => "eclipse gateway start".to_string(),
Unit::NotInstalled(_) => "eclipse gateway install".to_string(),
Unit::Unknown(_) => "eclipse gateway status".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::Path;
use std::time::Instant;
struct Fake {
show: Option<String>,
uptime: Option<f64>,
listening: Option<u16>,
}
impl Fake {
fn down() -> Self {
Fake {
show: Some("ActiveState=inactive\nExecMainPID=0\n".into()),
uptime: Some(500.0),
listening: None,
}
}
}
impl Host for Fake {
fn show(&self) -> Option<String> {
self.show.clone()
}
fn uptime_secs(&self) -> Option<f64> {
self.uptime
}
fn answers(&self, _host: &str, port: u16) -> bool {
self.listening == Some(port)
}
}
fn env_with(home: &Path) -> impl Fn(&str) -> Option<String> + '_ {
move |key: &str| match key {
"HOME" => Some(home.display().to_string()),
_ => None,
}
}
fn install(home: &Path, port: u16) -> PathBuf {
let root = home.join(".eclipse");
std::fs::create_dir_all(root.join("config")).unwrap();
std::fs::write(root.join("config.toml"), format!("[web]\nport = {port}\n")).unwrap();
root
}
fn write_unit(home: &Path, body: &str) -> PathBuf {
let dir = home.join(".config/systemd/user");
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join(SERVICE_NAME);
std::fs::write(&path, body).unwrap();
path
}
fn place(profile: Option<&str>, config: &Path) -> Where {
Where {
profile: profile.map(str::to_string),
config: Some(config.to_path_buf()),
overlay: None,
home: None,
sessions: None,
}
}
#[test]
fn a_unit_that_is_up_reports_its_age_pid_port_and_jobs() {
let home = tempfile::tempdir().unwrap();
let cfg = install(home.path(), 8787);
std::fs::write(cfg.join("config.toml"), "[web]\nport = 8787\n").unwrap();
let unit = write_unit(
home.path(),
&format!(
"[Service]\nEnvironment=\"ECLIPSE_CONFIG={}\"\n",
cfg.join("config.toml").display()
),
);
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let shown = format!(
"ActiveState=active\nActiveEnterTimestampMonotonic={}\nExecMainPID=4242\n",
0
);
let snapshot = probe(
&Fake {
show: Some(shown),
uptime: Some(1000.0),
listening: None,
},
env_fn,
None,
);
let text = text(&snapshot, None);
assert!(text.starts_with("gateway: up\n"), "{text}");
assert!(text.contains(" pid 4242\n"), "{text}");
assert!(
text.contains(" port 127.0.0.1:8787 — down\n"),
"{text}"
);
assert!(
text.contains("none scheduled"),
"an empty cron root says so: {text}"
);
assert!(
text.contains(&format!("reading {}", cfg.join("config.toml").display())),
"the config the unit names is the one the port came from: {text}"
);
assert!(unit.exists());
}
#[test]
fn the_age_is_the_boot_clock_minus_the_units_own_start() {
let home = tempfile::tempdir().unwrap();
install(home.path(), 8787);
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let snapshot = probe(
&Fake {
show: Some("ActiveState=active\nActiveEnterTimestampMonotonic=252000000\n".into()),
uptime: Some(10_000.0),
listening: None,
},
env_fn,
None,
);
assert!(
text(&snapshot, None).contains(" up for 2 h 42 m\n"),
"{}",
text(&snapshot, None)
);
let confused = probe(
&Fake {
show: Some("ActiveState=active\nActiveEnterTimestampMonotonic=99000000\n".into()),
uptime: Some(1.0),
listening: None,
},
env_fn,
None,
);
assert_eq!(age_word(&confused.unit), "unknown");
}
#[test]
fn a_gateway_that_is_down_says_down_for_the_state_the_age_and_the_port() {
let home = tempfile::tempdir().unwrap();
install(home.path(), 8787);
write_unit(
home.path(),
"[Service]\nExecStart=/usr/bin/eclipse-gateway\n",
);
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let snapshot = probe(&Fake::down(), env_fn, None);
let text = text(&snapshot, None);
assert!(text.contains("gateway: down (inactive)"), "{text}");
assert!(text.contains(" up for down\n"), "{text}");
assert!(
text.contains(" port 127.0.0.1:8787 — down\n"),
"{text}"
);
assert!(text.contains(" fix eclipse gateway start"), "{text}");
}
#[test]
fn a_port_that_answers_under_an_inactive_unit_says_which_it_is() {
let home = tempfile::tempdir().unwrap();
let root = install(home.path(), 8787);
write_unit(
home.path(),
"[Service]\nExecStart=/usr/bin/eclipse-gateway\n",
);
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let snapshot = probe(
&Fake {
show: Some("ActiveState=inactive\n".into()),
uptime: Some(500.0),
listening: Some(8787),
},
env_fn,
None,
);
let said = text(&snapshot, None);
assert!(said.contains("gateway: down (inactive)"), "{said}");
assert!(
said.contains(" port 127.0.0.1:8787 — answers (the unit is not active)"),
"{said}"
);
let up = probe(
&Fake {
show: Some("ActiveState=active\nActiveEnterTimestampMonotonic=0\n".into()),
uptime: Some(500.0),
listening: Some(8787),
},
env_fn,
None,
);
assert!(
text(&up, None).contains(" port 127.0.0.1:8787 — answers\n"),
"{}",
text(&up, None)
);
assert!(root.join("config.toml").exists());
}
#[test]
fn with_no_unit_installed_the_profile_reported_is_the_one_this_session_would_serve() {
let home = tempfile::tempdir().unwrap();
let root = install(home.path(), 8787);
std::fs::create_dir_all(root.join("profiles/lab")).unwrap();
let overlay = root.join("profiles/lab/config.toml");
std::fs::write(&overlay, "[web]\nport = 9099\n").unwrap();
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let mine = place(Some("lab"), &root.join("config.toml"));
let said = text(&probe(&Fake::down(), env_fn, Some(&mine)), Some(&mine));
assert!(
said.contains("profile lab, reading "),
"the overlay's profile, not the default: {said}"
);
assert!(
said.contains("no unit was read: this is what this session would serve"),
"{said}"
);
assert!(said.contains("127.0.0.1:9099 — down"), "{said}");
}
#[test]
fn a_port_nothing_listens_on_is_answered_fast() {
let free = {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
port
};
let home = tempfile::tempdir().unwrap();
install(home.path(), free);
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let started = Instant::now();
let snapshot = probe(&Fake::down(), env_fn, None);
let took = started.elapsed();
assert!(
took < Duration::from_millis(500),
"a dead gateway must not make the composer pause: {took:?}"
);
assert_eq!(
snapshot.endpoint.as_ref().map(|e| e.answers),
Some(false),
"nothing is listening on {free}"
);
assert!(
text(&snapshot, None).contains(&format!("127.0.0.1:{free} — down")),
"{}",
text(&snapshot, None)
);
}
#[test]
fn a_unit_installed_for_another_profile_is_not_reported_as_this_sessions() {
let home = tempfile::tempdir().unwrap();
let cfg = install(home.path(), 8787);
write_unit(
home.path(),
&format!(
"[Service]\nEnvironment=\"ECLIPSE_PROFILE=work\"\nEnvironment=\"ECLIPSE_CONFIG={}\"\n",
cfg.join("config.toml").display()
),
);
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let mine = cfg.join("config.toml");
let snapshot = probe(&Fake::down(), env_fn, None);
let other = text(&snapshot, Some(&place(None, &mine)));
assert!(
other.contains("profile work")
&& other.contains("not this session's (this one is default"),
"{other}"
);
let same = text(&snapshot, Some(&place(Some("work"), &mine)));
assert!(same.contains("this session's own"), "{same}");
let elsewhere = text(
&snapshot,
Some(&place(Some("work"), Path::new("/tmp/other.toml"))),
);
assert!(
elsewhere.contains("same profile, another config file"),
"{elsewhere}"
);
assert!(elsewhere.contains("/tmp/other.toml"), "{elsewhere}");
}
#[test]
fn no_unit_is_named_as_not_installed_with_the_file_and_the_command_that_writes_it() {
let home = tempfile::tempdir().unwrap();
install(home.path(), 8787);
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let snapshot = probe(&Fake::down(), env_fn, None);
let text = text(&snapshot, None);
assert!(text.contains("gateway: not installed"), "{text}");
assert!(text.contains(SERVICE_NAME), "{text}");
assert!(text.contains("fix eclipse gateway install"), "{text}");
assert!(text.contains("no unit was read"), "{text}");
}
#[test]
fn a_jobs_file_that_does_not_parse_is_reported_instead_of_counted_as_zero() {
let home = tempfile::tempdir().unwrap();
let root = install(home.path(), 8787);
std::fs::create_dir_all(root.join("cron")).unwrap();
std::fs::write(root.join("cron/jobs.toml"), "this is not toml [[[").unwrap();
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let snapshot = probe(&Fake::down(), env_fn, None);
assert!(snapshot.jobs.trouble.is_some(), "{:?}", snapshot.jobs);
let text = text(&snapshot, None);
assert!(
text.contains("could not be read") && !text.contains("none scheduled"),
"{text}"
);
}
#[test]
fn the_job_count_and_the_newest_outcome_come_from_the_store() {
let home = tempfile::tempdir().unwrap();
let root = install(home.path(), 8787);
std::fs::create_dir_all(root.join("cron")).unwrap();
std::fs::write(
root.join("cron/jobs.toml"),
"[[job]]\nname = \"brief\"\nschedule = \"daily 07:30\"\nprompt = \"say good morning\"\n\
\n[[job]]\nname = \"sweep\"\nschedule = \"hourly\"\nprompt = \"sweep\"\nenabled = false\n",
)
.unwrap();
std::fs::create_dir_all(root.join("state")).unwrap();
std::fs::write(
root.join("state/cron.json"),
r#"{"jobs": {"brief": {"runs": 2, "last_started_ms": 1000, "last_finished_ms": 1100, "last_outcome": "ok"}}}"#,
)
.unwrap();
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let snapshot = probe(&Fake::down(), env_fn, None);
assert_eq!(snapshot.jobs.total, 2);
assert_eq!(snapshot.jobs.enabled, 1, "one job is switched off");
let newest = snapshot.jobs.newest.clone().expect("brief has run");
assert_eq!(newest.job, "brief");
assert_eq!(newest.outcome, "ok");
let line = jobs_line(&snapshot.jobs);
assert!(line.contains("2 scheduled, 1 enabled"), "{line}");
assert!(line.contains("newest run brief: ok"), "{line}");
std::fs::write(
root.join("state/cron.json"),
r#"{"jobs": {"brief": {"runs": 2, "last_started_ms": 1000, "last_finished_ms": 1100, "last_outcome": "ok"},
"sweep": {"runs": 3, "last_started_ms": 2000, "last_outcome": "ok"}}}"#,
)
.unwrap();
let running = probe(&Fake::down(), env_fn, None);
assert_eq!(
running.jobs.newest.as_ref().map(|n| n.outcome.as_str()),
Some("running")
);
}
#[test]
fn platforms_says_there_are_none_and_shows_the_shape_one_would_have() {
let home = tempfile::tempdir().unwrap();
install(home.path(), 8787);
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let snapshot = probe(&Fake::down(), env_fn, None);
let said = platforms(&snapshot, None);
assert!(said.starts_with("gateway:"), "{said}");
assert!(said.contains("platforms: none configured"), "{said}");
assert!(said.contains("no messaging front end"), "{said}");
assert!(
said.contains("name · transport · state · requests carried"),
"the columns are named rather than promised: {said}"
);
assert!(PLATFORMS.is_empty(), "there are none yet");
}
#[test]
fn a_report_changes_no_file() {
let home = tempfile::tempdir().unwrap();
let cfg = install(home.path(), 8787);
let unit = write_unit(
home.path(),
"[Service]\nEnvironment=\"ECLIPSE_PROFILE=lab\"\n",
);
std::fs::create_dir_all(cfg.join("cron")).unwrap();
std::fs::write(cfg.join("cron/jobs.toml"), "").unwrap();
let env = env_with(home.path());
let env_fn: EnvFn = &env;
let before = |path: &Path| std::fs::read(path).unwrap_or_default();
let (config_before, unit_before, jobs_before) = (
before(&cfg.join("config.toml")),
before(&unit),
before(&cfg.join("cron/jobs.toml")),
);
let snapshot = probe(&Fake::down(), env_fn, None);
let _ = platforms(&snapshot, None);
assert_eq!(before(&cfg.join("config.toml")), config_before);
assert_eq!(before(&unit), unit_before);
assert_eq!(before(&cfg.join("cron/jobs.toml")), jobs_before);
assert!(
!eclipse_core::session::db_path(&cfg.join("state/sessions")).exists(),
"the verb opened the session store"
);
}
#[test]
fn the_unit_environment_is_read_as_the_pair_it_is() {
let text = "[Unit]\nDescription=x\n\n[Service]\n\
Environment=\"ECLIPSE_PROFILE=lab\"\n\
Environment=\"ECLIPSE_CONFIG=/srv/eclipse/lab.toml\"\n";
let (profile, config) = unit_env(text);
assert_eq!(profile.as_deref(), Some("lab"));
assert_eq!(config.as_deref(), Some(Path::new("/srv/eclipse/lab.toml")));
assert_eq!(
unit_env("[Service]\nExecStart=/usr/bin/eclipse\n"),
(None, None)
);
assert_eq!(unit_env("Environment=\"ECLIPSE_PROFILE=\"\n"), (None, None));
}
#[test]
fn systemctls_own_words_are_kept_and_a_zero_is_absence() {
let shown = parse_show(
"ActiveState=active\nActiveEnterTimestampMonotonic=1234000000\nExecMainPID=99\n",
);
assert_eq!(shown.state, "active");
assert_eq!(shown.pid, Some(99));
assert_eq!(shown.entered_us, Some(1_234_000_000));
let never =
parse_show("ActiveState=failed\nActiveEnterTimestampMonotonic=0\nExecMainPID=0\n");
assert_eq!(never.state, "failed");
assert_eq!(never.pid, None);
assert_eq!(never.entered_us, None);
assert_eq!(parse_show("").state, "");
}
#[test]
fn an_age_is_two_units_and_no_more() {
assert_eq!(span(Duration::from_secs(48)), "48 s");
assert_eq!(span(Duration::from_secs(12 * 60 + 5)), "12 m");
assert_eq!(span(Duration::from_secs(4 * 3600 + 12 * 60)), "4 h 12 m");
assert_eq!(span(Duration::from_secs(3 * 86_400 + 4 * 3600)), "3 d 4 h");
}
}