use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value, json};
use super::api::InstancesList;
use super::capacity::Capacity;
use super::machines::{Entry, MachineKind};
use crate::snapshot::{ContainerStatus, Depth, RuntimeView, Snapshot};
pub const LISTING_INTERVAL: Duration = Duration::from_secs(2);
pub const STATS_INTERVAL: Duration = Duration::from_secs(7);
pub type Join = Arc<dyn Fn(&Path, &RuntimeView) -> InstancesList + Send + Sync>;
type Usage = BTreeMap<String, (Option<String>, Option<String>)>;
#[derive(Default)]
pub struct Snapshots {
inner: Mutex<Inner>,
}
#[derive(Default)]
struct Inner {
roots: BTreeMap<PathBuf, Root>,
last_stats: Option<Instant>,
capacity: Option<Value>,
}
struct Root {
pushed: Arc<Value>,
usage: Usage,
stats: bool,
}
impl Snapshots {
pub fn cached(&self, dir: &Path) -> Option<Arc<Value>> {
self.lock().roots.get(dir).map(|r| Arc::clone(&r.pushed))
}
pub fn stats_due(&self, watched: &BTreeSet<PathBuf>, now: Instant) -> bool {
let inner = self.lock();
let fresh = watched.iter().any(|d| !inner.roots.get(d).is_some_and(|r| r.stats));
stats_due(inner.last_stats, now, fresh)
}
pub fn prune(&self, watched: &BTreeSet<PathBuf>) {
self.lock().roots.retain(|dir, _| watched.contains(dir));
}
pub fn uncached(&self, watched: &BTreeSet<PathBuf>) -> BTreeSet<PathBuf> {
let inner = self.lock();
watched.iter().filter(|d| !inner.roots.contains_key(*d)).cloned().collect()
}
pub fn set_capacity(&self, capacity: &Capacity) {
self.lock().capacity = serde_json::to_value(capacity).ok();
}
pub fn collect(
&self,
view: &RuntimeView,
roots: &BTreeSet<PathBuf>,
join: &(dyn Fn(&Path, &RuntimeView) -> InstancesList + Send + Sync),
) -> Vec<(PathBuf, Arc<Value>)> {
if view.depth == Depth::Full {
self.lock().last_stats = Some(view.at);
}
let mut out = Vec::new();
for dir in roots {
let prev = self.lock().roots.get(dir).map(|r| r.usage.clone()).unwrap_or_default();
let mut list = join(dir, view);
let stats = list.snapshot.depth == Depth::Full;
let had = self.lock().roots.get(dir).is_some_and(|r| r.stats);
carry_over(&mut list.snapshot, &prev);
if had && list.snapshot.depth == Depth::Listing {
list.snapshot.depth = Depth::Full;
}
let usage = usage(&list.snapshot);
let capacity = self.lock().capacity.clone();
let Some(pushed) = params_with(dir, &list, capacity) else { continue };
let mut inner = self.lock();
inner.roots.insert(dir.clone(), Root { pushed: Arc::clone(&pushed), usage, stats: had || stats });
out.push((dir.clone(), pushed));
}
out
}
fn lock(&self) -> std::sync::MutexGuard<'_, Inner> {
self.inner.lock().unwrap_or_else(|e| e.into_inner())
}
}
pub fn params(dir: &Path, list: &InstancesList) -> Option<Arc<Value>> {
params_with(dir, list, None)
}
fn params_with(dir: &Path, list: &InstancesList, capacity: Option<Value>) -> Option<Arc<Value>> {
let mut value = serde_json::to_value(list).ok()?;
let obj = value.as_object_mut()?;
obj.insert("dir".into(), Value::String(dir.to_string_lossy().into_owned()));
if let Some(capacity) = capacity {
obj.insert("capacity".into(), capacity);
}
Some(Arc::new(value))
}
pub fn stats_due(last: Option<Instant>, now: Instant, fresh: bool) -> bool {
fresh || last.is_none_or(|last| now >= last + STATS_INTERVAL)
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LinkState {
#[default]
Idle,
Connecting,
Connected,
Unreachable,
}
impl LinkState {
pub fn as_str(self) -> &'static str {
match self {
LinkState::Idle => "idle",
LinkState::Connecting => "connecting",
LinkState::Connected => "connected",
LinkState::Unreachable => "unreachable",
}
}
}
#[derive(Debug, Clone, Default)]
pub struct Machine {
pub name: String,
pub kind: MachineKind,
pub target: Option<String>,
pub command: Option<String>,
pub roots: Vec<PathBuf>,
pub default_root: Option<PathBuf>,
pub listed: bool,
pub state: LinkState,
pub error: Option<String>,
pub behind: crate::serve::fleet::update::Behind,
pub version: Option<String>,
pub rows: BTreeMap<PathBuf, Arc<Value>>,
pub seen: Option<u64>,
pub restored: bool,
pub fleet: Option<Arc<Value>>,
}
impl Machine {
pub fn capacity(&self) -> Option<Capacity> {
self.roots.iter().find_map(|r| serde_json::from_value(self.rows.get(r)?.get("capacity")?.clone()).ok())
}
pub fn set_link(&mut self, state: LinkState, error: Option<String>) -> bool {
let behind = state != LinkState::Connected && std::mem::take(&mut self.behind) != Default::default();
self.set_state(state, error) || behind
}
pub fn set_up(&mut self, behind: crate::serve::fleet::update::Behind) -> bool {
let moved = self.set_state(LinkState::Connected, None);
let behind_moved = self.behind != behind;
self.behind = behind;
moved || behind_moved
}
fn set_state(&mut self, state: LinkState, error: Option<String>) -> bool {
let (state, error) = match (self.restored, state) {
(false, _) => (state, error),
(true, LinkState::Connected) => {
self.restored = false;
(state, error)
}
(true, LinkState::Connecting) => return false,
(true, _) => (LinkState::Unreachable, Some(restored_error(error.as_deref(), self.seen))),
};
let moved = self.state != state || self.error != error;
self.state = state;
self.error = error;
moved
}
}
pub fn restored_error(why: Option<&str>, seen: Option<u64>) -> String {
let why = why.unwrap_or("not reconnected since this daemon started");
match seen {
Some(at) => format!("{why} (rows from {} UTC)", crate::inbox::clock::stamp(at, 0)),
None => why.to_string(),
}
}
#[derive(Default)]
pub struct Remotes {
inner: Mutex<BTreeMap<String, Machine>>,
}
impl Remotes {
pub fn sync(&self, entries: &[Entry]) {
let mut inner = self.lock();
inner.retain(|name, _| entries.iter().any(|e| e.name == *name));
for e in entries {
let m = inner.entry(e.name.clone()).or_insert_with(|| Machine { name: e.name.clone(), ..Machine::default() });
(m.kind, m.target) = e.kind.wire();
m.command.clone_from(&e.command);
}
}
pub fn roots(&self, name: &str) -> Vec<PathBuf> {
self.lock().get(name).map(|m| m.roots.clone()).unwrap_or_default()
}
pub fn restore(&self, machines: Vec<Machine>) {
let mut inner = self.lock();
for m in machines {
inner.entry(m.name.clone()).or_insert(m);
}
}
pub fn update(&self, name: &str, f: impl FnOnce(&mut Machine)) {
if let Some(m) = self.lock().get_mut(name) {
f(m);
}
}
pub fn get(&self, name: &str) -> Option<Machine> {
self.lock().get(name).cloned()
}
pub fn routed(&self, reach: Vec<(String, Result<String, String>)>) -> Vec<Routed> {
routed(reach, &self.lock().values().cloned().collect::<Vec<_>>())
}
pub fn all(&self) -> Vec<Machine> {
self.lock().values().cloned().collect()
}
fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, Machine>> {
self.inner.lock().unwrap_or_else(|e| e.into_inner())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SnapshotMachine {
pub name: String,
pub kind: MachineKind,
pub target: Option<String>,
pub state: LinkState,
pub error: Option<String>,
#[serde(default)]
pub behind: Option<String>,
#[serde(default)]
pub behind_here: Option<String>,
pub version: Option<String>,
pub runtime: Option<String>,
#[serde(default)]
pub depth: Option<Depth>,
pub command: Option<String>,
pub agent: bool,
#[serde(default)]
pub capacity: Option<Capacity>,
#[serde(default)]
pub via: Option<String>,
#[serde(default)]
pub exposed_by: Option<Vec<String>>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Routed {
pub name: String,
pub via: Option<String>,
pub state: LinkState,
pub error: Option<String>,
pub roots: Vec<PathBuf>,
pub version: Option<String>,
pub capacity: Option<Capacity>,
}
pub fn routed(reach: Vec<(String, Result<String, String>)>, machines: &[Machine]) -> Vec<Routed> {
let direct = |name: &str| machines.iter().any(|m| m.name == name);
let mut out: BTreeMap<String, Routed> = BTreeMap::new();
for (name, r) in reach {
if direct(&name) {
continue;
}
let (via, state, error) = match r {
Ok(hop) => (Some(hop), LinkState::Connected, None),
Err(why) => (None, LinkState::Unreachable, Some(why)),
};
out.insert(name.clone(), Routed { name, via, state, error, ..Routed::default() });
}
for control_plane in machines {
let Some(view) = control_plane.fleet.as_deref() else { continue };
for e in rows(view, "machines") {
let Ok(seen) = serde_json::from_value::<SnapshotMachine>(e.clone()) else { continue };
if direct(&seen.name) {
continue;
}
let r = out.entry(seen.name.clone()).or_insert_with(|| Routed {
name: seen.name.clone(),
state: LinkState::Unreachable,
error: Some(format!("no path to `{}` in this host's link graph", seen.name)),
..Routed::default()
});
if r.via.is_none() {
r.via = Some(control_plane.name.clone());
}
r.version = r.version.take().or(seen.version);
r.capacity = r.capacity.take().or(seen.capacity);
for row in rows(view, "sandboxes").filter(|row| row.get("machine").and_then(Value::as_str) == Some(&seen.name)) {
if let Some(root) = row.get("root").and_then(Value::as_str).map(PathBuf::from)
&& !r.roots.contains(&root)
{
r.roots.push(root);
}
}
}
}
out.into_values().collect()
}
pub fn fleet_view(params: &mut Value, me: Option<&str>) -> Value {
let Some(obj) = params.as_object_mut() else { return json!({}) };
let entries: Vec<Value> = take_array(obj, "machines")
.into_iter()
.filter(|e| {
let name = e.get("name").and_then(Value::as_str);
name.is_some() && name != me && e.get("via").is_none_or(Value::is_null)
})
.collect();
let names: BTreeSet<String> = entries.iter().filter_map(|e| e.get("name")?.as_str().map(String::from)).collect();
let mut view = Map::new();
for key in ["instances", "sandboxes", "services"] {
let (tagged, own): (Vec<Value>, Vec<Value>) = take_array(obj, key).into_iter().partition(|r| r.get("machine").and_then(Value::as_str).is_some());
obj.insert(key.into(), Value::Array(own));
let kept = tagged.into_iter().filter(|r| r.get("machine").and_then(Value::as_str).is_some_and(|m| names.contains(m)));
view.insert(key.into(), Value::Array(kept.collect()));
}
view.insert("machines".into(), Value::Array(entries));
Value::Object(view)
}
pub fn merge(local: &Value, machines: &[Machine], except: Option<&str>, exposed: &BTreeMap<String, Vec<String>>, granted: &BTreeSet<String>) -> Value {
let machines: Vec<&Machine> = machines.iter().filter(|m| Some(m.name.as_str()) != except).collect();
let mut out = local.clone();
let Some(obj) = out.as_object_mut() else { return out };
let mut instances = take_array(obj, "instances");
let mut sandboxes = take_array(obj, "sandboxes");
let mut services = take_array(obj, "services");
for m in machines.iter().copied() {
for (i, root) in m.roots.iter().enumerate() {
let Some(params) = m.rows.get(root) else { continue };
let root_text = root.to_string_lossy();
for row in rows(params, "instances") {
let own = row.get("root").and_then(Value::as_str).map(Path::new);
let here = match (own, &m.default_root) {
(Some(own), _) if m.roots.iter().any(|r| r == own) => own == root,
(_, Some(default)) if m.roots.contains(default) => default == root,
_ => i == 0,
};
if here {
instances.push(tag(row, &m.name, None));
}
}
sandboxes.extend(rows(params, "sandboxes").map(|row| tag(row, &m.name, Some(&root_text))));
services.extend(rows(params, "services").map(|row| tag(row, &m.name, Some(&root_text))));
}
}
let mut entries: Vec<SnapshotMachine> = machines.iter().map(|m| snapshot_machine(m)).collect();
for control_plane in machines.iter().copied() {
let Some(view) = control_plane.fleet.as_deref() else { continue };
let mut lifted = BTreeSet::new();
for e in rows(view, "machines") {
let Ok(mut m) = serde_json::from_value::<SnapshotMachine>(e.clone()) else { continue };
if Some(m.name.as_str()) == except || entries.iter().any(|d| d.name == m.name) {
continue;
}
lift(&mut m, control_plane);
lifted.insert(m.name.clone());
entries.push(m);
}
let theirs = |r: &&Value| r.get("machine").and_then(Value::as_str).is_some_and(|m| lifted.contains(m));
instances.extend(rows(view, "instances").filter(theirs).cloned());
sandboxes.extend(rows(view, "sandboxes").filter(theirs).cloned());
services.extend(rows(view, "services").filter(theirs).cloned());
}
obj.insert("instances".into(), Value::Array(instances));
obj.insert("sandbox_count".into(), json!(sandboxes.len()));
obj.insert("sandboxes".into(), Value::Array(sandboxes));
obj.insert("services".into(), Value::Array(services));
for m in &mut entries {
m.exposed_by = exposed.get(&m.name).cloned();
m.agent = granted.contains(&m.name);
}
let entries: Vec<Value> = entries.iter().map(|m| json!(m)).collect();
obj.insert("machines".into(), Value::Array(entries));
out
}
fn lift(m: &mut SnapshotMachine, control_plane: &Machine) {
m.kind = MachineKind::Routed;
m.via = Some(control_plane.name.clone());
m.target = None;
m.command = None;
m.behind_here = None;
if control_plane.state != LinkState::Connected {
m.behind = None;
let why = control_plane.error.as_deref().unwrap_or(control_plane.state.as_str());
m.state = match control_plane.state {
LinkState::Idle => LinkState::Connecting,
state => state,
};
m.error = Some(format!("through {}: {}", control_plane.name, why_without(&control_plane.name, why)));
}
}
fn why_without<'a>(machine: &str, error: &'a str) -> &'a str {
error.strip_prefix(machine).and_then(|e| e.strip_prefix(": ")).unwrap_or(error)
}
fn snapshot_machine(m: &Machine) -> SnapshotMachine {
let runtime = m.roots.iter().find_map(|r| {
let row = m.rows.get(r)?;
if row.get("no_runtime").and_then(Value::as_bool) == Some(true) {
return None;
}
row.get("runtime_name")?.as_str().map(str::to_string)
});
SnapshotMachine {
depth: machine_depth(m),
capacity: m.capacity(),
name: m.name.clone(),
kind: m.kind,
target: m.target.clone(),
state: m.state,
error: m.error.clone(),
behind: m.behind.peer.clone(),
behind_here: m.behind.here.clone(),
version: m.version.clone(),
runtime,
command: m.command.clone(),
agent: false,
via: None,
exposed_by: None,
}
}
fn machine_depth(m: &Machine) -> Option<Depth> {
if !m.listed {
return None;
}
m.roots.iter().try_fold(Depth::Full, |shallowest, root| {
let depth = m.rows.get(root)?.get("depth").cloned().and_then(|d| serde_json::from_value(d).ok()).unwrap_or_default();
Some(shallowest.min(depth))
})
}
fn take_array(obj: &mut Map<String, Value>, key: &str) -> Vec<Value> {
match obj.remove(key) {
Some(Value::Array(rows)) => rows,
_ => Vec::new(),
}
}
fn rows<'a>(params: &'a Value, key: &str) -> impl Iterator<Item = &'a Value> {
params.get(key).and_then(Value::as_array).into_iter().flatten()
}
fn tag(row: &Value, machine: &str, root: Option<&str>) -> Value {
let mut row = row.clone();
if let Some(obj) = row.as_object_mut() {
obj.insert("machine".into(), machine.into());
if let Some(root) = root {
obj.insert("root".into(), root.into());
}
}
row
}
pub fn carry_remote_status(prev: &Value, next: &mut Value) {
let unknown = |row: &Value| row.pointer("/status/state").and_then(Value::as_str) == Some("unknown");
let Some(next_rows) = next.get_mut("instances").and_then(Value::as_array_mut) else { return };
if next_rows.is_empty() || !next_rows.iter().all(unknown) {
return;
}
let before: BTreeMap<&str, &Value> =
rows(prev, "instances").filter_map(|r| Some((r.get("container")?.as_str()?, r))).collect();
for row in next_rows {
let Some(old) = row.get("container").and_then(Value::as_str).and_then(|c| before.get(c)) else { continue };
if unknown(old) {
continue;
}
let Some(obj) = row.as_object_mut() else { continue };
for key in ["status", "cpu", "mem"] {
if let Some(v) = old.get(key) {
obj.insert(key.into(), v.clone());
}
}
}
}
fn carry_over(snapshot: &mut Snapshot, prev: &Usage) {
if snapshot.depth == Depth::Full {
return;
}
for row in &mut snapshot.instances {
if !matches!(row.status, ContainerStatus::Running(_)) {
continue;
}
if let Some((cpu, mem)) = prev.get(&row.container) {
row.cpu.clone_from(cpu);
row.mem.clone_from(mem);
}
}
}
fn usage(snapshot: &Snapshot) -> Usage {
snapshot
.instances
.iter()
.filter(|r| matches!(r.status, ContainerStatus::Running(_)))
.map(|r| (r.container.clone(), (r.cpu.clone(), r.mem.clone())))
.collect()
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use crate::snapshot::InstanceRow;
#[test]
fn stats_are_due_every_interval_or_for_a_fresh_root() {
let t0 = Instant::now();
assert!(stats_due(None, t0, false));
assert!(!stats_due(Some(t0), t0 + Duration::from_secs(2), false));
assert!(stats_due(Some(t0), t0 + Duration::from_secs(2), true));
assert!(!stats_due(Some(t0), t0 + STATS_INTERVAL - Duration::from_millis(1), false));
assert!(stats_due(Some(t0), t0 + STATS_INTERVAL, false));
}
pub(crate) fn row(container: &str, running: bool, cpu: Option<&str>) -> InstanceRow {
let status = if running { ContainerStatus::Running("Up".into()) } else { ContainerStatus::Exited("Exited".into()) };
let json = serde_json::json!({
"name": container, "sandbox": "s", "container": container, "status": status,
"uptime_secs": 0, "cpu": cpu, "mem": cpu.map(|c| format!("{c}MiB")), "folder": "/w",
"worktree": false, "services": [], "workspace": "/w", "remote_user": null,
"remote_env_len": 0, "base_folder": "/w", "drift": false, "instance_id": container,
"dispatcher": null, "done": false, "phase": null,
});
serde_json::from_value(json).unwrap()
}
pub(crate) fn snapshot(instances: Vec<InstanceRow>, stats: bool) -> Snapshot {
let json = serde_json::json!({
"instances": instances, "sandboxes": [], "services": [], "sandbox_count": 0,
"runtime_name": "docker", "runtime_version": null, "error": null,
});
let mut s: Snapshot = serde_json::from_value(json).unwrap();
s.depth = if stats { Depth::Full } else { Depth::Listing };
s
}
#[test]
fn listing_only_snapshots_carry_running_cpu_mem_over() {
let full = snapshot(vec![row("a", true, Some("1%")), row("b", true, Some("2%"))], true);
let prev = usage(&full);
let mut listing = snapshot(vec![row("a", true, None), row("b", false, None), row("c", true, None)], false);
carry_over(&mut listing, &prev);
let cpu: Vec<_> = listing.instances.iter().map(|r| r.cpu.as_deref()).collect();
assert_eq!(cpu, [Some("1%"), None, None]);
assert_eq!(listing.instances[0].mem.as_deref(), Some("1%MiB"));
let prev = usage(&listing);
let mut restarted = snapshot(vec![row("b", true, None)], false);
carry_over(&mut restarted, &prev);
assert_eq!(restarted.instances[0].cpu, None);
let mut fresh = snapshot(vec![row("a", true, None)], true);
carry_over(&mut fresh, &usage(&full));
assert_eq!(fresh.instances[0].cpu, None);
}
fn remote(dir: &str, instances: &[(&str, Option<&str>)]) -> Arc<Value> {
let rows: Vec<Value> = instances.iter().map(|(n, r)| serde_json::json!({"name": n, "root": r})).collect();
let tag = Path::new(dir).file_name().unwrap().to_string_lossy().into_owned();
Arc::new(serde_json::json!({
"dir": dir, "instances": rows, "sandboxes": [{"name": format!("sb-{tag}"), "root": "/elsewhere"}],
"services": [{"name": format!("svc-{tag}")}], "runtime_name": "podman", "thread_children": {"x": {}},
}))
}
fn machine(name: &str, roots: &[&str], state: LinkState) -> Machine {
Machine {
name: name.into(),
target: Some(format!("me@{name}")),
roots: roots.iter().map(PathBuf::from).collect(),
state,
..Machine::default()
}
}
fn names(v: &Value, key: &str) -> Vec<String> {
v[key].as_array().unwrap().iter().map(|r| format!("{}@{}", r["name"].as_str().unwrap(), r["machine"].as_str().unwrap_or("-"))).collect()
}
#[test]
fn merge_tags_remote_rows_and_takes_each_instance_once() {
let local = serde_json::json!({
"dir": "/here", "instances": [{"name": "mine", "root": "/here"}], "sandboxes": [{"name": "s"}],
"services": [], "runtime_name": "docker", "thread_children": {"local": {}},
});
let mut a = machine("a", &["/r/one", "/r/two"], LinkState::Connected);
a.version = Some("0.6.1".into());
a.set_up(crate::serve::fleet::update::Behind { here: Some("here why".into()), peer: Some("its why".into()) });
let all = [("in-one", Some("/r/one")), ("in-two", Some("/r/two")), ("orphan", Some("/r/gone")), ("old", None)];
let capacity = Capacity { cpus: Some(8), running: 2, ..Capacity::default() };
let with_capacity = |dir: &str| {
let mut p = (*remote(dir, &all)).clone();
p["capacity"] = serde_json::to_value(&capacity).unwrap();
Arc::new(p)
};
a.rows.insert("/r/one".into(), with_capacity("/r/one"));
a.rows.insert("/r/two".into(), with_capacity("/r/two"));
let mut b = machine("b", &["/b"], LinkState::Unreachable);
b.error = Some("b: Connection refused".into());
b.rows.insert("/b".into(), remote("/b", &[("bee", Some("/b"))]));
let mut c = machine("c", &["/c"], LinkState::Unreachable);
c.error = Some("c: Permission denied".into());
c.command = Some("~/bin/devsandbox".into());
let w = Machine { kind: MachineKind::Inbound, target: None, ..machine("w", &[], LinkState::Idle) };
let merged = merge(&local, &[a, b, c, w], None, &Default::default(), &Default::default());
assert_eq!(names(&merged, "instances"), ["mine@-", "in-one@a", "orphan@a", "old@a", "in-two@a", "bee@b"]);
assert_eq!(names(&merged, "sandboxes"), ["s@-", "sb-one@a", "sb-two@a", "sb-b@b"]);
assert_eq!(merged["sandbox_count"], 4);
assert_eq!(names(&merged, "services"), ["svc-one@a", "svc-two@a", "svc-b@b"]);
assert_eq!(merged["sandboxes"][2]["root"], "/r/two");
assert_eq!(merged["services"][0]["root"], "/r/one");
assert_eq!(merged["instances"][3]["root"], Value::Null);
assert!(merged["instances"][0].get("machine").is_none(), "local rows untouched");
assert_eq!((&merged["dir"], &merged["runtime_name"]), (&serde_json::json!("/here"), &serde_json::json!("docker")));
assert_eq!(merged["thread_children"], serde_json::json!({"local": {}}));
let cap = serde_json::to_value(&capacity).unwrap();
assert_eq!(
merged["machines"],
serde_json::json!([
{"name": "a", "kind": "ssh", "target": "me@a", "state": "connected", "error": null, "behind": "its why", "behind_here": "here why", "version": "0.6.1", "runtime": "podman", "depth": null, "command": null, "agent": false, "capacity": cap, "via": null, "exposed_by": null},
{"name": "b", "kind": "ssh", "target": "me@b", "state": "unreachable", "behind": null, "behind_here": null, "error": "b: Connection refused", "version": null, "runtime": "podman", "depth": null, "command": null, "agent": false, "capacity": null, "via": null, "exposed_by": null},
{"name": "c", "kind": "ssh", "target": "me@c", "state": "unreachable", "behind": null, "behind_here": null, "error": "c: Permission denied", "version": null, "runtime": null, "depth": null, "command": "~/bin/devsandbox", "agent": false, "capacity": null, "via": null, "exposed_by": null},
{"name": "w", "kind": "inbound", "target": null, "state": "idle", "error": null, "behind": null, "behind_here": null, "version": null, "runtime": null, "depth": null, "command": null, "agent": false, "capacity": null, "via": null, "exposed_by": null},
])
);
crate::serve::dts::assert_matches("SnapshotMachine", &merged["machines"][0]);
crate::serve::dts::assert_matches("Capacity", &merged["machines"][0]["capacity"]);
let alone = merge(&local, &[], None, &Default::default(), &Default::default());
let mut want = local.clone();
want["machines"] = serde_json::json!([]);
want["sandbox_count"] = serde_json::json!(want["sandboxes"].as_array().unwrap().len());
assert_eq!(alone, want);
}
#[test]
fn a_machines_depth_is_its_shallowest_roots() {
let with = |depth: Option<&str>| {
let mut p = (*remote("/r/x", &[])).clone();
if let Some(d) = depth {
p["depth"] = d.into();
}
Arc::new(p)
};
let mut a = machine("a", &["/r/one", "/r/two"], LinkState::Connected);
a.rows.insert("/r/one".into(), with(Some("full")));
assert_eq!(machine_depth(&a), None, "not listed");
a.listed = true;
assert_eq!(machine_depth(&a), None, "/r/two hasn't pushed");
a.rows.insert("/r/two".into(), with(Some("listing")));
assert_eq!(machine_depth(&a), Some(Depth::Listing));
a.rows.insert("/r/two".into(), with(None));
assert_eq!(machine_depth(&a), Some(Depth::Disk));
a.rows.insert("/r/two".into(), with(Some("full")));
assert_eq!(snapshot_machine(&a).depth, Some(Depth::Full));
let none = Machine { listed: true, ..machine("n", &[], LinkState::Connected) };
assert_eq!(machine_depth(&none), Some(Depth::Full), "no roots: nothing to wait for");
}
#[test]
fn merge_takes_rootless_instances_from_the_default_root() {
let local = serde_json::json!({"dir": "/here", "instances": [], "sandboxes": [], "services": []});
let mut a = machine("a", &["/r/one", "/r/two"], LinkState::Connected);
a.default_root = Some("/r/two".into());
a.rows.insert("/r/one".into(), remote("/r/one", &[("in-one", Some("/r/one"))]));
a.rows.insert("/r/two".into(), remote("/r/two", &[("old", None), ("in-one", Some("/r/one"))]));
let merged = merge(&local, &[a], None, &Default::default(), &Default::default());
assert_eq!(names(&merged, "instances"), ["in-one@a", "old@a"]);
}
fn control_plane_push() -> Value {
let entry = |name: &str, via: Option<&str>| {
serde_json::json!({"name": name, "kind": "ssh", "target": format!("me@{name}"), "state": "connected", "error": null,
"behind": "its why", "behind_here": "the control plane's why", "version": "0.6.0", "runtime": "docker", "command": "~/ds", "agent": true, "capacity": null, "via": via})
};
serde_json::json!({
"dir": "/fleet/me", "runtime_name": "docker",
"instances": [{"name": "control-plane-own", "root": "/k"}, {"name": "xi", "machine": "x", "root": "/x"},
{"name": "mine", "machine": "me", "root": "/m"}, {"name": "yi", "machine": "y", "root": "/y"}],
"sandboxes": [{"name": "control-plane-sb"}, {"name": "x-sb", "machine": "x", "root": "/x"}],
"services": [{"name": "x-svc", "machine": "x", "root": "/x"}],
"machines": [entry("x", None), entry("me", None), entry("y", Some("z"))],
})
}
#[test]
fn a_control_planes_push_splits_into_its_own_rows_and_the_fleet_view() {
let mut params = control_plane_push();
let view = fleet_view(&mut params, Some("me"));
assert_eq!(names(¶ms, "instances"), ["control-plane-own@-"]);
assert_eq!(names(¶ms, "sandboxes"), ["control-plane-sb@-"]);
assert!(params.get("machines").is_none());
assert_eq!(names(&view, "instances"), ["xi@x"]);
assert_eq!(names(&view, "sandboxes"), ["x-sb@x"]);
assert_eq!(names(&view, "services"), ["x-svc@x"]);
assert_eq!(view["machines"].as_array().unwrap().len(), 1);
}
#[test]
fn merge_lifts_the_control_planes_view_and_a_direct_machine_wins() {
let local = serde_json::json!({"dir": "/here", "instances": [], "sandboxes": [], "services": []});
let mut params = control_plane_push();
let view = Arc::new(fleet_view(&mut params, Some("me")));
let mut k = machine("k", &["/k"], LinkState::Connected);
k.fleet = Some(Arc::clone(&view));
k.rows.insert("/k".into(), remote("/k", &[("control-plane-own", Some("/k"))]));
let merged = merge(&local, &[k.clone()], None, &Default::default(), &Default::default());
assert_eq!(names(&merged, "instances"), ["control-plane-own@k", "xi@x"]);
assert_eq!(names(&merged, "sandboxes"), ["sb-k@k", "x-sb@x"]);
assert_eq!(merged["sandbox_count"], 2);
let x = &merged["machines"][1];
assert_eq!((&x["name"], &x["via"], &x["target"], &x["command"], &x["agent"]), (&"x".into(), &"k".into(), &Value::Null, &Value::Null, &false.into()));
assert_eq!((&x["state"], &x["version"], &x["kind"]), (&"connected".into(), &"0.6.0".into(), &"routed".into()));
assert_eq!((&x["behind"], &x["behind_here"]), (&"its why".into(), &Value::Null));
assert_eq!(merged["machines"][0]["via"], Value::Null);
crate::serve::dts::assert_matches("SnapshotMachine", x);
assert_eq!((&merged["machines"][0]["exposed_by"], &x["exposed_by"]), (&Value::Null, &Value::Null));
let exposed = BTreeMap::from([("x".to_string(), vec!["k".to_string(), "x".to_string()]), ("k".to_string(), vec!["k".to_string()])]);
let merged = merge(&local, &[k.clone()], None, &exposed, &Default::default());
assert_eq!((&merged["machines"][0]["exposed_by"], &merged["machines"][1]["exposed_by"]), (&serde_json::json!(["k"]), &serde_json::json!(["k", "x"])));
let merged = merge(&local, &[k.clone()], None, &Default::default(), &BTreeSet::from(["k".to_string()]));
assert_eq!((&merged["machines"][0]["agent"], &merged["machines"][1]["agent"]), (&true.into(), &false.into()));
let merged = merge(&local, &[k.clone()], None, &Default::default(), &BTreeSet::from(["x".to_string()]));
assert_eq!((&merged["machines"][0]["agent"], &merged["machines"][1]["agent"]), (&false.into(), &true.into()));
let mut x = machine("x", &["/x"], LinkState::Connected);
x.rows.insert("/x".into(), remote("/x", &[("direct", Some("/x"))]));
let merged = merge(&local, &[k.clone(), x.clone()], None, &Default::default(), &Default::default());
assert_eq!(names(&merged, "instances"), ["control-plane-own@k", "direct@x"]);
assert_eq!(merged["machines"].as_array().unwrap().len(), 2);
assert_eq!(merged["machines"][1]["via"], Value::Null);
k.state = LinkState::Unreachable;
k.error = Some("k: ssh: no route".into());
let merged = merge(&local, &[k], None, &Default::default(), &Default::default());
assert_eq!(names(&merged, "instances"), ["control-plane-own@k", "xi@x"]);
assert_eq!((&merged["machines"][1]["state"], &merged["machines"][1]["error"]), (&"unreachable".into(), &"through k: ssh: no route".into()));
assert_eq!(merged["machines"][1]["behind"], Value::Null, "not connected: no one behind");
}
#[test]
fn behind_lasts_while_the_link_is_up() {
use crate::serve::fleet::update::Behind;
let behind = Behind { here: None, peer: Some("dev build: not taken".into()) };
let mut m = machine("m", &[], LinkState::Connecting);
assert!(m.set_up(behind.clone()), "connected, behind");
assert!(!m.set_up(behind.clone()), "no change");
assert!(m.set_up(Behind::default()), "no longer behind");
assert!(m.set_up(behind.clone()));
assert!(m.set_link(LinkState::Unreachable, Some("lost".into())));
assert_eq!(m.behind, Behind::default());
m.set_up(behind.clone());
assert!(!m.set_link(LinkState::Connected, None), "connected stays behind");
assert_eq!(m.behind, behind);
}
#[test]
fn routed_machines_come_from_the_graph_and_the_control_planes_view() {
let mut params = control_plane_push();
let view = Arc::new(fleet_view(&mut params, Some("me")));
let mut k = machine("k", &["/k"], LinkState::Connected);
k.fleet = Some(view);
let reach = vec![
("b".to_string(), Ok("k".to_string())),
("m".to_string(), Err("no path to `m` opened".to_string())),
("k".to_string(), Err("its link is down".to_string())),
];
let all = routed(reach.clone(), &[k.clone()]);
let names: Vec<&str> = all.iter().map(|r| r.name.as_str()).collect();
assert_eq!(names, ["b", "m", "x"], "k is a machine here");
assert_eq!((&all[0].via, all[0].state, &all[0].error), (&Some("k".into()), LinkState::Connected, &None));
assert_eq!((&all[1].via, all[1].state), (&None, LinkState::Unreachable));
let x = &all[2];
assert_eq!((&x.via, x.state, x.version.as_deref()), (&Some("k".into()), LinkState::Unreachable, Some("0.6.0")));
assert_eq!(x.error.as_deref(), Some("no path to `x` in this host's link graph"));
assert_eq!(x.roots, [PathBuf::from("/x")]);
let both = routed(vec![("x".into(), Ok("k".into()))], &[k]);
assert_eq!((both[0].state, &both[0].roots), (LinkState::Connected, &vec![PathBuf::from("/x")]));
}
#[test]
fn merge_leaves_the_asking_machine_out() {
let local = serde_json::json!({"dir": "/fleet/m", "instances": [{"name": "control-plane-own"}], "sandboxes": [], "services": []});
let mut m = machine("m", &["/m"], LinkState::Connected);
m.rows.insert("/m".into(), remote("/m", &[("mi", Some("/m"))]));
let mut x = machine("x", &["/x"], LinkState::Connected);
x.rows.insert("/x".into(), remote("/x", &[("xi", Some("/x"))]));
let merged = merge(&local, &[m.clone(), x.clone()], Some("m"), &Default::default(), &Default::default());
assert_eq!(names(&merged, "instances"), ["control-plane-own@-", "xi@x"]);
let entries: Vec<_> = merged["machines"].as_array().unwrap().iter().map(|e| e["name"].as_str().unwrap()).collect();
assert_eq!(entries, ["x"]);
}
#[test]
fn the_first_roots_snapshot_missing_drops_its_unregistered_instances_for_now() {
let mut a = machine("a", &["/r/one", "/r/two"], LinkState::Connecting);
a.rows.insert("/r/two".into(), remote("/r/two", &[("in-one", Some("/r/one")), ("in-two", Some("/r/two")), ("old", None)]));
let merged = merge(&serde_json::json!({"instances": [], "sandboxes": [], "services": []}), &[a], None, &Default::default(), &Default::default());
assert_eq!(names(&merged, "instances"), ["in-two@a"]);
}
#[test]
fn remotes_follow_the_registry() {
let remotes = Remotes::default();
remotes.sync(&[Entry::ssh("a", "a"), Entry::ssh("b", "b"), Entry::inbound("w")]);
let w = remotes.get("w").unwrap();
assert_eq!((w.kind, w.target), (MachineKind::Inbound, None));
assert_eq!(remotes.get("a").unwrap().target.as_deref(), Some("a"));
assert!(remotes.roots("a").is_empty(), "none until it lists");
remotes.update("a", |m| {
m.state = LinkState::Connected;
m.roots = vec!["/2".into(), "/1".into()];
m.rows.insert("/1".into(), Arc::new(Value::Null));
m.rows.insert("/2".into(), Arc::new(Value::Null));
});
remotes.update("nope", |_| panic!("not registered"));
remotes.sync(&[Entry { command: Some("ds".into()), ..Entry::ssh("a", "a") }]);
let all = remotes.all();
assert_eq!(all.len(), 1);
assert_eq!((all[0].state, all[0].rows.len(), all[0].command.as_deref()), (LinkState::Connected, 2, Some("ds")));
assert_eq!(remotes.roots("a"), [PathBuf::from("/2"), PathBuf::from("/1")]);
assert!(remotes.get("b").is_none() && remotes.roots("b").is_empty());
}
#[test]
fn a_disk_depth_remote_push_keeps_the_last_statuses() {
let unknown = |c: &str| serde_json::json!({"container": c, "status": {"state": "unknown"}, "cpu": null, "mem": null});
let prev = serde_json::json!({"instances": [
{"container": "a", "status": {"state": "running", "text": "Up"}, "cpu": "1%", "mem": "2MiB"},
{"container": "b", "status": {"state": "unknown"}, "cpu": null, "mem": null},
]});
let mut next = serde_json::json!({"instances": [unknown("a"), unknown("b"), unknown("new")]});
carry_remote_status(&prev, &mut next);
assert_eq!(next["instances"][0]["status"], serde_json::json!({"state": "running", "text": "Up"}));
assert_eq!((&next["instances"][0]["cpu"], &next["instances"][0]["mem"]), (&"1%".into(), &"2MiB".into()));
assert_eq!(next["instances"][1]["status"]["state"], "unknown");
assert_eq!(next["instances"][2]["status"]["state"], "unknown");
let mut real = serde_json::json!({"instances": [unknown("a"), {"container": "b", "status": {"state": "missing"}}]});
let want = real.clone();
carry_remote_status(&prev, &mut real);
assert_eq!(real, want);
}
fn view(depth: Depth) -> RuntimeView {
RuntimeView {
depth,
ps: Vec::new(),
stats: BTreeMap::new(),
runtime_name: "docker".into(),
runtime_version: None,
errors: Vec::new(),
at: Instant::now(),
no_runtime: false,
}
}
#[test]
fn collect_joins_watched_roots_caches_and_carries_over() {
let cache = Snapshots::default();
let (a, b) = (PathBuf::from("/cfg/a"), PathBuf::from("/cfg/b"));
let both: BTreeSet<PathBuf> = [a.clone(), b.clone()].into();
let join = |_: &Path, v: &RuntimeView| {
let full = v.depth == Depth::Full;
InstancesList {
snapshot: snapshot(vec![row("x", true, full.then_some("5%"))], full),
thread_children: Default::default(),
}
};
let t0 = Instant::now();
assert!(cache.stats_due(&both, t0), "fresh roots");
let first = view(Depth::Full);
let pushed = cache.collect(&first, &both, &join);
assert_eq!(pushed.iter().map(|(d, _)| d).collect::<Vec<_>>(), [&a, &b]);
assert_eq!(pushed[0].1["dir"], "/cfg/a");
assert_eq!(pushed[0].1["instances"][0]["cpu"], "5%");
assert!(!cache.stats_due(&both, first.at + Duration::from_secs(2)));
assert!(pushed[0].1.get("capacity").is_none(), "no capacity set yet");
let capacity = Capacity { cpus: Some(4), running: 1, ..Capacity::default() };
cache.set_capacity(&capacity);
let pushed = cache.collect(&view(Depth::Listing), &both, &join);
assert_eq!(pushed.len(), 2);
assert_eq!(pushed[1].1["instances"][0]["cpu"], "5%");
assert_eq!(cache.cached(&b).unwrap()["instances"][0]["cpu"], "5%");
assert_eq!(pushed[1].1["depth"], "full", "carried over: complete");
for (_, p) in &pushed {
assert_eq!(p["capacity"], serde_json::to_value(&capacity).unwrap());
}
assert_eq!(cache.cached(&a).unwrap()["capacity"]["cpus"], 4);
crate::serve::dts::assert_matches("Capacity", &pushed[0].1["capacity"]);
let c = PathBuf::from("/cfg/c");
let three: BTreeSet<PathBuf> = [a.clone(), c.clone()].into();
assert!(cache.stats_due(&three, first.at + Duration::from_secs(2)));
assert_eq!(cache.uncached(&three), [c.clone()].into());
cache.prune(&three);
cache.collect(&view(Depth::Listing), &three, &join);
assert_eq!(cache.cached(&c).unwrap()["depth"], "listing", "never had stats");
assert!(cache.cached(&b).is_none());
assert!(cache.cached(&c).is_some());
cache.prune(&BTreeSet::new());
assert!(cache.cached(&a).is_none());
}
}