From 307179e792ffc92c2c420208130a2e353717f511 Mon Sep 17 00:00:00 2001 From: sdairs Date: Tue, 17 Nov 2026 15:30:09 +0000 Subject: [PATCH] fix(api): add ClickStack alert list filters, minAutoGranularity and App subject - click_stack_list_alerts gains tag/search/source/state filters (repeated query parameters for the array ones), with new ClickStackListAlertsSource and ClickStackListAlertsState enums. Breaking signature change. - ClickStackMetricSource, ClickStackPromqlSource and their Response types gain optional min_auto_granularity; TryFrom carries it back. - ClickStackCASLPermissionSubject adds App. - CLI: `cloud clickstack alert list` passes no filters; a request-shape test pins that no filter parameter is sent. Fixes #1466 Co-Authored-By: Claude Opus 5.5 --- crates/clickhouse-cloud-api/CHANGELOG.md | 21 ++++ .../src/client/clickstack.rs | 30 ++++++ .../src/convert/clickstack.rs | 2 + .../src/models/clickstack/enums.rs | 70 +++++++++++++ .../src/models/clickstack/sources.rs | 22 +++++ .../tests/client/clickstack.rs | 94 +++++++++++++++++- .../tests/model_facade_test.rs | 8 ++ .../tests/models/clickstack.rs | 98 +++++++++++++++++++ crates/clickhousectl/src/cloud/clickstack.rs | 3 +- .../clickhousectl/tests/cloud/clickstack.rs | 7 +- 10 files changed, 349 insertions(+), 6 deletions(-) diff --git a/crates/clickhouse-cloud-api/CHANGELOG.md b/crates/clickhouse-cloud-api/CHANGELOG.md index f2f42ab3b..566a428fa 100644 --- a/crates/clickhouse-cloud-api/CHANGELOG.md +++ b/crates/clickhouse-cloud-api/CHANGELOG.md @@ -204,6 +204,27 @@ certificates, read-replica, restore, password, state and slow-query operations are no longer Beta: 19 entries leave `meta::BETA_OPERATIONS`, so `meta::is_beta_operation` returns `false` for them. +Breaking: `click_stack_list_alerts` takes four more arguments after `offset`, +for the spec's new alert filters: `tag: &[&str]` (alerts with any of these +tags), `search: Option<&str>` (case-insensitive display-name substring), +`source: &[ClickStackListAlertsSource]` and +`state: &[ClickStackListAlertsState]` (alerts of any of these sources or +states). Each slice element is sent as a repeated query parameter, and +`totalCount` counts only the matching alerts. The two new enums carry a +`VALUES` const and an `Unknown(String)` catch-all. Migrate +`click_stack_list_alerts(org, service, limit, offset)` to +`click_stack_list_alerts(org, service, limit, offset, &[], None, &[], &[])`; +the request sent is unchanged. + +`ClickStackMetricSource`, `ClickStackPromqlSource` and their `*Response` +types gain optional `min_auto_granularity` (`minAutoGranularity`), a floor for +the auto-inferred chart granularity in SQL interval format such as +`"1 minute"` (for PromQL sources it is also the scrape interval +`$__rate_interval` is computed from). `TryFrom` carries it back to the request +type. Struct-literal callers need `min_auto_granularity: None`. +`ClickStackCASLPermissionSubject` adds `App`; exhaustive matches without a +wildcard arm need the new variant. + ## 0.5.1 No changes to this crate; released in lockstep with `clickhousectl` 0.5.1. diff --git a/crates/clickhouse-cloud-api/src/client/clickstack.rs b/crates/clickhouse-cloud-api/src/client/clickstack.rs index 48f48b755..704820192 100644 --- a/crates/clickhouse-cloud-api/src/client/clickstack.rs +++ b/crates/clickhouse-cloud-api/src/client/clickstack.rs @@ -8,12 +8,30 @@ impl Client { /// /// The API defaults to 1,000 records from offset zero. Request successive /// pages with `limit` (1–1,000) and `offset` until a page is shorter than the limit. + /// + /// The optional filters narrow the result set, and `totalCount` counts only + /// the matching alerts. An empty slice or `None` sends no filter: + /// + /// - `tag`: alerts that have any of these tags (at most 50, each at most 32 + /// characters). Matches the tags stored on the alert, not tags inherited + /// from the linked dashboard or saved search. + /// - `search`: alerts whose stored display name contains this text, + /// case-insensitively (at most 512 characters). + /// - `source`: alerts of any of these sources. + /// - `state`: alerts in any of these states. + /// + /// Each slice element is sent as its own repeated query parameter. + #[allow(clippy::too_many_arguments)] pub async fn click_stack_list_alerts( &self, organization_id: &str, service_id: &str, limit: Option, offset: Option, + tag: &[&str], + search: Option<&str>, + source: &[ClickStackListAlertsSource], + state: &[ClickStackListAlertsState], ) -> Result>, Error> { let mut req = self.request( &operations::CLICK_STACK_LIST_ALERTS, @@ -25,6 +43,18 @@ impl Client { if let Some(offset) = offset { req = req.query(&[("offset", offset)]); } + for value in tag { + req = req.query(&[("tag", value)]); + } + if let Some(value) = search { + req = req.query(&[("search", value)]); + } + for value in source { + req = req.query(&[("source", value)]); + } + for value in state { + req = req.query(&[("state", value)]); + } let resp = req.send().await?; let status = resp.status(); let body_text = resp.text().await?; diff --git a/crates/clickhouse-cloud-api/src/convert/clickstack.rs b/crates/clickhouse-cloud-api/src/convert/clickstack.rs index 9c6eab3aa..d75d2affe 100644 --- a/crates/clickhouse-cloud-api/src/convert/clickstack.rs +++ b/crates/clickhouse-cloud-api/src/convert/clickstack.rs @@ -338,6 +338,7 @@ impl TryFrom for ClickStackMetricSource { kind, log_source_id: value.log_source_id, metric_tables: metric_tables.try_into()?, + min_auto_granularity: value.min_auto_granularity, name, query_settings: value .query_settings @@ -441,6 +442,7 @@ impl TryFrom for ClickStackPromqlSource { from: from.try_into()?, id: value.id, kind, + min_auto_granularity: value.min_auto_granularity, name, query_settings: value .query_settings diff --git a/crates/clickhouse-cloud-api/src/models/clickstack/enums.rs b/crates/clickhouse-cloud-api/src/models/clickstack/enums.rs index 37cedca04..ec4f9ab5b 100644 --- a/crates/clickhouse-cloud-api/src/models/clickstack/enums.rs +++ b/crates/clickhouse-cloud-api/src/models/clickstack/enums.rs @@ -229,6 +229,73 @@ impl std::fmt::Display for ClickStackAlertResponseState { } } +/// Inline enum for the `clickStackListAlerts` `source` query parameter. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum ClickStackListAlertsSource { + #[serde(rename = "saved_search")] + Saved_search, + #[serde(rename = "tile")] + Tile, + #[serde(rename = "inline")] + Inline, + /// Catch-all for unknown or newly-added values. + #[serde(untagged)] + Unknown(String), +} + +impl std::fmt::Display for ClickStackListAlertsSource { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Saved_search => write!(f, "saved_search"), + Self::Tile => write!(f, "tile"), + Self::Inline => write!(f, "inline"), + Self::Unknown(s) => write!(f, "{s}"), + } + } +} + +impl ClickStackListAlertsSource { + /// Wire values accepted by the API, excluding the catch-all. + pub const VALUES: &'static [&'static str] = &["saved_search", "tile", "inline"]; +} + +/// Inline enum for the `clickStackListAlerts` `state` query parameter. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub enum ClickStackListAlertsState { + #[serde(rename = "ALERT")] + Alert, + #[serde(rename = "OK")] + Ok, + #[serde(rename = "INSUFFICIENT_DATA")] + Insufficient_data, + #[serde(rename = "DISABLED")] + Disabled, + #[serde(rename = "PENDING")] + Pending, + /// Catch-all for unknown or newly-added values. + #[serde(untagged)] + Unknown(String), +} + +impl std::fmt::Display for ClickStackListAlertsState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Alert => write!(f, "ALERT"), + Self::Ok => write!(f, "OK"), + Self::Insufficient_data => write!(f, "INSUFFICIENT_DATA"), + Self::Disabled => write!(f, "DISABLED"), + Self::Pending => write!(f, "PENDING"), + Self::Unknown(s) => write!(f, "{s}"), + } + } +} + +impl ClickStackListAlertsState { + /// Wire values accepted by the API, excluding the catch-all. + pub const VALUES: &'static [&'static str] = + &["ALERT", "OK", "INSUFFICIENT_DATA", "DISABLED", "PENDING"]; +} + /// Inline enum for `ClickStackAlertResponse.thresholdType`. #[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)] pub enum ClickStackAlertResponseThresholdtype { @@ -477,6 +544,8 @@ pub enum ClickStackCASLPermissionSubject { Notebook, #[serde(rename = "SchemaMigration")] SchemaMigration, + #[serde(rename = "App")] + App, #[serde(rename = "all")] All, /// Catch-all for unknown or newly-added values. @@ -498,6 +567,7 @@ impl std::fmt::Display for ClickStackCASLPermissionSubject { Self::Role => write!(f, "Role"), Self::Notebook => write!(f, "Notebook"), Self::SchemaMigration => write!(f, "SchemaMigration"), + Self::App => write!(f, "App"), Self::All => write!(f, "all"), Self::Unknown(s) => write!(f, "{s}"), } diff --git a/crates/clickhouse-cloud-api/src/models/clickstack/sources.rs b/crates/clickhouse-cloud-api/src/models/clickstack/sources.rs index 5891bced5..7b4c73ccb 100644 --- a/crates/clickhouse-cloud-api/src/models/clickstack/sources.rs +++ b/crates/clickhouse-cloud-api/src/models/clickstack/sources.rs @@ -546,6 +546,11 @@ pub struct ClickStackMetricSource { pub log_source_id: Option, #[serde(rename = "metricTables")] pub metric_tables: ClickStackMetricTables, + /// Floor for the auto-inferred chart granularity, in the SQL interval + /// format (for example `1 minute`). Set it to the metrics' scrape or report + /// interval; it only constrains "Auto" granularity. `None` sets no minimum. + #[serde(rename = "minAutoGranularity", skip_serializing_if = "Option::is_none")] + pub min_auto_granularity: Option, pub name: String, #[serde(rename = "querySettings", skip_serializing_if = "Option::is_none")] pub query_settings: Option>, @@ -578,6 +583,11 @@ pub struct ClickStackMetricSourceResponse { pub log_source_id: Option, #[serde(rename = "metricTables", skip_serializing_if = "Option::is_none")] pub metric_tables: Option, + /// Floor for the auto-inferred chart granularity, in the SQL interval + /// format (for example `1 minute`). Set it to the metrics' scrape or report + /// interval; it only constrains "Auto" granularity. `None` sets no minimum. + #[serde(rename = "minAutoGranularity", skip_serializing_if = "Option::is_none")] + pub min_auto_granularity: Option, #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, #[serde(rename = "querySettings", skip_serializing_if = "Option::is_none")] @@ -661,6 +671,12 @@ pub struct ClickStackPromqlSource { #[serde(skip_serializing_if = "Option::is_none")] pub id: Option, pub kind: ClickStackPromqlSourceKind, + /// Floor for the auto-inferred chart granularity, and the scrape interval + /// `$__rate_interval` is computed from, in the SQL interval format (for + /// example `1 minute`). It only constrains "Auto" granularity. `None` sets + /// no minimum. + #[serde(rename = "minAutoGranularity", skip_serializing_if = "Option::is_none")] + pub min_auto_granularity: Option, pub name: String, #[serde(rename = "querySettings", skip_serializing_if = "Option::is_none")] pub query_settings: Option>, @@ -687,6 +703,12 @@ pub struct ClickStackPromqlSourceResponse { pub id: Option, #[serde(skip_serializing_if = "Option::is_none")] pub kind: Option, + /// Floor for the auto-inferred chart granularity, and the scrape interval + /// `$__rate_interval` is computed from, in the SQL interval format (for + /// example `1 minute`). It only constrains "Auto" granularity. `None` sets + /// no minimum. + #[serde(rename = "minAutoGranularity", skip_serializing_if = "Option::is_none")] + pub min_auto_granularity: Option, #[serde(skip_serializing_if = "Option::is_none")] pub name: Option, #[serde(rename = "querySettings", skip_serializing_if = "Option::is_none")] diff --git a/crates/clickhouse-cloud-api/tests/client/clickstack.rs b/crates/clickhouse-cloud-api/tests/client/clickstack.rs index a3d2a4ef0..4c7a92911 100644 --- a/crates/clickhouse-cloud-api/tests/client/clickstack.rs +++ b/crates/clickhouse-cloud-api/tests/client/clickstack.rs @@ -26,13 +26,91 @@ async fn list_alerts() { .await; let resp = c - .click_stack_list_alerts("org-1", "svc-1", None, None) + .click_stack_list_alerts("org-1", "svc-1", None, None, &[], None, &[], &[]) .await .unwrap(); let alerts = resp.result.unwrap(); assert_eq!(alerts.len(), 1); } +#[tokio::test] +async fn list_alerts_sends_repeated_filters() { + let (s, c) = setup().await; + + Mock::given(method("GET")) + .and(path( + "/v1/organizations/org-1/services/svc-1/clickstack/alerts", + )) + .and(wiremock::matchers::query_param("search", "checkout")) + .respond_with(ok_json(serde_json::json!([{"id": "alert-1"}]))) + .expect(1) + .mount(&s) + .await; + + let resp = c + .click_stack_list_alerts( + "org-1", + "svc-1", + Some(10), + None, + &["prod", "team a"], + Some("checkout"), + &[ + ClickStackListAlertsSource::Saved_search, + ClickStackListAlertsSource::Tile, + ], + &[ + ClickStackListAlertsState::Alert, + ClickStackListAlertsState::Insufficient_data, + ], + ) + .await + .unwrap(); + assert_eq!(resp.result.unwrap().len(), 1); + + let requests = s.received_requests().await.unwrap(); + assert_eq!(requests.len(), 1); + let pairs: Vec<(String, String)> = requests[0] + .url + .query_pairs() + .map(|(key, value)| (key.into_owned(), value.into_owned())) + .collect(); + let expected: Vec<(String, String)> = [ + ("limit", "10"), + ("tag", "prod"), + ("tag", "team a"), + ("search", "checkout"), + ("source", "saved_search"), + ("source", "tile"), + ("state", "ALERT"), + ("state", "INSUFFICIENT_DATA"), + ] + .into_iter() + .map(|(key, value)| (key.to_string(), value.to_string())) + .collect(); + assert_eq!(pairs, expected); +} + +#[tokio::test] +async fn list_alerts_without_filters_sends_no_filter_parameters() { + let (s, c) = setup().await; + + Mock::given(method("GET")) + .and(path( + "/v1/organizations/org-1/services/svc-1/clickstack/alerts", + )) + .respond_with(ok_json(serde_json::json!([]))) + .expect(1) + .mount(&s) + .await; + + c.click_stack_list_alerts("org-1", "svc-1", None, None, &[], None, &[], &[]) + .await + .unwrap(); + let requests = s.received_requests().await.unwrap(); + assert_eq!(requests[0].url.query(), None); +} + #[tokio::test] async fn create_alert() { let (s, c) = setup().await; @@ -565,12 +643,13 @@ async fn create_source() { "/v1/organizations/org-1/services/svc-1/clickstack/sources", )) .and(body_partial_json( - serde_json::json!({"kind": "promql", "name": "Prometheus Metrics"}), + serde_json::json!({"kind": "promql", "name": "Prometheus Metrics", "minAutoGranularity": "15 second"}), )) .respond_with(ok_json(serde_json::json!({ "id": "source-1", "kind": "promql", "name": "Prometheus Metrics", + "minAutoGranularity": "15 second", "connection": "conn-1", "from": {"databaseName": "default", "tableName": "metrics"}, "timestampValueExpression": "timestamp" @@ -589,6 +668,7 @@ async fn create_source() { timestamp_value_expression: "timestamp".to_string(), disabled: None, id: None, + min_auto_granularity: Some("15 second".to_string()), query_settings: None, section: None, }); @@ -596,7 +676,12 @@ async fn create_source() { .click_stack_create_source("org-1", "svc-1", &body) .await .unwrap(); - assert!(resp.result.is_some()); + match resp.result { + Some(ClickStackSourceResponse::ClickStackPromqlSource(source)) => { + assert_eq!(source.min_auto_granularity.as_deref(), Some("15 second")); + } + other => panic!("expected a promql source, got {other:?}"), + } } #[tokio::test] @@ -658,6 +743,7 @@ async fn update_source() { timestamp_value_expression: "timestamp".to_string(), disabled: None, id: None, + min_auto_granularity: None, query_settings: None, section: None, }); @@ -1279,7 +1365,7 @@ async fn clickstack_list_pagination_encodes_only_supplied_parameters() { .await; let count = match resource { "alerts" => client - .click_stack_list_alerts("org-1", "svc-1", limit, offset) + .click_stack_list_alerts("org-1", "svc-1", limit, offset, &[], None, &[], &[]) .await .unwrap() .result diff --git a/crates/clickhouse-cloud-api/tests/model_facade_test.rs b/crates/clickhouse-cloud-api/tests/model_facade_test.rs index 8852579e8..2acd63c64 100644 --- a/crates/clickhouse-cloud-api/tests/model_facade_test.rs +++ b/crates/clickhouse-cloud-api/tests/model_facade_test.rs @@ -122,6 +122,14 @@ fn extracted_models_keep_root_and_models_paths() { PhantomData::, PhantomData::, ); + assert_same_type( + PhantomData::, + PhantomData::, + ); + assert_same_type( + PhantomData::, + PhantomData::, + ); assert_same_type( PhantomData::, PhantomData::, diff --git a/crates/clickhouse-cloud-api/tests/models/clickstack.rs b/crates/clickhouse-cloud-api/tests/models/clickstack.rs index 92e781823..ff12a9d37 100644 --- a/crates/clickhouse-cloud-api/tests/models/clickstack.rs +++ b/crates/clickhouse-cloud-api/tests/models/clickstack.rs @@ -5703,3 +5703,101 @@ fn clickstack_tile_input_new_sends_only_required_fields() { serde_json::json!({"name": "Error Rate", "x": 1, "y": 2, "w": 6, "h": 3}) ); } + +#[test] +fn clickstack_metric_and_promql_min_auto_granularity_write_back() { + let metric = serde_json::json!({ + "kind": "metric", + "name": "metrics", + "connection": "conn-1", + "from": {"databaseName": "default"}, + "metricTables": { + "exponential histogram": "otel_metrics_exp_histogram", + "gauge": "otel_metrics_gauge", + "histogram": "otel_metrics_histogram", + "sum": "otel_metrics_sum", + "summary": "otel_metrics_summary" + }, + "resourceAttributesExpression": "ResourceAttributes", + "timestampValueExpression": "TimeUnix", + "minAutoGranularity": "1 minute", + }); + let response: ClickStackMetricSourceResponse = serde_json::from_value(metric.clone()).unwrap(); + assert_eq!(response.min_auto_granularity.as_deref(), Some("1 minute")); + let request = ClickStackMetricSource::try_from(response).unwrap(); + assert_eq!(request.min_auto_granularity.as_deref(), Some("1 minute")); + assert_eq!(serde_json::to_value(&request).unwrap(), metric); + + let promql = serde_json::json!({ + "kind": "promql", + "name": "prometheus", + "connection": "conn-1", + "from": {"databaseName": "default", "tableName": "metrics"}, + "timestampValueExpression": "timestamp", + "minAutoGranularity": "15 second", + }); + let response: ClickStackPromqlSourceResponse = serde_json::from_value(promql.clone()).unwrap(); + assert_eq!(response.min_auto_granularity.as_deref(), Some("15 second")); + let request = ClickStackPromqlSource::try_from(response).unwrap(); + assert_eq!(request.min_auto_granularity.as_deref(), Some("15 second")); + assert_eq!(serde_json::to_value(&request).unwrap(), promql); + + // Unset means no minimum and stays off the wire. + let mut without = request; + without.min_auto_granularity = None; + assert!( + serde_json::to_value(&without) + .unwrap() + .get("minAutoGranularity") + .is_none() + ); + for wire in [ + serde_json::json!({}), + serde_json::json!({"minAutoGranularity": null}), + ] { + let response: ClickStackPromqlSourceResponse = serde_json::from_value(wire).unwrap(); + assert_eq!(response.min_auto_granularity, None); + } +} + +#[test] +fn clickstack_casl_permission_subject_app_round_trips() { + let subject: ClickStackCASLPermissionSubject = + serde_json::from_value(serde_json::json!("App")).unwrap(); + assert_eq!(subject, ClickStackCASLPermissionSubject::App); + assert_eq!(subject.to_string(), "App"); + assert_eq!(serde_json::to_value(&subject).unwrap(), "App"); +} + +#[test] +fn clickstack_list_alerts_filter_enums_use_wire_values() { + for (value, wire) in [ + (ClickStackListAlertsSource::Saved_search, "saved_search"), + (ClickStackListAlertsSource::Tile, "tile"), + (ClickStackListAlertsSource::Inline, "inline"), + ] { + assert_eq!(value.to_string(), wire); + assert_eq!(serde_json::to_value(&value).unwrap(), wire); + assert_eq!( + serde_json::from_value::(serde_json::json!(wire)).unwrap(), + value + ); + } + for (value, wire) in [ + (ClickStackListAlertsState::Alert, "ALERT"), + (ClickStackListAlertsState::Ok, "OK"), + ( + ClickStackListAlertsState::Insufficient_data, + "INSUFFICIENT_DATA", + ), + (ClickStackListAlertsState::Disabled, "DISABLED"), + (ClickStackListAlertsState::Pending, "PENDING"), + ] { + assert_eq!(value.to_string(), wire); + assert_eq!(serde_json::to_value(&value).unwrap(), wire); + assert_eq!( + serde_json::from_value::(serde_json::json!(wire)).unwrap(), + value + ); + } +} diff --git a/crates/clickhousectl/src/cloud/clickstack.rs b/crates/clickhousectl/src/cloud/clickstack.rs index 14257ceb6..182f7ff50 100644 --- a/crates/clickhousectl/src/cloud/clickstack.rs +++ b/crates/clickhousectl/src/cloud/clickstack.rs @@ -1684,7 +1684,8 @@ impl CloudClient { ) -> CloudResult> { let response = self .api() - .click_stack_list_alerts(org_id, service_id, limit, offset) + // Filters are not exposed by `cloud clickstack alert list` yet. + .click_stack_list_alerts(org_id, service_id, limit, offset, &[], None, &[], &[]) .await .map_err(|error| self.convert_error_for_organization(error, org_id))?; Self::unwrap_response(response) diff --git a/crates/clickhousectl/tests/cloud/clickstack.rs b/crates/clickhousectl/tests/cloud/clickstack.rs index 50a6a4847..7cb59e613 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}; +use wiremock::matchers::{method, path, query_param_is_missing}; use wiremock::{Mock, MockServer, ResponseTemplate}; use crate::support::*; @@ -1105,8 +1105,13 @@ async fn clickstack_webhook_validate_posts_full_body_and_reports_results() { async fn clickstack_alert_list_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. Mock::given(method("GET")) .and(path(alerts)) + .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":[]},