Files
mxaccessgw/clients/rust/crates/mxgw-cli/src/galaxy.rs
T
Joseph Doherty 2a91e2b083
ci / nightly-windev (push) Has been skipped
ci / windows-x86 (push) Successful in 1m27s
ci / java (push) Successful in 2m3s
ci / portable (push) Failing after 4m10s
refactor(rust-cli): split mxgw-cli main.rs by command group (mxaccessgw#203)
Pure move: cli definition, per-group handlers (session, bulk, bench, events,
galaxy, smoke, batch) and shared output/parse/connect helpers now live in
their own modules. No behaviour or CLI surface change; --help of all 33
commands is byte-identical, clippy clean, tests unchanged.

Claude-Session: https://claude.ai/code/session_01GT67AEHd2Acv1YPwGfXEoV
2026-11-09 13:17:16 -05:00

449 lines
18 KiB
Rust

//! `galaxy` command group: Galaxy Repository browse, discovery and deploy-watch.
use futures_util::StreamExt;
use serde_json::json;
use serde_json::Value;
use zb_mom_ww_mxgateway_client::galaxy::{BrowseChildrenOptions, LazyBrowseNode};
use zb_mom_ww_mxgateway_client::generated::galaxy_repository::v1::DeployEvent;
use zb_mom_ww_mxgateway_client::{Error, GalaxyClient};
use crate::cli::*;
use crate::connect::*;
use crate::parse::*;
pub(crate) async fn run_galaxy(command: GalaxyCommand) -> Result<(), Error> {
match command {
GalaxyCommand::TestConnection { connection, json } => {
let mut client = connect_galaxy(connection).await?;
let ok = client.test_connection().await?;
if json {
println!("{}", json!({ "ok": ok }));
} else if ok {
println!("ok");
} else {
println!("not ok");
}
}
GalaxyCommand::LastDeployTime { connection, json } => {
let mut client = connect_galaxy(connection).await?;
let timestamp = client.get_last_deploy_time().await?;
match (json, timestamp) {
(true, Some(ts)) => {
println!(
"{}",
json!({
"present": true,
"seconds": ts.seconds,
"nanos": ts.nanos,
})
);
}
(true, None) => {
println!("{}", json!({ "present": false }));
}
(false, Some(ts)) => println!("{}.{:09}", ts.seconds, ts.nanos),
(false, None) => println!("(absent)"),
}
}
GalaxyCommand::Watch {
connection,
last_seen_deploy_time,
max_events,
json,
} => {
let mut client = connect_galaxy(connection).await?;
let last_seen = last_seen_deploy_time
.as_deref()
.map(parse_rfc3339_timestamp)
.transpose()?;
let mut stream = client.watch_deploy_events(last_seen).await?;
let mut count = 0usize;
loop {
tokio::select! {
biased;
signal = tokio::signal::ctrl_c() => {
signal.map_err(|err| Error::InvalidArgument {
name: "ctrl_c".to_owned(),
detail: err.to_string(),
})?;
// Drop the stream below by breaking; tonic tears the
// gRPC call down cooperatively.
break;
}
next = stream.next() => {
let Some(event) = next else { break; };
let event = event?;
count += 1;
print_deploy_event(&event, json);
if max_events != 0 && count >= max_events {
break;
}
}
}
}
}
GalaxyCommand::DiscoverHierarchy { connection, json } => {
let mut client = connect_galaxy(connection).await?;
let objects = client.discover_hierarchy().await?;
if json {
let payload: Vec<_> = objects
.iter()
.map(|object| {
json!({
"gobjectId": object.gobject_id,
"tagName": object.tag_name,
"containedName": object.contained_name,
"browseName": object.browse_name,
"parentGobjectId": object.parent_gobject_id,
"isArea": object.is_area,
"categoryId": object.category_id,
"hostedByGobjectId": object.hosted_by_gobject_id,
"templateChain": object.template_chain,
"attributes": object.attributes.iter().map(|attribute| json!({
"attributeName": attribute.attribute_name,
"fullTagReference": attribute.full_tag_reference,
"mxDataType": attribute.mx_data_type,
"dataTypeName": attribute.data_type_name,
"isArray": attribute.is_array,
"arrayDimension": attribute.array_dimension,
"arrayDimensionPresent": attribute.array_dimension_present,
"mxAttributeCategory": attribute.mx_attribute_category,
"securityClassification": attribute.security_classification,
"isHistorized": attribute.is_historized,
"isAlarm": attribute.is_alarm,
})).collect::<Vec<_>>(),
})
})
.collect();
println!("{}", json!({ "objects": payload }));
} else {
println!("{}", objects.len());
for object in &objects {
println!(
"{} {} {} ({} attribute(s))",
object.gobject_id,
object.tag_name,
object.browse_name,
object.attributes.len()
);
}
}
}
GalaxyCommand::Browse {
connection,
parent_gobject_id,
category_ids,
template_chain_contains,
tag_name_glob,
include_attributes,
alarm_bearing_only,
historized_only,
depth,
json,
} => {
if parent_gobject_id.is_some() && depth > 0 {
eprintln!("warning: --depth is ignored when --parent-gobject-id is specified");
}
let mut client = connect_galaxy(connection).await?;
let options = BrowseChildrenOptions {
category_ids,
template_chain_contains,
tag_name_glob,
include_attributes: include_attributes.then_some(true),
alarm_bearing_only,
historized_only,
};
match parent_gobject_id {
// No parent → walk the lazy-browse tree from the root objects,
// eagerly expanding `depth` further levels so the print walks
// cached children without re-issuing RPCs.
None => {
let nodes = client.browse(Some(options)).await?;
for node in &nodes {
expand_to_depth(node, depth).await?;
}
if json {
let mut payload = Vec::with_capacity(nodes.len());
for node in &nodes {
payload.push(lazy_node_to_json(node).await);
}
println!("{}", json!({ "nodes": payload }));
} else {
println!("{}", nodes.len());
for node in &nodes {
print_lazy_node(node, 0).await;
}
}
}
// A specific parent → fetch exactly one level of children via
// the raw paged RPC. `--depth` is not meaningful here; the
// single-level children are returned as-is.
Some(parent) => {
let children = browse_children_one_level(&mut client, parent, &options).await?;
print_browse_children(&children, json);
}
}
}
}
Ok(())
}
/// Page size used for the raw `BrowseChildren` RPC when fetching a single
/// level via `--parent-gobject-id`. Mirrors `BROWSE_CHILDREN_PAGE_SIZE` in
/// `galaxy.rs` (the library's lazy-browse helper uses the same value).
pub(crate) const BROWSE_PAGE_SIZE: i32 = 500;
/// Drive `BrowseChildren` paging by hand for a single parent and return the
/// flattened child list. Used by the `browse --parent-gobject-id` path, which
/// surfaces one level of children rather than the lazy root-tree walk.
/// Record a non-empty `next_page_token` in `seen` and reject a repeat. A
/// server that returns the same continuation token twice would loop forever,
/// so the second sighting is converted to an `InvalidArgument` error. Extracted
/// from [`browse_children_one_level`] so the guard can be unit-tested without a
/// network client.
pub(crate) fn register_page_token(
seen: &mut std::collections::HashSet<String>,
token: &str,
) -> Result<(), Error> {
if !seen.insert(token.to_owned()) {
return Err(Error::InvalidArgument {
name: "page_token".to_owned(),
detail: format!("galaxy browse children returned repeated page token `{token}`"),
});
}
Ok(())
}
pub(crate) async fn browse_children_one_level(
client: &mut GalaxyClient,
parent_gobject_id: i32,
options: &BrowseChildrenOptions,
) -> Result<Vec<GalaxyBrowseChild>, Error> {
use std::collections::HashSet;
use zb_mom_ww_mxgateway_client::generated::galaxy_repository::v1::{
browse_children_request, BrowseChildrenRequest,
};
let mut children = Vec::new();
let mut page_token = String::new();
let mut seen: HashSet<String> = HashSet::new();
loop {
let request = BrowseChildrenRequest {
page_size: BROWSE_PAGE_SIZE,
page_token: page_token.clone(),
category_ids: options.category_ids.clone(),
template_chain_contains: options.template_chain_contains.clone(),
tag_name_glob: options.tag_name_glob.clone().unwrap_or_default(),
include_attributes: options.include_attributes,
alarm_bearing_only: options.alarm_bearing_only,
historized_only: options.historized_only,
parent: Some(browse_children_request::Parent::ParentGobjectId(
parent_gobject_id,
)),
};
let reply = client.browse_children_raw(request).await?;
let hints = reply.child_has_children;
for (index, object) in reply.children.into_iter().enumerate() {
let has_children_hint = hints.get(index).copied().unwrap_or(false);
children.push(GalaxyBrowseChild {
object,
has_children_hint,
});
}
page_token = reply.next_page_token;
if page_token.is_empty() {
return Ok(children);
}
register_page_token(&mut seen, &page_token)?;
}
}
/// A single child returned by the raw `BrowseChildren` paging path, paired
/// with its server-supplied `child_has_children` hint.
pub(crate) struct GalaxyBrowseChild {
object: zb_mom_ww_mxgateway_client::generated::galaxy_repository::v1::GalaxyObject,
has_children_hint: bool,
}
/// Print the one-level children of a browsed parent, mirroring the JSON node
/// shape used by the root-tree walk (minus the recursive `children` array).
pub(crate) fn print_browse_children(children: &[GalaxyBrowseChild], use_json: bool) {
if use_json {
let payload: Vec<_> = children.iter().map(browse_child_to_json).collect();
println!("{}", json!({ "nodes": payload }));
} else {
println!("{}", children.len());
for child in children {
let object = &child.object;
let marker = if child.has_children_hint { "+" } else { "-" };
println!(
"{marker} {} {} (gobject {})",
object.tag_name, object.browse_name, object.gobject_id,
);
}
}
}
/// Render one raw browse child as a JSON object whose key set matches the
/// lazy-node renderer (with an empty `children` array).
pub(crate) fn browse_child_to_json(child: &GalaxyBrowseChild) -> Value {
let object = &child.object;
json!({
"gobjectId": object.gobject_id,
"tagName": object.tag_name,
"containedName": object.contained_name,
"browseName": object.browse_name,
"parentGobjectId": object.parent_gobject_id,
"isArea": object.is_area,
"categoryId": object.category_id,
"hostedByGobjectId": object.hosted_by_gobject_id,
"templateChain": object.template_chain,
"hasChildrenHint": child.has_children_hint,
"attributes": object.attributes.iter().map(|attribute| json!({
"attributeName": attribute.attribute_name,
"fullTagReference": attribute.full_tag_reference,
"mxDataType": attribute.mx_data_type,
"dataTypeName": attribute.data_type_name,
"isArray": attribute.is_array,
"arrayDimension": attribute.array_dimension,
"arrayDimensionPresent": attribute.array_dimension_present,
"mxAttributeCategory": attribute.mx_attribute_category,
"securityClassification": attribute.security_classification,
"isHistorized": attribute.is_historized,
"isAlarm": attribute.is_alarm,
})).collect::<Vec<_>>(),
"children": Vec::<Value>::new(),
})
}
/// Recursively expand a [`LazyBrowseNode`] up to `depth` further levels. A
/// `depth` of 0 leaves the node unexpanded so the caller prints only the
/// requested level.
pub(crate) fn expand_to_depth(
node: &LazyBrowseNode,
depth: usize,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), Error>> + Send + '_>> {
Box::pin(async move {
if depth == 0 {
return Ok(());
}
node.expand().await?;
for child in node.children().await {
expand_to_depth(&child, depth - 1).await?;
}
Ok(())
})
}
/// Print a [`LazyBrowseNode`] and any already-expanded descendants as an
/// indented tree. Indentation is two spaces per level.
pub(crate) fn print_lazy_node(
node: &LazyBrowseNode,
indent: usize,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>> {
Box::pin(async move {
let object = node.object();
let marker = if node.has_children_hint() { "+" } else { "-" };
println!(
"{:indent$}{marker} {} {} (gobject {})",
"",
object.tag_name,
object.browse_name,
object.gobject_id,
indent = indent,
);
if node.is_expanded().await {
for child in node.children().await {
print_lazy_node(&child, indent + 2).await;
}
}
})
}
/// Render a [`LazyBrowseNode`] (and its already-expanded children) as a JSON
/// object. Mirrors the `discover-hierarchy` object shape with an added
/// `hasChildrenHint` flag and a nested `children` array.
pub(crate) fn lazy_node_to_json(
node: &LazyBrowseNode,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Value> + Send + '_>> {
Box::pin(async move {
let object = node.object();
let mut children = Vec::new();
if node.is_expanded().await {
for child in node.children().await {
children.push(lazy_node_to_json(&child).await);
}
}
json!({
"gobjectId": object.gobject_id,
"tagName": object.tag_name,
"containedName": object.contained_name,
"browseName": object.browse_name,
"parentGobjectId": object.parent_gobject_id,
"isArea": object.is_area,
"categoryId": object.category_id,
"hostedByGobjectId": object.hosted_by_gobject_id,
"templateChain": object.template_chain,
"hasChildrenHint": node.has_children_hint(),
"attributes": object.attributes.iter().map(|attribute| json!({
"attributeName": attribute.attribute_name,
"fullTagReference": attribute.full_tag_reference,
"mxDataType": attribute.mx_data_type,
"dataTypeName": attribute.data_type_name,
"isArray": attribute.is_array,
"arrayDimension": attribute.array_dimension,
"arrayDimensionPresent": attribute.array_dimension_present,
"mxAttributeCategory": attribute.mx_attribute_category,
"securityClassification": attribute.security_classification,
"isHistorized": attribute.is_historized,
"isAlarm": attribute.is_alarm,
})).collect::<Vec<_>>(),
"children": children,
})
})
}
pub(crate) fn print_deploy_event(event: &DeployEvent, use_json: bool) {
if use_json {
println!(
"{}",
json!({
"sequence": event.sequence,
"observedAt": event.observed_at.as_ref().map(|ts| json!({
"seconds": ts.seconds,
"nanos": ts.nanos,
})),
"timeOfLastDeploy": event.time_of_last_deploy.as_ref().map(|ts| json!({
"seconds": ts.seconds,
"nanos": ts.nanos,
})),
"timeOfLastDeployPresent": event.time_of_last_deploy_present,
"objectCount": event.object_count,
"attributeCount": event.attribute_count,
})
);
} else {
let observed = event
.observed_at
.as_ref()
.map(|ts| format!("{}.{:09}", ts.seconds, ts.nanos))
.unwrap_or_else(|| "(absent)".to_owned());
let last_deploy = if event.time_of_last_deploy_present {
event
.time_of_last_deploy
.as_ref()
.map(|ts| format!("{}.{:09}", ts.seconds, ts.nanos))
.unwrap_or_else(|| "(absent)".to_owned())
} else {
"(absent)".to_owned()
};
println!(
"seq={} observed={} lastDeploy={} objects={} attributes={}",
event.sequence, observed, last_deploy, event.object_count, event.attribute_count,
);
}
}