diff options
| author | tv <tv@krebsco.de> | 2026-11-19 21:49:18 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-19 22:54:03 +0100 |
| commit | 4c2a4dfdb88fb008e0ba915047207efb8418ce77 (patch) | |
| tree | 7d550d6372a7ac38a65c7dea930c9474e949ac6a /src/federation | |
| parent | 5aa649bcb366ed6863732dac68ce081bacdbe4a8 (diff) | |
continuum-party status: everything but the values, in colour, and as JSON
`status` becomes the one place to look (party/status.rs): everything
about the federation at the node but the values, which `get` and
`values` read.
* the store: its ID, checkpoint, heads, what it took, its stop;
* the node: its party, whether it votes by itself, the revisions it knows;
* the version: number, hash, federation, revision, how many pass a change;
* every party: the keys its version names and its key set, --key's
marked, and its nodes, each with its name, how long ago the node heard
from it, and what it runs (wire versions, newest revision);
* every proposal on the current version: how it stands, who voted what
and who not yet, who proposed it and what it does (version_lines, as
`show` says it), what moving to its checkpoint refuses, why no client
backs it;
* what the node refused of its own;
* the party the client works as: its --key, its record held against the
node's votes, what `again` signs again;
* the warnings of what may keep votes away (cut_off).
It is built as one JSON object (`model`), which `--json` writes, its
`format` (FORMAT, 1) raised where it changes otherwise than by more
members; what people read is rendered from it (`render`), and may change
from release to release. On a terminal, in colour (Paint): true colour
where COLORTERM says so, 256 where TERM does, else the basic eight; none
with NO_COLOR, TERM=dumb, or off a terminal. What is fine is green, what
needs a look yellow, what is wrong red; headings and the shortest prefix
naming a proposal bold.
Diffstat (limited to 'src/federation')
| -rw-r--r-- | src/federation/party.rs | 343 | ||||
| -rw-r--r-- | src/federation/party/status.rs | 894 |
2 files changed, 914 insertions, 323 deletions
diff --git a/src/federation/party.rs b/src/federation/party.rs index 29d9cb8..e030048 100644 --- a/src/federation/party.rs +++ b/src/federation/party.rs @@ -35,8 +35,8 @@ //! twice; //! * `proposals`: the proposals on the current version at the node, each with whether it //! passed or is dead, who voted what, and what its version changes (`client::changes`); -//! * `status`: the store, its version and parties, the party's keys and nodes, the node, -//! the proposals, the versions the node refused of its own, what to sign again; +//! * `status`: everything about the federation at the node but the values (`status`); +//! with `--json`, as one JSON object of a versioned format; //! * `values [PATH]`: the values that count, all or under `PATH`, with who writes there; //! * `get [PATH]`: what counts at `PATH` as one JSON value (`tree`): a place's, or what lies //! under it, places and the values within theirs; with `-r`, a string as it is; @@ -81,6 +81,8 @@ use super::version::Version; use crate::access::sshsig::PublicKey; use crate::config; +mod status; + /// The client's options (`config::PARTY_OPTIONS`), as the command line and configuration /// files set them. #[derive(Deserialize)] @@ -284,10 +286,21 @@ fn command() -> Command { .subcommand(Command::new("proposals").about( "The proposals on the current version, each as show says it", )) - .subcommand(Command::new("status").about( - "The store, its version and parties, the party's keys and nodes, the node, the \ - proposals on the current version, and what the party has to sign again", - )) + .subcommand( + Command::new("status") + .about( + "Everything about the federation at the node but the values: the store, the \ + node, the version, every party's keys and nodes, the proposals and what \ + each does, what the node refused, and the party's own key, record and \ + what it signs again", + ) + .arg( + Arg::new("json") + .long("json") + .action(ArgAction::SetTrue) + .help("As one JSON object, of a format versioned by its `format`"), + ), + ) .subcommand( Command::new("get") .about( @@ -679,7 +692,7 @@ pub(crate) async fn main() -> Result<()> { return proposals(&node).await; } if name == "status" { - return status(&node, &options, party.as_deref()).await; + return status::status(&node, &options, party.as_deref(), sub.get_flag("json")).await; } if name == "values" { return values(&node, sub).await; @@ -1817,186 +1830,6 @@ fn working_as(name: &str, sub: &ArgMatches, options: &Options) -> Result<Option< } } -/// What the node and the party's record say at a glance: the store, its checkpoint and -/// heads; the current version, its federation and revision, and its parties; the party's -/// keys and node list as they count, and whether the version names `--key`; the node's -/// party, whether it votes for it by itself, and where it stopped; the proposals on the -/// current version, each as `show` begins; the versions the node refused of its own; and -/// what a move refused that the party signs again (`again`). -async fn status(node: &Node, options: &Options, party: Option<&str>) -> Result<()> { - let summary = node.get("/events").await?; - let counts = node.counts().await?; - let current = current(&counts)?; - let text = |value: &JsonValue| value.as_str().unwrap_or_default().to_owned(); - let plural = - |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); - let heads = summary["heads"].as_array().map_or(0, Vec::len); - println!("store {}", text(&summary["store"])); - println!(" checkpoint {}", text(&summary["checkpoint"])); - println!( - " {}, {} taken after the checkpoint", - plural(heads, "head", "heads"), - plural( - summary["taken"].as_u64().unwrap_or_default() as usize, - "event", - "events" - ) - ); - let needed = (2 * current.parties.len()).div_ceil(3); - println!("version {} ({})", current.number, current.hash); - println!( - " federation {}, {}", - counts["version"]["version"]["federation"], current.revision - ); - println!( - " {}, {needed} passing a change:", - plural(current.parties.len(), "party", "parties") - ); - for party in current.parties.keys() { - println!(" {party}"); - } - let record = options - .record - .as_ref() - .map(PathBuf::from) - .filter(|path| path.exists()) - .map(|path| Record::load(&path).map_err(|why| anyhow!(why))) - .transpose()?; - let party = party - .map(str::to_owned) - .or_else(|| summary["party"].as_str().map(str::to_owned)); - if let Some(party) = &party { - println!("{party}"); - match current.parties.get(party) { - None => println!(" no party of version {}", current.number), - Some(given) => { - for line in party_lines(&counts, party, &given.keys, options.key.as_deref()) { - println!(" {line}"); - } - } - } - } - let by_itself = if summary["votesByItself"].as_bool() == Some(true) { - ", voting for it by itself" - } else { - "" - }; - match summary["party"].as_str() { - Some(of) => println!("the node: {of}'s{by_itself}"), - None => println!("the node: of no party"), - } - if let Some(stopped) = summary["stopped"].as_object() { - println!( - " stopped at {}: {}", - stopped - .get("id") - .and_then(JsonValue::as_str) - .unwrap_or_default(), - stopped - .get("why") - .and_then(JsonValue::as_str) - .unwrap_or_default() - ); - } - let hashes = proposal_hashes(&counts); - match hashes.len() { - 0 => println!("no proposal on version {}", current.number), - 1 => println!("1 proposal on version {} (show says more):", current.number), - n => println!( - "{n} proposals on version {} (show says more):", - current.number - ), - } - for hash in &hashes { - println!(" {}", ballot_line(&counts, ¤t, hash, &hashes)); - } - let refused = node.get("/events/refused").await?; - let own = refused["own"].as_array().map_or(0, Vec::len); - if own > 0 { - println!( - "the node refused {own} version event{} by what it took before: keys may have \ - voted twice, and nodes be apart (GET /events/refused)", - if own == 1 { "" } else { "s" } - ); - } - if let Some(record) = &record { - let moved: BTreeSet<Id> = refused["refused"] - .as_array() - .into_iter() - .flatten() - .filter(|entry| matches!(entry["kind"].as_str(), Some("notAbove" | "builtOn"))) - .filter_map(|entry| entry["id"].as_str().and_then(Id::from_hex)) - .collect(); - let again = record.again(|id| moved.contains(id)).len(); - if again > 0 { - println!( - "{} of {}'s latest events a move refused: `again` signs {} again", - again, - record.party, - if again == 1 { "it" } else { "them" } - ); - } - } - Ok(()) -} - -/// A party's keys and nodes, as `status` says them under its name, a line each, indented -/// beneath their heading: the keys the version names (`named`), which sign its votes, -/// proposals, key set and node list; those of its key set as it counts (`counts`), which -/// sign its writes; each by its fingerprint, `--key`'s (`given`) marked, and said where -/// it is neither; and its nodes as they count, by ID, each with the name it gave itself -/// where it did. -fn party_lines( - counts: &JsonValue, - party: &str, - named: &[String], - given: Option<&str>, -) -> Vec<String> { - let given = given.and_then(|given| match given_key(given).ok()? { - Given::Private(key) => Some(PublicKey(key.verifying_key().to_bytes()).line()), - Given::Public(key, _) => Some(key.line()), - }); - let key_line = |key: &String| { - let mark = if given.as_ref() == Some(key) { - " (--key)" - } else { - "" - }; - format!(" {}{mark}", client::fingerprint(key)) - }; - let set = listed(counts, party, "keys"); - let mut lines = - vec!["keys the version names (votes, proposals, key set, node list):".to_owned()]; - lines.extend(named.iter().map(key_line)); - if set == named { - lines.push("keys of its key set (writes): the same".to_owned()); - } else { - lines.push("keys of its key set (writes):".to_owned()); - lines.extend(set.iter().map(key_line)); - } - if let Some(given) = &given - && !named.contains(given) - && !set.contains(given) - { - lines.push(format!( - "--key, {}, is none of these: it signs nothing for {party}", - client::fingerprint(given) - )); - } - let nodes = listed(counts, party, "nodes"); - if nodes.is_empty() { - lines.push("nodes: none".to_owned()); - } else { - lines.push("nodes:".to_owned()); - } - let names = &counts["parties"][party]["names"]; - lines.extend(nodes.iter().map(|node| match names[node].as_str() { - Some(name) => format!(" {node} ({name})"), - None => format!(" {node}"), - })); - lines -} - /// The values that count, all or under the place `path` names (and it), each with who /// writes there, a line each: `PATH VALUE (WRITER)`, the value as JSON; or with `--json`, /// one JSON object of them, by place. @@ -3214,142 +3047,6 @@ mod tests { assert_eq!(working_as(&["status"], None, None).unwrap(), None); } - /// `status` says a party's keys and nodes a line each: the version's, its key set's - /// where they differ, `--key`'s marked, and each node with the name it gave itself. - #[test] - fn a_partys_keys_and_nodes_a_line_each() { - use crate::federation::client::fingerprint; - use crate::federation::harness::{key_line, node_id}; - let (named, laptop) = (key_line(1), key_line(2)); - let counts = serde_json::json!({"parties": {"tv": { - "keys": [laptop], - "nodes": [node_id(1), node_id(2)], - "names": {node_id(1): "alpha"}, - }}}); - let dir = crate::files::scratch_dir("party-lines"); - let given = dir.join("laptop.pub"); - std::fs::write(&given, format!("{laptop} tv@laptop\n")).unwrap(); - let lines = super::party_lines(&counts, "tv", std::slice::from_ref(&named), given.to_str()); - assert_eq!( - lines, - [ - "keys the version names (votes, proposals, key set, node list):".to_owned(), - format!(" {}", fingerprint(&named)), - "keys of its key set (writes):".to_owned(), - format!(" {} (--key)", fingerprint(&laptop)), - "nodes:".to_owned(), - format!(" {} (alpha)", node_id(1)), - format!(" {}", node_id(2)), - ] - ); - let lines = super::party_lines(&counts, "tv", std::slice::from_ref(&laptop), None); - assert_eq!(lines[2], "keys of its key set (writes): the same"); - } - - /// `get` reads what counts as JSON: a place's value; what lies under a path, places and - /// the values within theirs, as one object; a list's item by its index; a deeper place - /// winning over what a value above it held there. - #[test] - fn what_counts_as_json() { - use serde_json::json; - let values = json!({ - "home/tv/motd": "hello", - "home/tv/hosts/laptop": {"ip6": "42::1", "ports": [22, 80]}, - "home/tv/hosts": {"desk": {"ip6": "42::2"}, "laptop": {"ip6": "old"}}, - "home/lass/motd": "hi", - "home/tvx/motd": "beside", - }); - let values = values.as_object().unwrap(); - let get = |path: &str| super::at(&super::tree(values, path), path).cloned(); - assert_eq!(get("home/tv/motd"), Some(json!("hello"))); - assert_eq!( - get("home/tv"), - Some(json!({ - "motd": "hello", - "hosts": { - "desk": {"ip6": "42::2"}, - "laptop": {"ip6": "42::1", "ports": [22, 80]}, - }, - })) - ); - assert_eq!(get("home/tv/hosts/desk/ip6"), Some(json!("42::2"))); - assert_eq!(get("home/tv/hosts/laptop/ports/1"), Some(json!(80))); - assert_eq!(get("home/tv/hosts/laptop/ports/2"), None); - assert_eq!(get("home/tv/elsewhere"), None); - assert_eq!(get("home").unwrap()["lass"], json!({"motd": "hi"})); - assert_eq!(get("").unwrap()["home"]["tvx"]["motd"], "beside"); - } - - /// Before a vote, the party's votes the node shows are held against the record's: one - /// the node shows that the record lacks refuses the vote, one the record holds that - /// the node doesn't show is said; nothing where they agree. - #[test] - fn a_record_held_against_the_votes_a_node_shows() { - use crate::federation::client::Record; - use crate::federation::harness::{Party, Spec}; - use crate::federation::store::Id; - use crate::federation::version::Version; - let (tv, lass) = (Party::new("tv", 1), Party::new("lass", 2)); - let first = Spec::first(&[&tv, &lass], &[]); - let current = Version::read(&first.json()).unwrap(); - let (one, two) = (Id::of(b"one"), Id::of(b"two")); - let mut record = Record::before(Id::of(b"root"), "tv"); - record.cast( - ¤t, - &tv.vote(&[Id::of(b"root")], first.hash(), one, true), - Vec::new(), - ); - let counts = |yes_one: &[&str], no_two: &[&str]| { - serde_json::json!({"proposals": { - one.to_string(): {"yes": yes_one, "no": []}, - two.to_string(): {"yes": [], "no": no_two}, - }}) - }; - let agreeing = counts(&["tv", "lass"], &[]); - assert_eq!( - super::unrecorded(&agreeing, ¤t, &record), - (Vec::new(), Vec::new()) - ); - assert!(super::consistent(&agreeing, ¤t, &record).is_ok()); - let elsewhere = counts(&["tv"], &["tv"]); - let (theirs, ours) = super::unrecorded(&elsewhere, ¤t, &record); - assert_eq!(theirs.len(), 1); - assert!(theirs[0].starts_with("`false` on "), "{theirs:?}"); - assert!(ours.is_empty()); - assert!(super::consistent(&elsewhere, ¤t, &record).is_err()); - let behind = counts(&["lass"], &[]); - let (theirs, ours) = super::unrecorded(&behind, ¤t, &record); - assert!(theirs.is_empty()); - assert_eq!(ours.len(), 1); - assert!(super::consistent(&behind, ¤t, &record).is_ok()); - } - - /// What may keep a vote from the node: the party's own nodes not heard from lately; - /// and parties none of whose nodes were, where they are a third of those with nodes. - #[test] - fn nodes_cut_off_are_said() { - let ago = super::LATELY + 1; - let counts = |lass_heard: Option<u64>| { - let lass = match lass_heard { - Some(ago) => serde_json::json!({"n3": ago}), - None => serde_json::json!({}), - }; - serde_json::json!({"parties": { - "tv": {"nodes": ["n1", "n2"], "names": {"n2": "beta"}, "heard": {"n1": 0, "n2": ago}}, - "lass": {"nodes": ["n3"], "names": {}, "heard": lass}, - "makefu": {"nodes": ["n4"], "names": {}, "heard": {"n4": 3}}, - "krebs": {"nodes": [], "names": {}, "heard": {}}, - }}) - }; - let lines = super::cut_off(&counts(Some(10)), "tv"); - assert_eq!(lines.len(), 1); - assert!(lines[0].contains("n2 (beta)"), "{lines:?}"); - let lines = super::cut_off(&counts(None), "makefu"); - assert_eq!(lines.len(), 1); - assert!(lines[0].contains("any node of lass"), "{lines:?}"); - assert!(super::cut_off(&counts(Some(10)), "makefu").is_empty()); - } - /// `values` shows a place and those under it, not those beside it. #[test] fn places_under_a_path() { diff --git a/src/federation/party/status.rs b/src/federation/party/status.rs new file mode 100644 index 0000000..2428845 --- /dev/null +++ b/src/federation/party/status.rs @@ -0,0 +1,894 @@ +//! `continuum-party status`: everything about the federation at a node but the values +//! (`values`, `get`). The store; the node; the current version; every party's keys and +//! nodes, when the node last heard from each and what each runs; the proposals on the +//! current version, how they stand and what each does; what the node refused of its own; +//! and the party the client works as: its key, its record against the node, what it signs +//! again; with what may keep votes away. +//! +//! As people read it, in colours on a terminal (`Paint`), which may change from release to +//! release; with `--json`, the same as one JSON object (`model`), of a format versioned by +//! its `format` (`FORMAT`). + +use std::collections::BTreeSet; +use std::path::Path; + +use anyhow::{Result, anyhow}; +use serde_json::{Value as JsonValue, json}; + +use super::{ + Given, LATELY, Node, Options, current, cut_off, given_key, listed, proposal_hashes, unrecorded, + version_lines, +}; +use crate::access::sshsig::PublicKey; +use crate::federation::client::{self, Record}; +use crate::federation::event::{Does, Event, Signed}; +use crate::federation::store::Id; +use crate::federation::version::Version; + +/// The version of `--json`'s format: raised with every change to it that isn't an +/// addition. +pub(super) const FORMAT: u64 = 1; + +/// Says what the node and the party's record say, as people read it or with `json` as one +/// JSON object; of `party`, where the client works as one (else the node's). +pub(super) async fn status( + node: &Node, + options: &Options, + party: Option<&str>, + json: bool, +) -> Result<()> { + let model = model(node, options, party).await?; + if json { + println!("{}", serde_json::to_string_pretty(&model)?); + return Ok(()); + } + for line in render(&model, &Paint::detect()) { + println!("{line}"); + } + Ok(()) +} + +/// What `status` says, as one JSON object of `FORMAT`. +async fn model(node: &Node, options: &Options, party: Option<&str>) -> Result<JsonValue> { + let summary = node.get("/events").await?; + let counts = node.counts().await?; + let refused = node.get("/events/refused").await?; + let current = current(&counts)?; + let needed = (2 * current.parties.len()).div_ceil(3); + let parties: serde_json::Map<String, JsonValue> = current + .parties + .iter() + .map(|(name, given)| { + let of = &counts["parties"][name]; + let nodes: Vec<JsonValue> = listed(&counts, name, "nodes") + .iter() + .map(|id| { + json!({ + "id": id, + "name": of["names"][id], + "heard": of["heard"][id], + "knows": of["knows"][id], + }) + }) + .collect(); + ( + name.clone(), + json!({ + "keys": given.keys, + "keySet": listed(&counts, name, "keys"), + "nodes": nodes, + }), + ) + }) + .collect(); + let mut proposals = Vec::new(); + for hash in proposal_hashes(&counts) { + proposals.push(proposal(node, &counts, ¤t, &hash).await?); + } + let revisions: Vec<&JsonValue> = summary["revisions"] + .as_array() + .into_iter() + .flatten() + .map(|revision| &revision["named"]) + .collect(); + let party = party + .map(str::to_owned) + .or_else(|| summary["party"].as_str().map(str::to_owned)); + let you = match &party { + Some(party) => Some(you(&counts, ¤t, &refused, options, party)?), + None => None, + }; + let warnings = party + .as_deref() + .map(|party| cut_off(&counts, party)) + .unwrap_or_default(); + Ok(json!({ + "format": FORMAT, + "store": { + "id": summary["store"], + "checkpoint": summary["checkpoint"], + "heads": summary["heads"].as_array().map_or(0, Vec::len), + "taken": summary["taken"], + "stopped": summary["stopped"], + }, + "node": { + "party": summary["party"], + "votesByItself": summary["votesByItself"], + "revisions": revisions, + }, + "version": { + "number": current.number, + "hash": current.hash.to_string(), + "federation": counts["version"]["version"]["federation"], + "revision": counts["version"]["revision"], + "parties": current.parties.len(), + "needed": needed, + }, + "parties": parties, + "proposals": proposals, + "refused": {"own": refused["own"]}, + "you": you, + "warnings": warnings, + })) +} + +/// The proposal of `hash` on `current`, as `counts` reads it and the event proposing it +/// says: how it stands (`open`, `passed`, `dead`), how many more `true` pass it, who voted +/// what and who not yet; who proposed it and what its version does (`version_lines`); of +/// a checkpoint, how much moving there refuses; why no client backs it, where none does. +async fn proposal( + node: &Node, + counts: &JsonValue, + current: &Version, + hash: &str, +) -> Result<JsonValue> { + let ballot = &counts["proposals"][hash]; + let names = |what: &str| -> Vec<String> { + ballot[what] + .as_array() + .into_iter() + .flatten() + .filter_map(|party| party.as_str().map(str::to_owned)) + .collect() + }; + let (yes, no) = (names("yes"), names("no")); + let not_yet: Vec<&String> = current + .parties + .keys() + .filter(|party| !yes.contains(party) && !no.contains(party)) + .collect(); + let standing = if ballot["passed"].as_bool() == Some(true) { + "passed" + } else if ballot["dead"].as_bool() == Some(true) { + "dead" + } else { + "open" + }; + let needed = (2 * current.parties.len()).div_ceil(3); + let mut model = json!({ + "hash": hash, + "standing": standing, + "needed": needed, + "more": needed.saturating_sub(yes.len()), + "yes": yes, + "no": no, + "notYet": not_yet, + "proposedBy": null, + "number": null, + "does": [], + "beside": ballot["beside"].as_array().map(Vec::len), + "none": ballot["none"], + }); + let Some(id) = ballot["proposals"][0].as_str().and_then(Id::from_hex) else { + return Ok(model); + }; + if let Some(Event::Signed(Signed { + party, + does: Does::Proposal { hash: of, version }, + .. + })) = Event::read(&node.event(&id).await?) + && of.to_string() == hash + { + model["proposedBy"] = party.into(); + match client::backable(current, &version) { + Ok(proposed) => { + model["number"] = proposed.number.into(); + model["does"] = version_lines(counts, current, &proposed).into(); + } + Err(why) => model["none"] = why.into(), + } + } + Ok(model) +} + +/// The party the client works as: its `--key`, whether the version names it or it is of +/// the party's key set; its record held against the node's votes (`unrecorded`); and how +/// many of its latest events a move refused, which `again` signs again. +fn you( + counts: &JsonValue, + current: &Version, + refused: &JsonValue, + options: &Options, + party: &str, +) -> Result<JsonValue> { + let key = options + .key + .as_deref() + .and_then(|given| given_key(given).ok()) + .map(|given| match given { + Given::Private(key) => PublicKey(key.verifying_key().to_bytes()).line(), + Given::Public(key, _) => key.line(), + }); + let named = current + .parties + .get(party) + .map(|given| given.keys.clone()) + .unwrap_or_default(); + let set = listed(counts, party, "keys"); + let record = options + .record + .as_deref() + .map(Path::new) + .filter(|path| path.exists()) + .map(|path| Record::load(path).map(|record| (path, record))) + .transpose() + .map_err(|why| anyhow!(why))? + .filter(|(_, record)| record.party == party); + let moved: BTreeSet<Id> = refused["refused"] + .as_array() + .into_iter() + .flatten() + .filter(|entry| matches!(entry["kind"].as_str(), Some("notAbove" | "builtOn"))) + .filter_map(|entry| entry["id"].as_str().and_then(Id::from_hex)) + .collect(); + Ok(json!({ + "party": party, + "isParty": current.parties.contains_key(party), + "key": key.map(|line| json!({ + "key": line, + "named": named.contains(&line), + "inKeySet": set.contains(&line), + })), + "record": record.as_ref().map(|(path, record)| { + let (theirs, ours) = unrecorded(counts, current, record); + json!({ + "path": path.display().to_string(), + "agrees": theirs.is_empty(), + "unrecorded": theirs, + "notShown": ours, + }) + }), + "again": record + .as_ref() + .map(|(_, record)| record.again(|id| moved.contains(id)).len()), + })) +} + +/// How many colours the terminal shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Colours { + None, + /// The eight of ANSI, bright or not. + Basic, + Ansi256, + True, +} + +/// What a part of what `status` says is, for its colour. +#[derive(Clone, Copy, Debug)] +enum Style { + /// A section's heading. + Heading, + Party, + /// A node's name. + Name, + /// An ID or a hash. + Id, + Good, + Warn, + Bad, + /// Nothing there: `nobody`, `none`. + Quiet, +} + +/// Colours for a terminal of so many (`Colours`). +struct Paint(Colours); + +impl Paint { + /// As standard output shows them: none where it is no terminal, `NO_COLOR` is set, or + /// `TERM` is `dumb`; true colour where `COLORTERM` says so; 256 where `TERM` does; + /// else the basic eight. + fn detect() -> Paint { + use std::io::IsTerminal; + let var = |name: &str| std::env::var(name).unwrap_or_default(); + let colours = if !std::io::stdout().is_terminal() + || std::env::var_os("NO_COLOR").is_some_and(|value| !value.is_empty()) + || var("TERM") == "dumb" + { + Colours::None + } else if matches!(var("COLORTERM").as_str(), "truecolor" | "24bit") { + Colours::True + } else if var("TERM").contains("256color") { + Colours::Ansi256 + } else { + Colours::Basic + }; + Paint(colours) + } + + /// The SGR parameters of `style`, as this terminal shows colours. + fn code(&self, style: Style) -> &'static str { + use Colours::{Ansi256, Basic, None, True}; + match (self.0, style) { + (None, _) => "", + (_, Style::Heading) => "1", + (True, Style::Party) => "1;38;2;95;175;215", + (Ansi256, Style::Party) => "1;38;5;74", + (Basic, Style::Party) => "1;36", + (True, Style::Name) => "38;2;95;175;215", + (Ansi256, Style::Name) => "38;5;74", + (Basic, Style::Name) => "36", + (True, Style::Id) => "38;2;138;138;138", + (Ansi256, Style::Id) => "38;5;245", + (Basic, Style::Id) => "90", + (True, Style::Good) => "38;2;95;175;95", + (Ansi256, Style::Good) => "38;5;71", + (Basic, Style::Good) => "32", + (True, Style::Warn) => "38;2;215;175;95", + (Ansi256, Style::Warn) => "38;5;179", + (Basic, Style::Warn) => "33", + (True, Style::Bad) => "1;38;2;215;95;95", + (Ansi256, Style::Bad) => "1;38;5;167", + (Basic, Style::Bad) => "1;31", + (_, Style::Quiet) => "2", + } + } + + fn paint(&self, style: Style, text: &str) -> String { + match self.code(style) { + "" => text.to_owned(), + code => format!("\x1b[{code}m{text}\x1b[0m"), + } + } + + /// `hash`, its first `length` digits, which name it among those shown, in bold. + fn marked(&self, hash: &str, length: usize) -> String { + let (named, rest) = hash.split_at(length.min(hash.len())); + format!( + "{}{}", + self.paint(Style::Heading, named), + self.paint(Style::Id, rest) + ) + } +} + +/// `n` and `one` or `many`, as `n` asks. +fn counted(n: u64, one: &str, many: &str) -> String { + format!("{n} {}", if n == 1 { one } else { many }) +} + +/// How long ago, in seconds, said: `12 s ago`, `4 min ago`, `3 h ago`, `2 d ago`. +fn ago(seconds: u64) -> String { + match seconds { + 0..120 => format!("{seconds} s ago"), + 120..7200 => format!("{} min ago", seconds / 60), + 7200..172_800 => format!("{} h ago", seconds / 3600), + _ => format!("{} d ago", seconds / 86_400), + } +} + +/// What a node said it runs (`knows`, `speaking::shown`): its wire versions and the +/// newest revision it knows. +fn runs(knows: &JsonValue) -> Option<String> { + let wire = knows["wire"].as_array()?; + let (oldest, newest) = (wire.first()?.as_u64()?, wire.last()?.as_u64()?); + let wire = if oldest == newest { + format!("wire {newest}") + } else { + format!("wire {oldest} to {newest}") + }; + Some(match knows["revision"]["named"].as_str() { + Some(revision) => format!("{wire}; {revision}"), + None => format!("{wire}; no federation"), + }) +} + +/// Names `list` holds, by `, `; `nobody` where it holds none. +fn names(paint: &Paint, list: &JsonValue) -> String { + let names: Vec<String> = list + .as_array() + .into_iter() + .flatten() + .filter_map(JsonValue::as_str) + .map(|name| paint.paint(Style::Party, name)) + .collect(); + if names.is_empty() { + paint.paint(Style::Quiet, "nobody") + } else { + names.join(", ") + } +} + +/// `model` as people read it, a line each, its parts in colours by `paint`. +fn render(model: &JsonValue, paint: &Paint) -> Vec<String> { + let mut out = Vec::new(); + let heading = |text: &str| paint.paint(Style::Heading, text); + let text = |value: &JsonValue| value.as_str().unwrap_or_default().to_owned(); + let number = |value: &JsonValue| value.as_u64().unwrap_or_default(); + + let store = &model["store"]; + out.push(format!( + "{} {}", + heading("store"), + paint.paint(Style::Id, &text(&store["id"])) + )); + out.push(format!( + " checkpoint {}", + paint.paint(Style::Id, &text(&store["checkpoint"])) + )); + out.push(format!( + " {}, {} taken after the checkpoint", + counted(number(&store["heads"]), "head", "heads"), + counted(number(&store["taken"]), "event", "events") + )); + if store["stopped"].is_object() { + out.push(format!( + " {}", + paint.paint( + Style::Bad, + &format!( + "stopped at {}: {}", + text(&store["stopped"]["id"]), + text(&store["stopped"]["why"]) + ) + ) + )); + } + + let node = &model["node"]; + out.push(heading("the node")); + out.push(match node["party"].as_str() { + Some(party) => format!( + " {}'s{}", + paint.paint(Style::Party, party), + if node["votesByItself"].as_bool() == Some(true) { + ", voting for it by itself" + } else { + "" + } + ), + None => format!(" {}", paint.paint(Style::Quiet, "of no party")), + }); + let revisions: Vec<String> = node["revisions"] + .as_array() + .into_iter() + .flatten() + .map(text) + .collect(); + out.push(format!(" knows {}", revisions.join(", "))); + + let version = &model["version"]; + out.push(format!( + "{} {} ({})", + heading("version"), + number(&version["number"]), + paint.paint(Style::Id, &text(&version["hash"])) + )); + out.push(format!( + " federation {}, {}", + version["federation"], + text(&version["revision"]["named"]) + )); + out.push(format!( + " {}, {} passing a change", + counted(number(&version["parties"]), "party", "parties"), + number(&version["needed"]) + )); + + let key = model["you"]["key"]["key"].as_str(); + out.push(heading("parties")); + for (name, party) in model["parties"].as_object().into_iter().flatten() { + out.push(format!(" {}", paint.paint(Style::Party, name))); + let key_line = |line: &JsonValue| { + let line = text(line); + let mark = if key == Some(line.as_str()) { + format!(" {}", paint.paint(Style::Good, "(--key)")) + } else { + String::new() + }; + format!(" {}{mark}", client::fingerprint(&line)) + }; + out.push(" keys the version names (votes, proposals, key set, node list):".to_owned()); + out.extend(party["keys"].as_array().into_iter().flatten().map(key_line)); + if party["keySet"] == party["keys"] { + out.push(" keys of its key set (writes): the same".to_owned()); + } else { + out.push(" keys of its key set (writes):".to_owned()); + out.extend( + party["keySet"] + .as_array() + .into_iter() + .flatten() + .map(key_line), + ); + } + let nodes = party["nodes"].as_array().cloned().unwrap_or_default(); + if nodes.is_empty() { + out.push(format!(" nodes: {}", paint.paint(Style::Quiet, "none"))); + } else { + out.push(" nodes:".to_owned()); + } + for node in &nodes { + let name = match node["name"].as_str() { + Some(name) => format!(" ({})", paint.paint(Style::Name, name)), + None => String::new(), + }; + out.push(format!( + " {}{name}", + paint.paint(Style::Id, &text(&node["id"])) + )); + let heard = match node["heard"].as_u64() { + Some(0) => paint.paint(Style::Good, "this node"), + Some(seconds) if seconds <= LATELY => { + paint.paint(Style::Good, &format!("heard {}", ago(seconds))) + } + Some(seconds) => paint.paint(Style::Warn, &format!("heard {}", ago(seconds))), + None => paint.paint(Style::Bad, "not heard from since the node started"), + }; + let runs = runs(&node["knows"]) + .map(|runs| format!("; {runs}")) + .unwrap_or_else(|| { + format!( + "; {}", + paint.paint(Style::Quiet, "said nothing of what it runs") + ) + }); + out.push(format!(" {heard}{runs}")); + } + } + + let proposals = model["proposals"].as_array().cloned().unwrap_or_default(); + let on = number(&version["number"]); + if proposals.is_empty() { + out.push(format!( + "{} on version {on}: {}", + heading("proposals"), + paint.paint(Style::Quiet, "none") + )); + } else { + out.push(format!("{} on version {on}", heading("proposals"))); + } + let hashes: Vec<String> = proposals.iter().map(|p| text(&p["hash"])).collect(); + let hashes: Vec<&str> = hashes.iter().map(String::as_str).collect(); + let lengths = client::prefixes(&hashes); + for (proposal, length) in proposals.iter().zip(lengths) { + let standing = match proposal["standing"].as_str() { + Some("passed") => paint.paint(Style::Good, "passed"), + Some("dead") => paint.paint(Style::Bad, "dead"), + _ => paint.paint( + Style::Warn, + &format!( + "can still pass, {} more `true` passing it ({} of {})", + number(&proposal["more"]), + number(&proposal["needed"]), + number(&version["parties"]) + ), + ), + }; + out.push(format!( + " {}: {standing}", + paint.marked(&text(&proposal["hash"]), length) + )); + out.push(format!( + " true: {}; false: {}; not yet: {}", + names(paint, &proposal["yes"]), + names(paint, &proposal["no"]), + names(paint, &proposal["notYet"]) + )); + if let Some(by) = proposal["proposedBy"].as_str() { + match proposal["number"].as_u64() { + Some(number) => out.push(format!( + " proposed by {}: version {number} on {on}", + paint.paint(Style::Party, by) + )), + None => out.push(format!(" proposed by {}", paint.paint(Style::Party, by))), + } + } + for line in proposal["does"].as_array().into_iter().flatten() { + out.push(format!(" {}", text(line))); + } + match proposal["beside"].as_u64() { + Some(0) => out.push(" moving there refuses nothing this node took".to_owned()), + Some(n) => out.push(format!( + " {}", + paint.paint( + Style::Warn, + &format!( + "moving there refuses {n} of the writes, key sets and node lists this \ + node took, which their parties sign again" + ) + ) + )), + None => {} + } + if let Some(why) = proposal["none"].as_str() { + out.push(format!( + " {}", + paint.paint(Style::Bad, &format!("backed by no client: {why}")) + )); + } + } + + out.push(heading("refused")); + match model["refused"]["own"].as_array().map_or(0, Vec::len) { + 0 => out.push(format!( + " {}", + paint.paint(Style::Good, "no version event of its own") + )), + n => out.push(format!( + " {}", + paint.paint( + Style::Bad, + &format!( + "{} by what the node took before: keys may have voted twice, and nodes be \ + apart (GET /events/refused)", + counted(n as u64, "version event", "version events") + ) + ) + )), + } + + let you = &model["you"]; + if let Some(party) = you["party"].as_str() { + out.push(format!( + "{} {}", + heading("you:"), + paint.paint(Style::Party, party) + )); + if you["isParty"].as_bool() != Some(true) { + out.push(format!( + " {}", + paint.paint(Style::Bad, &format!("no party of version {on}")) + )); + } + if let Some(line) = you["key"]["key"].as_str() { + let (style, what) = match ( + you["key"]["named"].as_bool() == Some(true), + you["key"]["inKeySet"].as_bool() == Some(true), + ) { + (true, true) => ( + Style::Good, + "the version names it, and it is of the key set", + ), + (true, false) => ( + Style::Good, + "the version names it: votes, proposals, key set, node list", + ), + (false, true) => (Style::Good, "of the key set: writes"), + (false, false) => (Style::Bad, "none of the party's keys: it signs nothing"), + }; + out.push(format!( + " --key {}: {}", + client::fingerprint(line), + paint.paint(style, what) + )); + } + let record = &you["record"]; + match record["path"].as_str() { + None => out.push(format!( + " {}", + paint.paint(Style::Quiet, "no record: reading only, as votes go by one") + )), + Some(path) => { + let unrecorded: Vec<String> = record["unrecorded"] + .as_array() + .into_iter() + .flatten() + .map(text) + .collect(); + if unrecorded.is_empty() { + out.push(format!( + " record {path}: {}", + paint.paint(Style::Good, "agrees with the node") + )); + } else { + out.push(format!( + " record {path}: {}", + paint.paint( + Style::Bad, + &format!( + "lacks votes the node shows: {}: `restore` takes them in", + unrecorded.join(", ") + ) + ) + )); + } + let not_shown: Vec<String> = record["notShown"] + .as_array() + .into_iter() + .flatten() + .map(text) + .collect(); + if !not_shown.is_empty() { + out.push(format!( + " {}", + paint.paint( + Style::Warn, + &format!( + "the node doesn't show the record's {} yet", + not_shown.join(", ") + ) + ) + )); + } + } + } + if let Some(again) = you["again"].as_u64().filter(|again| *again > 0) { + out.push(format!( + " {}", + paint.paint( + Style::Warn, + &format!( + "{} a move refused: `again` signs {} again", + counted(again, "event", "events"), + if again == 1 { "it" } else { "them" } + ) + ) + )); + } + } + + let warnings = model["warnings"].as_array().cloned().unwrap_or_default(); + if !warnings.is_empty() { + out.push(heading("warnings")); + for warning in &warnings { + out.push(format!(" {}", paint.paint(Style::Warn, &text(warning)))); + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A model as `model` makes one, of two parties, a proposal and the party's own. + fn sample() -> JsonValue { + json!({ + "format": FORMAT, + "store": {"id": "6d1e", "checkpoint": "6d1e", "heads": 3, "taken": 1, "stopped": null}, + "node": {"party": "lass", "votesByItself": true, "revisions": ["the base revision"]}, + "version": { + "number": 3, + "hash": "a7c2", + "federation": 1, + "revision": {"named": "the base revision"}, + "parties": 2, + "needed": 2, + }, + "parties": { + "lass": { + "keys": ["ssh-ed25519 AAAAone"], + "keySet": ["ssh-ed25519 AAAAone"], + "nodes": [{ + "id": "continuum:9c07", + "name": "beta", + "heard": 0, + "knows": {"wire": [52, 52], "revision": {"named": "the base revision"}}, + }], + }, + "tv": { + "keys": ["ssh-ed25519 AAAAtwo"], + "keySet": ["ssh-ed25519 AAAAthree"], + "nodes": [ + {"id": "continuum:5be1", "name": null, "heard": LATELY + 1, "knows": null}, + {"id": "continuum:77d0", "name": null, "heard": null, "knows": null}, + ], + }, + }, + "proposals": [{ + "hash": "8d02f1e3", + "standing": "open", + "needed": 2, + "more": 1, + "yes": ["tv"], + "no": [], + "notYet": ["lass"], + "proposedBy": "tv", + "number": 4, + "does": ["lets makefu in: 1 key (…); no node"], + "beside": null, + "none": null, + }], + "refused": {"own": []}, + "you": { + "party": "tv", + "isParty": true, + "key": {"key": "ssh-ed25519 AAAAthree", "named": false, "inKeySet": true}, + "record": { + "path": "tv.record", + "agrees": false, + "unrecorded": ["`false` on 8d02f1e3"], + "notShown": [], + }, + "again": 2, + }, + "warnings": ["the node hasn't heard from these nodes of tv lately: continuum:77d0"], + }) + } + + /// Without colours, what people read: a heading each, every party's keys and nodes, each + /// node with its name, when it was heard from and what it runs; each proposal with who + /// voted what and who not yet, and what it does; the party's own key, record and what + /// it signs again; the warnings. + #[test] + fn everything_but_the_values_at_a_glance() { + let lines = render(&sample(), &Paint(Colours::None)); + let has = |wanted: &str| { + assert!( + lines.iter().any(|line| line == wanted), + "{wanted:?} missing:\n{}", + lines.join("\n") + ); + }; + has("store 6d1e"); + has("the node"); + has(" lass's, voting for it by itself"); + has("version 3 (a7c2)"); + has(" 2 parties, 2 passing a change"); + has(" tv"); + has(" continuum:9c07 (beta)"); + has(" this node; wire 52; the base revision"); + has(&format!( + " heard {}; said nothing of what it runs", + ago(LATELY + 1) + )); + has(" not heard from since the node started; said nothing of what it runs"); + has(" keys of its key set (writes): the same"); + has("proposals on version 3"); + has(" 8d02f1e3: can still pass, 1 more `true` passing it (2 of 2)"); + has(" true: tv; false: nobody; not yet: lass"); + has(" proposed by tv: version 4 on 3"); + has(" lets makefu in: 1 key (…); no node"); + has(" no version event of its own"); + has("you: tv"); + has( + " record tv.record: lacks votes the node shows: `false` on 8d02f1e3: `restore` takes them in", + ); + has(" 2 events a move refused: `again` signs them again"); + has("warnings"); + assert!(lines.iter().all(|line| !line.contains('\x1b'))); + } + + /// Colours as the terminal shows them: true colour, 256, the basic eight, none. + #[test] + fn colours_as_the_terminal_shows_them() { + assert_eq!(Paint(Colours::None).paint(Style::Bad, "x"), "x"); + assert_eq!( + Paint(Colours::Basic).paint(Style::Bad, "x"), + "\x1b[1;31mx\x1b[0m" + ); + assert!( + Paint(Colours::Ansi256) + .paint(Style::Good, "x") + .contains("38;5;") + ); + assert!( + Paint(Colours::True) + .paint(Style::Good, "x") + .contains("38;2;") + ); + let marked = Paint(Colours::Basic).marked("8d02f1", 4); + assert!(marked.starts_with("\x1b[1m8d02\x1b[0m"), "{marked:?}"); + let lines = render(&sample(), &Paint(Colours::True)); + assert!(lines.iter().any(|line| line.contains("\x1b["))); + } + + #[test] + fn times_ago_said() { + assert_eq!(ago(12), "12 s ago"); + assert_eq!(ago(240), "4 min ago"); + assert_eq!(ago(3 * 3600), "3 h ago"); + assert_eq!(ago(2 * 86_400), "2 d ago"); + } +} |
