use std::collections::{BTreeMap, BTreeSet};
use super::procs::{ProcState, MESSAGE_ROW};
pub use crate::snapshot::{collect, ContainerStatus, InstanceRow, SandboxRow, ServiceRow, Snapshot};
pub const ORPHANS_NAME: &str = "(not in config)";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Node {
Sandbox(usize),
Instance(usize),
Empty(usize),
Orphans,
Proc { instance: usize, row: usize },
}
pub fn visible_nodes(
sandboxes: &[SandboxRow],
instances: &[InstanceRow],
collapsed: &BTreeSet<String>,
expanded_procs: &BTreeSet<String>,
procs: &BTreeMap<String, ProcState>,
) -> Vec<Node> {
let mut nodes = Vec::new();
let configured: BTreeSet<&str> = sandboxes.iter().map(|s| s.name.as_str()).collect();
for (si, sb) in sandboxes.iter().enumerate() {
nodes.push(Node::Sandbox(si));
if collapsed.contains(&sb.name) {
continue;
}
let mut any = false;
for (ii, inst) in instances.iter().enumerate() {
if inst.sandbox == sb.name {
nodes.push(Node::Instance(ii));
push_proc_nodes(&mut nodes, ii, inst, expanded_procs, procs);
any = true;
}
}
if !any {
nodes.push(Node::Empty(si));
}
}
let orphans: Vec<usize> = instances
.iter()
.enumerate()
.filter(|(_, inst)| !configured.contains(inst.sandbox.as_str()))
.map(|(ii, _)| ii)
.collect();
if !orphans.is_empty() {
nodes.push(Node::Orphans);
if !collapsed.contains(ORPHANS_NAME) {
for ii in orphans {
nodes.push(Node::Instance(ii));
push_proc_nodes(&mut nodes, ii, &instances[ii], expanded_procs, procs);
}
}
}
nodes
}
fn push_proc_nodes(
nodes: &mut Vec<Node>,
instance: usize,
inst: &InstanceRow,
expanded_procs: &BTreeSet<String>,
procs: &BTreeMap<String, ProcState>,
) {
if !expanded_procs.contains(&inst.name) {
return;
}
match procs.get(&inst.name) {
Some(ProcState::Rows { rows, .. }) => {
for row in 0..rows.len() {
nodes.push(Node::Proc { instance, row });
}
}
_ => nodes.push(Node::Proc { instance, row: MESSAGE_ROW }),
}
}
pub fn dispatcher_label(row: &InstanceRow, instances: &[InstanceRow]) -> Option<String> {
let id = row.dispatcher.as_deref()?;
Some(match instances.iter().find(|i| i.instance_id == id) {
Some(owner) => format!("⇠ {}", owner.name),
None => format!("⇠ {id} (orphan)"),
})
}
pub fn sandbox_stats(instances: usize, running: usize) -> String {
format!("{running}/{instances} running")
}
pub fn humanize_secs(secs: u64) -> String {
let days = secs / 86_400;
let hours = (secs % 86_400) / 3_600;
let mins = (secs % 3_600) / 60;
if days > 0 {
format!("{days}d{hours}h")
} else if hours > 0 {
format!("{hours}h{mins:02}m")
} else if mins > 0 {
format!("{mins}m")
} else {
format!("{secs}s")
}
}
pub const STALE_AFTER_SECS: u64 = 10;
pub fn totals_line(snapshot: &Snapshot, age: std::time::Duration) -> String {
let running = snapshot
.instances
.iter()
.filter(|r| matches!(r.status, ContainerStatus::Running(_)))
.count();
let stopped = snapshot.instances.len() - running;
let service_containers: usize = snapshot
.services
.iter()
.flat_map(|s| &s.containers)
.filter(|(_, st)| !matches!(st, ContainerStatus::Missing))
.count();
let version = snapshot.runtime_version.as_deref().unwrap_or("?");
let mut line = format!(
"{} {} · {running} running / {stopped} stopped · {service_containers} service {} · {} {version}",
snapshot.sandbox_count,
plural(snapshot.sandbox_count, "sandbox", "sandboxes"),
plural(service_containers, "container", "containers"),
snapshot.runtime_name,
);
if age.as_secs() >= STALE_AFTER_SECS {
line.push_str(&format!(" (stale {}s)", age.as_secs()));
}
line
}
fn plural<'a>(n: usize, singular: &'a str, plural: &'a str) -> &'a str {
if n == 1 { singular } else { plural }
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn humanize_secs_scales() {
assert_eq!(humanize_secs(0), "0s");
assert_eq!(humanize_secs(40), "40s");
assert_eq!(humanize_secs(60), "1m");
assert_eq!(humanize_secs(12 * 60), "12m");
assert_eq!(humanize_secs(2 * 3600 + 5 * 60), "2h05m");
assert_eq!(humanize_secs(3 * 86_400 + 4 * 3600 + 30 * 60), "3d4h");
}
fn inst(name: &str, status: ContainerStatus) -> InstanceRow {
InstanceRow {
name: name.into(),
sandbox: "s".into(),
container: format!("devsandbox-{name}"),
status,
uptime_secs: 0,
cpu: None,
mem: None,
folder: "/f".into(),
worktree: false,
services: Vec::new(),
workspace: "/w".into(),
remote_user: None,
remote_env_len: 0,
base_folder: "/f".into(),
drift: false,
instance_id: String::new(),
dispatcher: None,
}
}
fn svc_row(containers: Vec<ContainerStatus>) -> ServiceRow {
ServiceRow {
name: "db".into(),
scope: "global",
source: "image x".into(),
ports: Vec::new(),
containers: containers
.into_iter()
.enumerate()
.map(|(i, s)| (format!("c{i}"), s))
.collect(),
used_by: Vec::new(),
env_len: 0,
command: None,
config_hash: String::new(),
drift: false,
}
}
fn snap(
instances: Vec<InstanceRow>,
services: Vec<ServiceRow>,
sandbox_count: usize,
runtime_version: Option<&str>,
) -> Snapshot {
Snapshot {
instances,
sandboxes: Vec::new(),
services,
sandbox_count,
runtime_name: "docker",
runtime_version: runtime_version.map(str::to_string),
collected_at: Instant::now(),
error: None,
}
}
#[test]
fn totals_line_counts_running_stopped_and_service_containers() {
let s = snap(
vec![
inst("a", ContainerStatus::Running("Up".into())),
inst("b", ContainerStatus::Exited("Exited".into())),
inst("c", ContainerStatus::Missing),
],
vec![svc_row(vec![
ContainerStatus::Running("Up".into()),
ContainerStatus::Missing,
])],
3,
Some("24.0.7"),
);
assert_eq!(
totals_line(&s, std::time::Duration::from_secs(0)),
"3 sandboxes · 1 running / 2 stopped · 1 service container · docker 24.0.7",
);
}
#[test]
fn totals_line_pluralizes_and_marks_missing_version() {
let s = snap(vec![inst("a", ContainerStatus::Running("Up".into()))], Vec::new(), 1, None);
assert_eq!(
totals_line(&s, std::time::Duration::from_secs(0)),
"1 sandbox · 1 running / 0 stopped · 0 service containers · docker ?",
);
}
#[test]
fn totals_line_flags_stale_data() {
let s = snap(Vec::new(), Vec::new(), 0, Some("24.0.7"));
let out = totals_line(&s, std::time::Duration::from_secs(STALE_AFTER_SECS + 2));
assert!(out.ends_with(" (stale 12s)"), "got: {out}");
let fresh = totals_line(&s, std::time::Duration::from_secs(1));
assert!(!fresh.contains("stale"), "got: {fresh}");
}
fn sb(name: &str) -> SandboxRow {
SandboxRow {
name: name.into(),
source: "image x".into(),
folder: None,
services: Vec::new(),
extends: Vec::new(),
config_hash: "hash".into(),
build_hash: String::new(),
issues: Vec::new(),
}
}
#[test]
fn dispatcher_label_names_the_owner_or_marks_an_orphan() {
let mut owner = inst("pr-dispatcher", ContainerStatus::Missing);
owner.instance_id = "d-1".into();
let mut child = inst("web-pr-1", ContainerStatus::Missing);
child.instance_id = "c-1".into();
child.dispatcher = Some("d-1".into());
let mut orphan = inst("web-pr-2", ContainerStatus::Missing);
orphan.dispatcher = Some("gone-7".into());
let rows = vec![owner.clone(), child.clone(), orphan.clone()];
assert_eq!(dispatcher_label(&owner, &rows), None, "user-created");
assert_eq!(dispatcher_label(&child, &rows).as_deref(), Some("⇠ pr-dispatcher"));
assert_eq!(dispatcher_label(&orphan, &rows).as_deref(), Some("⇠ gone-7 (orphan)"));
assert_eq!(dispatcher_label(&child, &rows[1..]).as_deref(), Some("⇠ d-1 (orphan)"));
}
fn inst_in(name: &str, sandbox: &str) -> InstanceRow {
let mut row = inst(name, ContainerStatus::Missing);
row.sandbox = sandbox.into();
row
}
fn collapsed(names: &[&str]) -> BTreeSet<String> {
names.iter().map(|s| s.to_string()).collect()
}
fn no_procs() -> (BTreeSet<String>, BTreeMap<String, ProcState>) {
(BTreeSet::new(), BTreeMap::new())
}
#[test]
fn visible_nodes_expands_sandboxes_with_instances() {
let sandboxes = vec![sb("a"), sb("b")];
let instances = vec![
inst_in("a1", "a"),
inst_in("b1", "b"),
inst_in("a2", "a"),
];
let (ep, pm) = no_procs();
let nodes = visible_nodes(&sandboxes, &instances, &BTreeSet::new(), &ep, &pm);
assert_eq!(
nodes,
vec![
Node::Sandbox(0),
Node::Instance(0), Node::Instance(2), Node::Sandbox(1),
Node::Instance(1), ],
);
}
#[test]
fn visible_nodes_empty_sandbox_gets_marker() {
let sandboxes = vec![sb("a")];
let (ep, pm) = no_procs();
let nodes = visible_nodes(&sandboxes, &[], &BTreeSet::new(), &ep, &pm);
assert_eq!(nodes, vec![Node::Sandbox(0), Node::Empty(0)]);
}
#[test]
fn visible_nodes_collapsed_sandbox_hides_children() {
let sandboxes = vec![sb("a"), sb("b")];
let instances = vec![inst_in("a1", "a"), inst_in("b1", "b")];
let (ep, pm) = no_procs();
let nodes = visible_nodes(&sandboxes, &instances, &collapsed(&["a"]), &ep, &pm);
assert_eq!(
nodes,
vec![Node::Sandbox(0), Node::Sandbox(1), Node::Instance(1)],
);
}
#[test]
fn visible_nodes_orphans_group_at_bottom() {
let sandboxes = vec![sb("a")];
let instances = vec![inst_in("a1", "a"), inst_in("x1", "gone")];
let (ep, pm) = no_procs();
let nodes = visible_nodes(&sandboxes, &instances, &BTreeSet::new(), &ep, &pm);
assert_eq!(
nodes,
vec![
Node::Sandbox(0),
Node::Instance(0),
Node::Orphans,
Node::Instance(1),
],
);
let nodes = visible_nodes(&sandboxes, &instances, &collapsed(&[ORPHANS_NAME]), &ep, &pm);
assert_eq!(
nodes,
vec![Node::Sandbox(0), Node::Instance(0), Node::Orphans],
);
}
#[test]
fn visible_nodes_no_orphan_group_when_all_configured() {
let sandboxes = vec![sb("a")];
let instances = vec![inst_in("a1", "a")];
let (ep, pm) = no_procs();
let nodes = visible_nodes(&sandboxes, &instances, &BTreeSet::new(), &ep, &pm);
assert!(!nodes.contains(&Node::Orphans));
}
fn proc_row(pid: &str) -> super::super::procs::ProcRow {
super::super::procs::ProcRow { pid: pid.into(), depth: 0, args: "x".into() }
}
#[test]
fn visible_nodes_emits_proc_rows_under_expanded_instance() {
let sandboxes = vec![sb("a")];
let instances = vec![inst_in("a1", "a")];
let expanded: BTreeSet<String> = ["a1".to_string()].into_iter().collect();
let mut procs = BTreeMap::new();
procs.insert(
"a1".to_string(),
ProcState::Rows { rows: vec![proc_row("1"), proc_row("2")], signalable: true },
);
let nodes = visible_nodes(&sandboxes, &instances, &BTreeSet::new(), &expanded, &procs);
assert_eq!(
nodes,
vec![
Node::Sandbox(0),
Node::Instance(0),
Node::Proc { instance: 0, row: 0 },
Node::Proc { instance: 0, row: 1 },
],
);
}
#[test]
fn visible_nodes_message_row_when_not_fetched_or_error() {
let sandboxes = vec![sb("a")];
let instances = vec![inst_in("a1", "a")];
let expanded: BTreeSet<String> = ["a1".to_string()].into_iter().collect();
let nodes =
visible_nodes(&sandboxes, &instances, &BTreeSet::new(), &expanded, &BTreeMap::new());
assert_eq!(nodes.last(), Some(&Node::Proc { instance: 0, row: MESSAGE_ROW }));
let mut procs = BTreeMap::new();
procs.insert("a1".to_string(), ProcState::Message("(not running)".into()));
let nodes = visible_nodes(&sandboxes, &instances, &BTreeSet::new(), &expanded, &procs);
assert_eq!(
nodes,
vec![
Node::Sandbox(0),
Node::Instance(0),
Node::Proc { instance: 0, row: MESSAGE_ROW },
],
);
}
#[test]
fn visible_nodes_collapsed_sandbox_hides_expanded_procs() {
let sandboxes = vec![sb("a")];
let instances = vec![inst_in("a1", "a")];
let expanded: BTreeSet<String> = ["a1".to_string()].into_iter().collect();
let mut procs = BTreeMap::new();
procs.insert(
"a1".to_string(),
ProcState::Rows { rows: vec![proc_row("1")], signalable: true },
);
let nodes = visible_nodes(&sandboxes, &instances, &collapsed(&["a"]), &expanded, &procs);
assert_eq!(nodes, vec![Node::Sandbox(0)]);
}
#[test]
fn sandbox_stats_formats_running_over_total() {
assert_eq!(sandbox_stats(0, 0), "0/0 running");
assert_eq!(sandbox_stats(3, 1), "1/3 running");
}
}