aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md6
-rw-r--r--docs/guides/federation/getting-started.md10
-rw-r--r--docs/guides/federation/writing-and-reading.md29
-rw-r--r--share/bash-completion/completions/continuum-party11
-rw-r--r--src/federation/party.rs127
5 files changed, 174 insertions, 9 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d52027a..de8582e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,12 @@ it from the release before ([`docs/operations.md`](docs/operations.md),
## Unreleased
+* `continuum-party get PATH` reads what counts as JSON: a place's value, or what lies
+ under a path as one object, within places' values too; `-r` a string as it is
+ ([`docs/guides/federation/writing-and-reading.md`](docs/guides/federation/writing-and-reading.md),
+ [Reading](docs/guides/federation/writing-and-reading.md#reading);
+ [`src/federation/party.rs`](src/federation/party.rs)).
+
* `continuum-party status` says the party's keys and nodes a line each, its nodes by the
names they gave themselves, which `GET /events/counts` shows (`names`)
([`docs/guides/federation/watching.md`](docs/guides/federation/watching.md);
diff --git a/docs/guides/federation/getting-started.md b/docs/guides/federation/getting-started.md
index 483a991..89d43ef 100644
--- a/docs/guides/federation/getting-started.md
+++ b/docs/guides/federation/getting-started.md
@@ -141,8 +141,14 @@ names them once, when it begins its record (`init --federation NAME`), and never
lass reads it on its node, with everything else that counts:
```sh
-continuum-party --node http://lass:secret@localhost:3000 values
-# home/tv/motd "hello" (tv)
+continuum-party --node http://lass:secret@localhost:3000 get home/tv/motd -r
+# hello
+continuum-party --node http://lass:secret@localhost:3000 get home
+# {
+# "tv": {
+# "motd": "hello"
+# }
+# }
```
lass can't write there: its node refuses it, as every node does.
diff --git a/docs/guides/federation/writing-and-reading.md b/docs/guides/federation/writing-and-reading.md
index abd5221..c6b27ba 100644
--- a/docs/guides/federation/writing-and-reading.md
+++ b/docs/guides/federation/writing-and-reading.md
@@ -94,11 +94,34 @@ Votes and proposals aren't signed again: their version is behind.
## Reading
-The client shows the values that count, each with who writes there, all or under a
-place (`--json` as one object, by place):
+The client reads what counts as JSON, as an application holds it: a place's value, or
+what lies under a path as one object, the places under it and the values within theirs,
+a list's items by their index; `-r` writes a string as it is, as `jq -r` does:
```sh
-continuum-party --node http://lass:secret@localhost:3000 values home/tv
+continuum-party get home/tv/motd -r
+# hello
+continuum-party get home/tv
+# {
+# "hosts": {
+# "laptop": {
+# "ip6": "42:0:a46e::1"
+# }
+# },
+# "motd": "hello"
+# }
+continuum-party get home/tv/hosts/laptop/ip6 -r
+# 42:0:a46e::1
+```
+
+Where a place lies under another's value (`home/tv/hosts` holding an object, and
+`home/tv/hosts/laptop` a place of its own), the deeper place is the later word there.
+Nothing counting at a path is an error. `values` shows the places themselves, each with
+who writes there (`--json` as one object, by place):
+
+```sh
+continuum-party values home/tv
+# home/tv/hosts/laptop {"ip6":"42:0:a46e::1"} (tv)
# home/tv/motd "hello" (tv)
```
diff --git a/share/bash-completion/completions/continuum-party b/share/bash-completion/completions/continuum-party
index de44be7..7834536 100644
--- a/share/bash-completion/completions/continuum-party
+++ b/share/bash-completion/completions/continuum-party
@@ -24,10 +24,12 @@ _continuum_party_parties()
awk '/passing a change:$/ { on = 1; next } on && /^ [^ ]/ { print $1; next } { on = 0 }'
}
-# The places holding a value.
+# The places holding a value, and the paths on their way.
_continuum_party_places()
{
- _continuum_party_asking values | cut -d' ' -f1
+ _continuum_party_asking values | cut -d' ' -f1 |
+ awk -F/ '{ path = $1; print path; for (i = 2; i <= NF; i++) { path = path "/" $i; print path } }' |
+ sort -u
}
# The features of the revisions the client knows, as `--version` names them.
@@ -79,7 +81,7 @@ _continuum_party()
local global_options='--node --token --key --record --federation --config --unset
--help --version'
local commands='init write keys nodes next propose vote again found root fork check
- judge proposals show status values twice help'
+ judge proposals show status values get twice help'
local intents='admit remove give take keys nodes checkpoint revision'
# The command, the intent of `propose` and `fork`, and the arguments after them that
@@ -216,9 +218,10 @@ _continuum_party()
_continuum_party_words '--list --add --remove --set --force'
fi
;;
- write | values)
+ write | values | get)
if [[ $cur == -* ]]; then
[[ $command == values ]] && _continuum_party_words '--json'
+ [[ $command == get ]] && _continuum_party_words '-r --raw'
elif ((n == 0)); then
_continuum_party_words "$(_continuum_party_places)"
fi
diff --git a/src/federation/party.rs b/src/federation/party.rs
index 19aadbd..4902f0f 100644
--- a/src/federation/party.rs
+++ b/src/federation/party.rs
@@ -36,6 +36,8 @@
//! * `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;
//! * `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;
//! * `found PARTY=KEY|FILE...`: the first version of a federation, from its parties' keys,
//! node lists (`--nodes`) and rules (`--rule`), to standard output;
//! * `root FILE`: the root of the federation whose first version `FILE` holds (JSON),
@@ -280,6 +282,21 @@ fn command() -> Command {
proposals on the current version, and what the party has to sign again",
))
.subcommand(
+ Command::new("get")
+ .about(
+ "What counts at a path, as JSON: a place's value, or what lies under it, \
+ places and the values within theirs, as one object; all without a path",
+ )
+ .arg(Arg::new("path").help("Segments by slashes (home/tv/motd); a list's items by their index"))
+ .arg(
+ Arg::new("raw")
+ .short('r')
+ .long("raw")
+ .action(ArgAction::SetTrue)
+ .help("A string as it is, not as JSON, as jq -r prints one"),
+ ),
+ )
+ .subcommand(
Command::new("values")
.about("The values that count, each with who writes there: all, or under a path")
.arg(Arg::new("path").help("The place, and those under it"))
@@ -645,6 +662,24 @@ pub(crate) async fn main() -> Result<()> {
if name == "values" {
return values(&node, sub).await;
}
+ if name == "get" {
+ let counts = node.counts().await?;
+ let path = sub
+ .get_one::<String>("path")
+ .map(|path| path.trim_matches('/'))
+ .unwrap_or_default();
+ let empty = serde_json::Map::new();
+ let tree = tree(counts["values"].as_object().unwrap_or(&empty), path);
+ let found = at(&tree, path).with_context(|| format!("nothing counts at {path}"))?;
+ match found {
+ JsonValue::String(text) if sub.get_flag("raw") => println!("{text}"),
+ JsonValue::Object(_) | JsonValue::Array(_) => {
+ println!("{}", serde_json::to_string_pretty(found)?)
+ }
+ scalar => println!("{scalar}"),
+ }
+ return Ok(());
+ }
if name == "show" {
let counts = node.counts().await?;
let proposal = proposal_named(&counts, sub)?.to_string();
@@ -1768,6 +1803,64 @@ async fn values(node: &Node, sub: &ArgMatches) -> Result<()> {
Ok(())
}
+/// What counts as one JSON value, from `values`, what counts at each place: each place's
+/// value at its path, the maps on its way made; of those on the way to `path` or under
+/// it alone (all, for an empty `path`). A place under another one's value goes into it,
+/// winning over what that value held there: the deeper place is the later word.
+fn tree(values: &serde_json::Map<String, JsonValue>, path: &str) -> JsonValue {
+ let under = (!path.is_empty()).then_some(path);
+ let mut places: Vec<(Vec<&str>, &JsonValue)> = values
+ .iter()
+ .filter(|(place, _)| {
+ is_under(place, under) || under.is_some_and(|under| is_under(under, Some(place)))
+ })
+ .map(|(place, value)| (place.split('/').collect(), value))
+ .collect();
+ places.sort_by(|(a, _), (b, _)| a.len().cmp(&b.len()).then(a.cmp(b)));
+ let mut tree = JsonValue::Object(serde_json::Map::new());
+ for (segments, value) in places {
+ let mut at = &mut tree;
+ for segment in segments {
+ if !at.is_object() {
+ *at = JsonValue::Object(serde_json::Map::new());
+ }
+ at = at
+ .as_object_mut()
+ .expect("made an object")
+ .entry(segment.to_owned())
+ .or_insert(JsonValue::Null);
+ }
+ merge(at, value.clone());
+ }
+ tree
+}
+
+/// `value` put where `at` is: objects merged, `value`'s members winning, deeply; else
+/// `value` in its place.
+fn merge(at: &mut JsonValue, value: JsonValue) {
+ match (at, value) {
+ (JsonValue::Object(held), JsonValue::Object(given)) => {
+ for (key, value) in given {
+ merge(held.entry(key).or_insert(JsonValue::Null), value);
+ }
+ }
+ (at, value) => *at = value,
+ }
+}
+
+/// What `tree` holds at `path`, segments by slashes, a list's items by their index; all of
+/// it for an empty `path`.
+fn at<'a>(tree: &'a JsonValue, path: &str) -> Option<&'a JsonValue> {
+ if path.is_empty() {
+ return Some(tree);
+ }
+ path.split('/').try_fold(tree, |at, segment| match at {
+ JsonValue::Object(members) => members.get(segment),
+ JsonValue::Array(items) => items.get(segment.parse::<usize>().ok()?),
+ _ => None,
+ })
+}
+
/// Whether `place` is the place `under` names, or under it; any, where `under` is none.
fn is_under(place: &str, under: Option<&str>) -> bool {
under.is_none_or(|under| {
@@ -2930,6 +3023,40 @@ mod tests {
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");
+ }
+
/// `values` shows a place and those under it, not those beside it.
#[test]
fn places_under_a_path() {