//! The `clap` command-line definition: `Cli`, `Command`, `GalaxyCommand` and shared connection arguments. use std::env; use std::path::PathBuf; use std::time::Duration; use clap::{Args, Parser, Subcommand, ValueEnum}; use zb_mom_ww_mxgateway_client::{ApiKey, ClientOptions}; #[derive(Debug, Parser)] #[command(name = "mxgw")] #[command(about = "MXAccess Gateway Rust test CLI")] pub(crate) struct Cli { #[command(subcommand)] pub(crate) command: Command, } #[derive(Debug, Subcommand)] pub(crate) enum Command { Version { #[arg(long)] json: bool, }, Ping { #[command(flatten)] connection: ConnectionArgs, #[arg(long, default_value = "ping")] message: String, #[arg(long)] json: bool, }, OpenSession { #[command(flatten)] connection: ConnectionArgs, #[arg(long, default_value = "mxgw-rust-cli")] client_name: String, #[arg(long)] json: bool, }, CloseSession { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] json: bool, }, Register { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long, default_value = "mxgw-rust-cli")] client_name: String, #[arg(long)] json: bool, }, AddItem { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long)] item: String, #[arg(long)] json: bool, }, Advise { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long)] item_handle: i32, #[arg(long)] json: bool, }, AdviseSupervisory { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long)] item_handle: i32, #[arg(long)] json: bool, }, /// Release a `ServerHandle` (and the items advised under it) via /// MXAccess `Unregister`. Unregister { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long)] json: bool, }, /// Resolve an MXAccess user id from a credential via `AuthenticateUser`. /// The password is read from `--password` or, if omitted, from the /// environment variable named by `--password-env`; it is never echoed to /// stdout/stderr. AuthenticateUser { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long)] verify_user: String, /// Verifier password. Prefer `--password-env` so the secret never /// appears in the process command line. #[arg(long)] password: Option, /// Name of the environment variable holding the verifier password. /// Used only when `--password` is not supplied. #[arg(long, default_value = "MXGATEWAY_VERIFY_PASSWORD")] password_env: String, #[arg(long)] json: bool, }, /// Single credential-verified write via MXAccess `WriteSecured`. /// /// Parity note: this fails natively unless the session has first run /// `authenticate-user` + `advise-supervisory` and the item carries a /// value-bearing body — the native failure is surfaced, not hidden. WriteSecured { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long)] item_handle: i32, #[arg(long, value_enum)] value_type: CliValueType, #[arg(long)] value: String, #[arg(long, default_value_t = 0)] current_user_id: i32, #[arg(long, default_value_t = 0)] verifier_user_id: i32, #[arg(long)] json: bool, }, SubscribeBulk { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long, value_delimiter = ',')] items: Vec, #[arg(long)] json: bool, }, UnsubscribeBulk { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long, value_delimiter = ',')] item_handles: Vec, #[arg(long)] json: bool, }, /// Snapshot the current value for each requested tag. Cached /// OnDataChange values are returned for tags that are already advised /// without touching the existing subscription; otherwise the worker /// takes a one-shot AddItem + Advise + UnAdvise + RemoveItem lifecycle. ReadBulk { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long, value_delimiter = ',')] items: Vec, /// Snapshot deadline in milliseconds, shared by all tags in the command. `0` uses the worker default (1000 ms). #[arg(long, default_value_t = 0)] timeout_ms: u32, #[arg(long)] json: bool, }, /// Bulk Write — one MXAccess Write per (item_handle, value) pair. WriteBulk { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long, value_delimiter = ',')] item_handles: Vec, #[arg(long, value_enum)] value_type: CliValueType, #[arg(long, value_delimiter = ',')] values: Vec, #[arg(long, default_value_t = 0)] user_id: i32, #[arg(long)] json: bool, }, /// Bulk Write2 — timestamped variant; the timestamp applies to all entries. Write2Bulk { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long, value_delimiter = ',')] item_handles: Vec, #[arg(long, value_enum)] value_type: CliValueType, #[arg(long, value_delimiter = ',')] values: Vec, #[arg(long)] timestamp: String, #[arg(long, default_value_t = 0)] user_id: i32, #[arg(long)] json: bool, }, /// Bulk WriteSecured. WriteSecuredBulk { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long, value_delimiter = ',')] item_handles: Vec, #[arg(long, value_enum)] value_type: CliValueType, #[arg(long, value_delimiter = ',')] values: Vec, #[arg(long, default_value_t = 0)] current_user_id: i32, #[arg(long, default_value_t = 0)] verifier_user_id: i32, #[arg(long)] json: bool, }, /// Bulk WriteSecured2 — timestamped + verified. WriteSecured2Bulk { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long, value_delimiter = ',')] item_handles: Vec, #[arg(long, value_enum)] value_type: CliValueType, #[arg(long, value_delimiter = ',')] values: Vec, #[arg(long)] timestamp: String, #[arg(long, default_value_t = 0)] current_user_id: i32, #[arg(long, default_value_t = 0)] verifier_user_id: i32, #[arg(long)] json: bool, }, /// Cross-language stress benchmark for ReadBulk: opens its own session, /// subscribes to `--bulk-size` tags so the worker's per-session value cache /// populates from real OnDataChange events, then hammers ReadBulk in a /// tight loop for `--duration-seconds` with per-call latency capture. Emits /// a single JSON object on stdout matching the schema the /// `scripts/bench-read-bulk.ps1` driver collates across all five clients. BenchReadBulk { #[command(flatten)] connection: ConnectionArgs, #[arg(long, default_value = "mxgw-rust-bench")] client_name: String, #[arg(long, default_value_t = 30)] duration_seconds: u64, #[arg(long, default_value_t = 3)] warmup_seconds: u64, #[arg(long, default_value_t = 6)] bulk_size: usize, #[arg(long, default_value_t = 1)] tag_start: i32, #[arg(long, default_value = "TestMachine_")] tag_prefix: String, #[arg(long, default_value = "TestChangingInt")] tag_attribute: String, #[arg(long, default_value_t = 1500)] timeout_ms: u32, #[arg(long)] json: bool, }, StreamEvents { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long, default_value_t = 0)] after_worker_sequence: u64, #[arg(long, default_value_t = 1)] max_events: usize, #[arg(long)] json: bool, #[arg(long)] jsonl: bool, }, /// Attach to the gateway's session-less central alarm feed. The stream /// opens with one `active_alarm` per currently-active alarm, then a /// single `snapshot_complete`, then a `transition` for every subsequent /// raise / acknowledge / clear. StreamAlarms { #[command(flatten)] connection: ConnectionArgs, /// Optional alarm-reference prefix scoping the feed to an equipment /// sub-tree. Omit to stream every active alarm. #[arg(long)] filter_prefix: Option, #[arg(long, default_value_t = 1)] max_events: usize, #[arg(long)] json: bool, #[arg(long)] jsonl: bool, }, /// Acknowledge an active MXAccess alarm condition through the gateway's /// session-less AcknowledgeAlarm RPC. AcknowledgeAlarm { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] reference: String, #[arg(long, default_value = "")] comment: String, /// Galaxy account of the acknowledging operator (required; the gateway /// rejects an empty operator so the real operator is recorded). #[arg(long)] operator: String, /// Galaxy domain of the operator; empty authenticates the bare user name. #[arg(long, default_value = "")] operator_domain: String, /// Operator password (prefer `--operator-password-env`; empty is allowed). #[arg(long)] operator_password: Option, /// Environment variable holding the operator password. #[arg(long, default_value = "MXGATEWAY_OPERATOR_PASSWORD")] operator_password_env: String, #[arg(long)] json: bool, }, Write { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long)] item_handle: i32, #[arg(long, value_enum)] value_type: CliValueType, #[arg(long)] value: String, #[arg(long, default_value_t = 0)] user_id: i32, #[arg(long)] json: bool, }, Write2 { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] session_id: String, #[arg(long)] server_handle: i32, #[arg(long)] item_handle: i32, #[arg(long, value_enum)] value_type: CliValueType, #[arg(long)] value: String, #[arg(long)] timestamp: String, #[arg(long, default_value_t = 0)] user_id: i32, #[arg(long)] json: bool, }, Smoke { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] item: String, #[arg(long, default_value = "mxgw-rust-smoke")] client_name: String, #[arg(long)] json: bool, }, /// Read commands from stdin, one per line, execute each in sequence, and /// write `__MXGW_BATCH_EOR__` to stdout after every result. Errors are /// written as `{"error":"…","type":"error"}` JSON to stdout (not stderr) /// so the harness can parse them without interleaving stderr. The loop /// never terminates on command error or accidental blank lines; only /// stdin EOF ends the session — empty lines log an empty-EOR-bracketed /// result and continue, matching the other four language CLIs. Batch, #[command(subcommand)] Galaxy(GalaxyCommand), } #[derive(Debug, Subcommand)] pub(crate) enum GalaxyCommand { TestConnection { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] json: bool, }, LastDeployTime { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] json: bool, }, DiscoverHierarchy { #[command(flatten)] connection: ConnectionArgs, #[arg(long)] json: bool, }, /// Lazily browse the Galaxy hierarchy through `BrowseChildren`. /// /// With no `--parent-gobject-id` the root objects are listed; pass a /// parent id to list that object's direct children. `--depth` controls /// how many further levels are eagerly expanded (0 = the requested level /// only). The filter flags map onto `BrowseChildrenOptions` and are reused /// at every expanded level, mirroring the lazy-browse library helper. Browse { #[command(flatten)] connection: ConnectionArgs, /// Parent gobject id whose children to browse. Omit for root objects. #[arg(long)] parent_gobject_id: Option, /// Restrict to objects whose `category_id` matches one of these ids. /// Repeatable. #[arg(long = "category-id")] category_ids: Vec, /// Restrict to objects whose template chain contains this entry. /// Repeatable (combined with AND). #[arg(long = "template-contains")] template_chain_contains: Vec, /// Restrict to objects whose tag name matches this SQL `LIKE`-style glob. #[arg(long)] tag_name_glob: Option, /// Populate `attributes` on the returned objects. #[arg(long)] include_attributes: bool, /// Only return objects that own at least one alarm-bearing attribute. #[arg(long)] alarm_bearing_only: bool, /// Only return objects that own at least one historized attribute. #[arg(long)] historized_only: bool, /// Number of additional levels to eagerly expand beneath each returned /// node. 0 (the default) prints only the requested level. /// Ignored when --parent-gobject-id is specified. #[arg(long, default_value_t = 0)] depth: usize, #[arg(long)] json: bool, }, /// Subscribe to the WatchDeployEvents server stream. /// /// Prints one line per received event (or one JSON object with `--json`). /// Runs until the stream ends, the server fails the call, or the /// process is interrupted (Ctrl+C). #[command(alias = "watch-deploy-events")] Watch { #[command(flatten)] connection: ConnectionArgs, /// Optional RFC3339 timestamp (e.g. `2026-04-28T15:30:00Z`). When /// supplied, the server suppresses the bootstrap event if its /// cached deploy time matches this value. #[arg(long)] last_seen_deploy_time: Option, /// Optional cap on the number of events to print before exiting. /// 0 (the default) means run until cancelled or the stream ends. #[arg(long, default_value_t = 0)] max_events: usize, #[arg(long)] json: bool, }, } #[derive(Debug, Args, Clone)] pub(crate) struct ConnectionArgs { #[arg(long, default_value = "http://127.0.0.1:5000")] pub(crate) endpoint: String, #[arg(long)] api_key: Option, /// Name of the environment variable holding the gateway API key. The /// variable's value must be a full gateway key of the form /// `mxgw__`; it is forwarded verbatim as the Bearer /// token, so do not point this at an unrelated credential. #[arg(long, default_value = "MXGATEWAY_API_KEY")] api_key_env: String, /// Use an unencrypted (plaintext h2c) channel. Mutually exclusive with /// `--tls`; supplying both is rejected so an explicit `--tls` cannot be /// silently downgraded. #[arg(long, conflicts_with = "tls")] plaintext: bool, #[arg(long)] tls: bool, #[arg(long)] ca_file: Option, #[arg(long)] server_name_override: Option, /// Verify the server certificate against the system trust roots even /// without a pinned CA. The Rust client's default is to require a CA /// file (see `--ca-file`); set this flag to use system roots instead. #[arg(long)] require_certificate_validation: bool, #[arg(long, default_value_t = 10)] connect_timeout_seconds: u64, #[arg(long, default_value_t = 30)] call_timeout_seconds: u64, } impl ConnectionArgs { /// Identity of the connection for batch-mode client reuse: every field that /// changes how the channel is dialed, including the API key actually /// resolved (flag or environment variable). Held in memory only. pub(crate) fn cache_key(&self) -> String { let api_key = self .api_key .clone() .or_else(|| env::var(&self.api_key_env).ok()) .unwrap_or_default(); format!( "{}|{}|{}|{:?}|{:?}|{}|{}|{}", self.endpoint, api_key, !self.tls || self.plaintext, self.ca_file, self.server_name_override, self.require_certificate_validation, self.connect_timeout_seconds, self.call_timeout_seconds ) } pub(crate) fn options(&self) -> ClientOptions { let mut options = ClientOptions::new(self.endpoint.clone()) .with_plaintext(!self.tls || self.plaintext) .with_connect_timeout(Duration::from_secs(self.connect_timeout_seconds)) .with_call_timeout(Duration::from_secs(self.call_timeout_seconds)); if let Some(api_key) = self .api_key .clone() .or_else(|| env::var(&self.api_key_env).ok()) .filter(|value| !value.is_empty()) { options = options.with_api_key(ApiKey::new(api_key)); } if let Some(ca_file) = &self.ca_file { options = options.with_ca_file(ca_file); } if let Some(server_name_override) = &self.server_name_override { options = options.with_server_name_override(server_name_override); } if self.require_certificate_validation { options = options.with_require_certificate_validation(true); } options } } #[derive(Clone, Copy, Debug, ValueEnum)] pub(crate) enum CliValueType { Bool, Int32, Int64, Float, Double, String, }