Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions crates/clickhouse-cloud-api/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
30 changes: 30 additions & 0 deletions crates/clickhouse-cloud-api/src/client/clickstack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i64>,
offset: Option<i64>,
tag: &[&str],
search: Option<&str>,
source: &[ClickStackListAlertsSource],
state: &[ClickStackListAlertsState],
) -> Result<ApiResponse<Vec<ClickStackAlertResponse>>, Error> {
let mut req = self.request(
&operations::CLICK_STACK_LIST_ALERTS,
Expand All @@ -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?;
Expand Down
2 changes: 2 additions & 0 deletions crates/clickhouse-cloud-api/src/convert/clickstack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,7 @@ impl TryFrom<ClickStackMetricSourceResponse> 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
Expand Down Expand Up @@ -441,6 +442,7 @@ impl TryFrom<ClickStackPromqlSourceResponse> for ClickStackPromqlSource {
from: from.try_into()?,
id: value.id,
kind,
min_auto_granularity: value.min_auto_granularity,
name,
query_settings: value
.query_settings
Expand Down
70 changes: 70 additions & 0 deletions crates/clickhouse-cloud-api/src/models/clickstack/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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.
Expand All @@ -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}"),
}
Expand Down
22 changes: 22 additions & 0 deletions crates/clickhouse-cloud-api/src/models/clickstack/sources.rs
Original file line number Diff line number Diff line change
Expand Up @@ -546,6 +546,11 @@ pub struct ClickStackMetricSource {
pub log_source_id: Option<String>,
#[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<String>,
pub name: String,
#[serde(rename = "querySettings", skip_serializing_if = "Option::is_none")]
pub query_settings: Option<Vec<ClickStackQuerySetting>>,
Expand Down Expand Up @@ -578,6 +583,11 @@ pub struct ClickStackMetricSourceResponse {
pub log_source_id: Option<String>,
#[serde(rename = "metricTables", skip_serializing_if = "Option::is_none")]
pub metric_tables: Option<ClickStackMetricTablesResponse>,
/// 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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "querySettings", skip_serializing_if = "Option::is_none")]
Expand Down Expand Up @@ -661,6 +671,12 @@ pub struct ClickStackPromqlSource {
#[serde(skip_serializing_if = "Option::is_none")]
pub id: Option<String>,
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<String>,
pub name: String,
#[serde(rename = "querySettings", skip_serializing_if = "Option::is_none")]
pub query_settings: Option<Vec<ClickStackQuerySetting>>,
Expand All @@ -687,6 +703,12 @@ pub struct ClickStackPromqlSourceResponse {
pub id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub kind: Option<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<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(rename = "querySettings", skip_serializing_if = "Option::is_none")]
Expand Down
94 changes: 90 additions & 4 deletions crates/clickhouse-cloud-api/tests/client/clickstack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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"
Expand All @@ -589,14 +668,20 @@ 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,
});
let resp = c
.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]
Expand Down Expand Up @@ -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,
});
Expand Down Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions crates/clickhouse-cloud-api/tests/model_facade_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ fn extracted_models_keep_root_and_models_paths() {
PhantomData::<api::PgStandbyCount>,
PhantomData::<api::models::PgStandbyCount>,
);
assert_same_type(
PhantomData::<api::ClickStackListAlertsSource>,
PhantomData::<api::models::ClickStackListAlertsSource>,
);
assert_same_type(
PhantomData::<api::ClickStackListAlertsState>,
PhantomData::<api::models::ClickStackListAlertsState>,
);
assert_same_type(
PhantomData::<api::PostgresBackup>,
PhantomData::<api::models::PostgresBackup>,
Expand Down
Loading
Loading