From 1508d664230e25e2f8343f37c6dc65c34eabac0c Mon Sep 17 00:00:00 2001 From: sdairs Date: Tue, 17 Nov 2026 15:39:24 +0000 Subject: [PATCH] feat(cli): filter ClickStack alert list by tag, search, source and state Add `--tag`, `--search`, `--source` and `--state` to `cloud clickstack alert list`. Repeated flags are sent as repeated query parameters; `--source`/`--state` take the library enums' VALUES. The spec limits (32-character tags, 512-character search) are clap value-parser errors, and the 50-tag limit is a post-parse usage error on `alert list`, both before credentials. `--name` lookups keep paging through every alert unfiltered. Fixes #1472 Co-Authored-By: Claude Opus 5.5 --- crates/clickhousectl/src/cloud/cli.rs | 9 + crates/clickhousectl/src/cloud/clickstack.rs | 290 +++++++++++++++++- crates/clickhousectl/src/main.rs | 40 +++ .../clickhousectl/tests/cloud/clickstack.rs | 67 +++- docs/guides/clickstack.md | 6 + 5 files changed, 393 insertions(+), 19 deletions(-) diff --git a/crates/clickhousectl/src/cloud/cli.rs b/crates/clickhousectl/src/cloud/cli.rs index 59aae8a3..3c19faf3 100644 --- a/crates/clickhousectl/src/cloud/cli.rs +++ b/crates/clickhousectl/src/cloud/cli.rs @@ -82,6 +82,15 @@ impl CloudArgs { command.clickpipe_create_validation_error() } + /// A `clickstack` usage error clap cannot detect, with the owning + /// subcommand path below `clickstack`, checked before credentials. + pub fn clickstack_validation_error(&self) -> Option<(&'static [&'static str], String)> { + let CloudCommands::ClickStack { command } = &self.command else { + return None; + }; + command.validation_error() + } + /// The `clickpipe reverse-private-endpoint create` validation message, if /// the flags cannot describe the chosen `--type`. clap cannot express /// "forbidden for this value of another argument", so the check runs after diff --git a/crates/clickhousectl/src/cloud/clickstack.rs b/crates/clickhousectl/src/cloud/clickstack.rs index 182f7ff5..705b966a 100644 --- a/crates/clickhousectl/src/cloud/clickstack.rs +++ b/crates/clickhousectl/src/cloud/clickstack.rs @@ -130,12 +130,13 @@ use crate::cloud::config::read_lossless_config; use crate::cloud::output::{or_absent, print_human}; use crate::cloud::shared::{NameSelector, resolve_org_id, select_named_id}; use clap::Subcommand; -use clap::builder::NonEmptyStringValueParser; +use clap::builder::{NonEmptyStringValueParser, PossibleValuesParser, TypedValueParser}; use clickhouse_cloud_api::models::{ ClickStackAlertResponse, ClickStackCreateAlertRequest, ClickStackCreateDashboardRequest, - ClickStackCreateRoleRequest, ClickStackDashboardResponse, ClickStackRole, - ClickStackSavedSearch, ClickStackSavedSearchInput, ClickStackSource, ClickStackSourceResponse, - ClickStackUpdateAlertRequest, ClickStackUpdateDashboardRequest, ClickStackUpdateRoleRequest, + ClickStackCreateRoleRequest, ClickStackDashboardResponse, ClickStackListAlertsSource, + ClickStackListAlertsState, ClickStackRole, ClickStackSavedSearch, ClickStackSavedSearchInput, + ClickStackSource, ClickStackSourceResponse, ClickStackUpdateAlertRequest, + ClickStackUpdateDashboardRequest, ClickStackUpdateRoleRequest, ClickStackValidateDashboardResponse, ClickStackValidateWebhookResponse, ClickStackWebhook, ClickStackWebhookInput, }; @@ -246,10 +247,17 @@ impl From for NameSelector { #[derive(Subcommand)] pub enum AlertCommands { /// List ClickStack alerts + #[command(after_help = "\ +CONTEXT FOR AGENTS: + Repeated values of one filter match any of them; different filters must all match. + --tag and --search match only the tags and displayName stored on the alert, not those + inherited from its saved search or dashboard.")] List { /// Service ID (from `cloud service list`) #[arg(value_parser = NonEmptyStringValueParser::new())] service_id: String, + #[command(flatten)] + filters: AlertListFilters, }, /// Get ClickStack alert details Get { @@ -315,6 +323,91 @@ CONTEXT FOR AGENTS: }, } +/// The API's alert-list limits, checked before credentials so an over-long +/// filter is a usage error rather than a request the API rejects. +const ALERT_LIST_MAX_TAGS: usize = 50; +const ALERT_LIST_TAG_MAX_CHARS: usize = 32; +const ALERT_LIST_SEARCH_MAX_CHARS: usize = 512; + +/// Server-side filters for `alert list`. +#[derive(clap::Args, Debug, Clone, Default)] +pub struct AlertListFilters { + /// Only alerts with this tag; repeat to match any of several + #[arg(long = "tag", value_name = "TAG", value_parser = parse_alert_tag)] + pub tags: Vec, + /// Only alerts whose displayName contains this text (case-insensitive) + #[arg(long, value_name = "TEXT", value_parser = parse_alert_search)] + pub search: Option, + /// Only alerts from this source; repeat to match any of several + #[arg( + long = "source", + value_name = "SOURCE", + value_parser = PossibleValuesParser::new(ClickStackListAlertsSource::VALUES) + .map(|value| alert_filter_enum::(&value)), + )] + pub sources: Vec, + /// Only alerts in this state; repeat to match any of several + #[arg( + long = "state", + value_name = "STATE", + value_parser = PossibleValuesParser::new(ClickStackListAlertsState::VALUES) + .map(|value| alert_filter_enum::(&value)), + )] + pub states: Vec, +} + +impl AlertListFilters { + /// The tag-count limit, which clap cannot express for a repeated flag. + pub(crate) fn validation_error(&self) -> Option { + let count = self.tags.len(); + (count > ALERT_LIST_MAX_TAGS).then(|| { + format!("--tag was given {count} times; at most {ALERT_LIST_MAX_TAGS} tags are allowed") + }) + } +} + +/// Convert a value clap already checked against the enum's `VALUES`. The +/// library enums keep an `Unknown` catch-all, so deserialization cannot fail. +fn alert_filter_enum(value: &str) -> T { + serde_json::from_value(Value::String(value.to_owned())) + .expect("library filter enums accept every string") +} + +fn parse_alert_tag(value: &str) -> Result { + let length = value.chars().count(); + if length > ALERT_LIST_TAG_MAX_CHARS { + return Err(format!( + "tag is {length} characters; the limit is {ALERT_LIST_TAG_MAX_CHARS}" + )); + } + Ok(value.to_owned()) +} + +fn parse_alert_search(value: &str) -> Result { + let length = value.chars().count(); + if length > ALERT_LIST_SEARCH_MAX_CHARS { + return Err(format!( + "search is {length} characters; the limit is {ALERT_LIST_SEARCH_MAX_CHARS}" + )); + } + Ok(value.to_owned()) +} + +impl ClickStackCommands { + /// A usage error clap cannot detect, checked after parsing and before + /// credentials. Returns the owning subcommand path below `clickstack`. + pub fn validation_error(&self) -> Option<(&'static [&'static str], String)> { + match self { + Self::Alert { + command: AlertCommands::List { filters, .. }, + } => filters + .validation_error() + .map(|message| (&["alert", "list"][..], message)), + _ => None, + } + } +} + impl AlertCommands { pub fn is_write(&self) -> bool { match self { @@ -879,6 +972,8 @@ async fn resolve_clickstack_target( service_id, Some(NAME_LOOKUP_PAGE_SIZE), Some(offset), + // A name lookup searches every alert. + &AlertListFilters::default(), ) .await? .into_iter() @@ -945,9 +1040,14 @@ pub async fn run(client: &CloudClient, command: ClickStackCommands, json: bool) async fn run_alert(client: &CloudClient, command: AlertCommands, json: bool) -> CloudResult<()> { match command { - AlertCommands::List { service_id } => { + AlertCommands::List { + service_id, + filters, + } => { let org_id = resolve_org_id(client).await?; - let alerts = client.click_stack_list_alerts(&org_id, &service_id).await?; + let alerts = client + .click_stack_list_alerts(&org_id, &service_id, &filters) + .await?; print_alert_list(&alerts, json) } AlertCommands::Get { service_id, target } => { @@ -1670,22 +1770,35 @@ impl CloudClient { &self, org_id: &str, service_id: &str, + filters: &AlertListFilters, ) -> CloudResult> { - self.click_stack_list_alerts_page(org_id, service_id, None, None) + self.click_stack_list_alerts_page(org_id, service_id, None, None, filters) .await } + /// One page of alerts. Every page of a paged read must pass the same + /// `filters`, so offsets index the same filtered result set. async fn click_stack_list_alerts_page( &self, org_id: &str, service_id: &str, limit: Option, offset: Option, + filters: &AlertListFilters, ) -> CloudResult> { + let tags: Vec<&str> = filters.tags.iter().map(String::as_str).collect(); let response = self .api() - // Filters are not exposed by `cloud clickstack alert list` yet. - .click_stack_list_alerts(org_id, service_id, limit, offset, &[], None, &[], &[]) + .click_stack_list_alerts( + org_id, + service_id, + limit, + offset, + &tags, + filters.search.as_deref(), + &filters.sources, + &filters.states, + ) .await .map_err(|error| self.convert_error_for_organization(error, org_id))?; Self::unwrap_response(response) @@ -2608,6 +2721,165 @@ mod tests { assert_eq!(digits(&error.message), "", "{error}"); } + fn parse_alert_list_filters(extra: &[&str]) -> AlertListFilters { + let mut args = vec![ + "clickhousectl", + "cloud", + "clickstack", + "alert", + "list", + "svc-1", + ]; + args.extend(extra); + let ClickStackCommands::Alert { + command: AlertCommands::List { filters, .. }, + } = parse_clickstack(&args) + else { + panic!("expected alert list") + }; + filters + } + + #[test] + fn alert_list_filters_default_to_none_and_repeat() { + let filters = parse_alert_list_filters(&[]); + assert!(filters.tags.is_empty()); + assert_eq!(filters.search, None); + assert!(filters.sources.is_empty() && filters.states.is_empty()); + + let filters = parse_alert_list_filters(&[ + "--tag", + "prod", + "--tag", + "checkout", + "--search", + "Errors", + "--source", + "tile", + "--source", + "saved_search", + "--state", + "ALERT", + "--state", + "PENDING", + ]); + assert_eq!(filters.tags, ["prod", "checkout"]); + assert_eq!(filters.search.as_deref(), Some("Errors")); + assert_eq!( + filters.sources, + [ + ClickStackListAlertsSource::Tile, + ClickStackListAlertsSource::Saved_search + ] + ); + assert_eq!( + filters.states, + [ + ClickStackListAlertsState::Alert, + ClickStackListAlertsState::Pending + ] + ); + } + + #[test] + fn alert_list_filter_enums_accept_every_wire_value_and_reject_others() { + use clap::error::ErrorKind; + for value in ClickStackListAlertsSource::VALUES { + let filters = parse_alert_list_filters(&["--source", value]); + assert_eq!(filters.sources[0].to_string(), *value); + } + for value in ClickStackListAlertsState::VALUES { + let filters = parse_alert_list_filters(&["--state", value]); + assert_eq!(filters.states[0].to_string(), *value); + } + for (flag, value) in [("--source", "dashboard"), ("--state", "alert")] { + let error = Cli::try_parse_from([ + "clickhousectl", + "cloud", + "clickstack", + "alert", + "list", + "svc-1", + flag, + value, + ]) + .err() + .expect("unknown filter value must be rejected"); + assert_eq!(error.kind(), ErrorKind::InvalidValue, "{flag} {value}"); + } + } + + #[test] + fn alert_list_filters_enforce_the_api_length_limits() { + use clap::error::ErrorKind; + let tag_at_limit = "t".repeat(ALERT_LIST_TAG_MAX_CHARS); + let search_at_limit = "é".repeat(ALERT_LIST_SEARCH_MAX_CHARS); + let filters = + parse_alert_list_filters(&["--tag", &tag_at_limit, "--search", &search_at_limit]); + assert_eq!(filters.tags, [tag_at_limit]); + assert_eq!(filters.search.as_deref(), Some(search_at_limit.as_str())); + + for (flag, value) in [ + ("--tag", "t".repeat(ALERT_LIST_TAG_MAX_CHARS + 1)), + ("--search", "s".repeat(ALERT_LIST_SEARCH_MAX_CHARS + 1)), + ] { + let error = Cli::try_parse_from([ + "clickhousectl", + "cloud", + "clickstack", + "alert", + "list", + "svc-1", + flag, + &value, + ]) + .err() + .expect("an over-long filter must be rejected"); + assert_eq!(error.kind(), ErrorKind::ValueValidation, "{flag}"); + assert!(error.to_string().contains(flag), "{error}"); + } + } + + #[test] + fn alert_list_tag_count_limit_is_a_clickstack_validation_error() { + let tags = |count: usize| -> Vec { + (0..count) + .flat_map(|index| ["--tag".to_owned(), format!("t{index}")]) + .collect() + }; + let at_limit = tags(ALERT_LIST_MAX_TAGS); + let at_limit: Vec<&str> = at_limit.iter().map(String::as_str).collect(); + let mut args = vec![ + "clickhousectl", + "cloud", + "clickstack", + "alert", + "list", + "svc-1", + ]; + args.extend(&at_limit); + assert_eq!(parse_clickstack(&args).validation_error(), None); + + let over = tags(ALERT_LIST_MAX_TAGS + 1); + let over: Vec<&str> = over.iter().map(String::as_str).collect(); + let mut args = vec![ + "clickhousectl", + "cloud", + "clickstack", + "alert", + "list", + "svc-1", + ]; + args.extend(&over); + let (path, message) = parse_clickstack(&args).validation_error().unwrap(); + assert_eq!(path, ["alert", "list"]); + assert!(message.contains("--tag"), "{message}"); + assert!( + message.contains(&(ALERT_LIST_MAX_TAGS + 1).to_string()), + "{message}" + ); + } + #[test] fn alert_list_name_prefers_display_name_over_name_template() { let alerts: Vec = serde_json::from_value(serde_json::json!([ diff --git a/crates/clickhousectl/src/main.rs b/crates/clickhousectl/src/main.rs index aa4adcf3..05527960 100644 --- a/crates/clickhousectl/src/main.rs +++ b/crates/clickhousectl/src/main.rs @@ -257,6 +257,20 @@ fn validate_post_parse(cli: &Cli, cmd: &mut clap::Command) -> std::result::Resul )); } + // Limits clap cannot express, such as how often a flag may repeat. + if let Some((path, message)) = args.clickstack_validation_error() { + let mut owner = cmd + .find_subcommand_mut("cloud") + .and_then(|cloud| cloud.find_subcommand_mut("clickstack")) + .expect("cloud clickstack command must exist"); + for name in path { + owner = owner + .find_subcommand_mut(name) + .expect("clickstack validation path names an existing subcommand"); + } + return Err(owner.error(ErrorKind::TooManyValues, message)); + } + // Each reverse private endpoint type has its own required flags, and the // flags of the other types are meaningless for it; clap has no way to // forbid an argument based on another argument's value. @@ -680,6 +694,32 @@ mod tests { Ok(cli) } + #[test] + fn clickstack_validation_errors_are_usage_errors_on_the_owning_command() { + let mut args = vec![ + "clickhousectl".to_owned(), + "cloud".to_owned(), + "clickstack".to_owned(), + "alert".to_owned(), + "list".to_owned(), + "svc-1".to_owned(), + ]; + for index in 0..51 { + args.extend(["--tag".to_owned(), format!("t{index}")]); + } + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + let error = parse_and_validate(&args) + .err() + .expect("more than 50 tags should be rejected"); + assert_eq!(error.exit_code(), 2); + let message = error.to_string(); + assert!(message.contains("--tag"), "{message}"); + assert!( + message.contains("clickhousectl cloud clickstack alert list"), + "{message}" + ); + } + #[test] fn service_query_rejects_explicit_json_with_format_in_both_orders() { for args in [ diff --git a/crates/clickhousectl/tests/cloud/clickstack.rs b/crates/clickhousectl/tests/cloud/clickstack.rs index 7cb59e61..645b8962 100644 --- a/crates/clickhousectl/tests/cloud/clickstack.rs +++ b/crates/clickhousectl/tests/cloud/clickstack.rs @@ -4,7 +4,7 @@ use std::io::Write as _; use std::process::{Command, Stdio}; use serde_json::Value; -use wiremock::matchers::{method, path, query_param_is_missing}; +use wiremock::matchers::{method, path, query_param, query_param_is_missing}; use wiremock::{Mock, MockServer, ResponseTemplate}; use crate::support::*; @@ -1102,22 +1102,50 @@ async fn clickstack_webhook_validate_posts_full_body_and_reports_results() { } #[tokio::test] -async fn clickstack_alert_list_and_name_selector_use_display_name() { +async fn clickstack_alert_list_filters_and_name_selector_use_display_name() { let mock = MockServer::start().await; let alerts = "/v1/organizations/org-1/services/svc-1/clickstack/alerts"; - // The list sends none of the API's alert filters. + let alert_list = serde_json::json!({ + "result":[ + {"id":"alert-1","displayName":"Checkout errors","name":"Errors hit {{value}}","tags":[]}, + {"id":"alert-2","displayName":"Latency","tags":[]} + ] + }); + // `list` sends every filter, repeated flags as repeated parameters. + Mock::given(method("GET")) + .and(path(alerts)) + .and(|request: &wiremock::Request| { + let mut pairs: Vec<(String, String)> = request + .url + .query_pairs() + .map(|(key, value)| (key.into_owned(), value.into_owned())) + .collect(); + pairs.sort(); + pairs + == [ + ("search", "checkout errors"), + ("source", "saved_search"), + ("source", "tile"), + ("state", "ALERT"), + ("tag", "checkout"), + ("tag", "prod"), + ] + .map(|(key, value)| (key.to_owned(), value.to_owned())) + }) + .respond_with(ResponseTemplate::new(200).set_body_json(alert_list.clone())) + .expect(1) + .mount(&mock) + .await; + // A `--name` lookup pages through every alert, unfiltered. Mock::given(method("GET")) .and(path(alerts)) + .and(query_param("offset", "0")) .and(query_param_is_missing("tag")) .and(query_param_is_missing("search")) .and(query_param_is_missing("source")) .and(query_param_is_missing("state")) - .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({ - "result":[ - {"id":"alert-1","displayName":"Checkout errors","name":"Errors hit {{value}}","tags":[]}, - {"id":"alert-2","displayName":"Latency","tags":[]} - ] - }))) + .respond_with(ResponseTemplate::new(200).set_body_json(alert_list)) + .expect(2) .mount(&mock) .await; Mock::given(method("GET")) @@ -1131,7 +1159,26 @@ async fn clickstack_alert_list_and_name_selector_use_display_name() { let output = invoke_clickstack_cli( &mock, - &["clickstack", "alert", "list", "svc-1", "--org-id", "org-1"], + &[ + "clickstack", + "alert", + "list", + "svc-1", + "--tag", + "prod", + "--tag", + "checkout", + "--search", + "checkout errors", + "--source", + "saved_search", + "--source", + "tile", + "--state", + "ALERT", + "--org-id", + "org-1", + ], None, false, ); diff --git a/docs/guides/clickstack.md b/docs/guides/clickstack.md index a07e3839..f8588791 100644 --- a/docs/guides/clickstack.md +++ b/docs/guides/clickstack.md @@ -110,6 +110,12 @@ Inspect `state` and `executionErrors`, as well as notification destinations. A ` An alert's `displayName` is the name shown in the UI and in `alert list`; its optional `name` is a Handlebars template for the notification title. For `alert get`, `update` and `delete`, `--name` selects the alert whose `displayName` or `name` equals the value, and fails if more than one alert matches. +`alert list` filters on the server. Repeat `--tag`, `--source` (`saved_search`, `tile` or `inline`) or `--state` (`ALERT`, `OK`, `INSUFFICIENT_DATA`, `DISABLED` or `PENDING`) to match any of several values; `--search` matches text in `displayName`, ignoring case. Different filters must all match. `--tag` and `--search` see only the tags and `displayName` stored on the alert, not those inherited from its saved search or dashboard. The API accepts up to 50 tags of at most 32 characters each and a search of at most 512 characters: + +```bash +clickhousectl cloud clickstack alert list --state ALERT --state PENDING --tag checkout +``` + `displayName` defaults to the name of the saved search, tile or chart the alert queries, and `tags` default to the saved search's or dashboard's tags. An `inline` alert carries its own chart in `chartConfig` (a `line`, `stacked_bar`, `stacked_line` or `number` chart) instead of referencing a dashboard tile, and has no tags unless you set them: ```json